Skip to content

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

feat: add agent sessions and scoped activity monitoring

Luigi Agostie9bb9d627e1f
diff --git a/cmd/pinchtab/cmd_session.go b/cmd/pinchtab/cmd_session.go
index 32a14695..5a83efc7 100644
--- a/cmd/pinchtab/cmd_session.go
+++ b/cmd/pinchtab/cmd_session.go
@@ -1,6 +1,9 @@
package main
import (
+ "fmt"
+ "os"
+
"github.com/pinchtab/pinchtab/internal/cli/apiclient"
"github.com/spf13/cobra"
)
@@ -16,11 +19,54 @@ func init() {
Short: "Show current agent session details",
Run: func(cmd *cobra.Command, args []string) {
runCLI(func(rt cliRuntime) {
- apiclient.DoGet(rt.client, rt.base, rt.token, "/api/sessions/me", nil)
+ apiclient.DoGet(rt.client, rt.base, rt.token, "/sessions/me", nil)
+ })
+ },
+ }
+
+ listCmd := &cobra.Command{
+ Use: "list",
+ Short: "List all agent sessions",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ apiclient.DoGet(rt.client, rt.base, rt.token, "/sessions", nil)
+ })
+ },
+ }
+
+ createCmd := &cobra.Command{
+ Use: "create",
+ Short: "Create a new agent session",
+ Run: func(cmd *cobra.Command, args []string) {
+ agentID, _ := cmd.Flags().GetString("agent-id")
+ label, _ := cmd.Flags().GetString("label")
+ if agentID == "" {
+ fmt.Fprintln(os.Stderr, "Error: --agent-id is required")
+ os.Exit(1)
+ }
+ body := map[string]any{"agentId": agentID}
+ if label != "" {
+ body["label"] = label
+ }
+ runCLI(func(rt cliRuntime) {
+ apiclient.DoPost(rt.client, rt.base, rt.token, "/sessions", body)
+ })
+ },
+ }
+ createCmd.Flags().String("agent-id", "", "Agent ID to associate with the session (required)")
+ createCmd.Flags().String("label", "", "Optional human-readable label")
+
+ revokeCmd := &cobra.Command{
+ Use: "revoke <session-id>",
+ Short: "Revoke an agent session",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ apiclient.DoPost(rt.client, rt.base, rt.token, "/sessions/"+args[0]+"/revoke", nil)
})
},
}
- sessionCmd.AddCommand(infoCmd)
+ sessionCmd.AddCommand(infoCmd, listCmd, createCmd, revokeCmd)
rootCmd.AddCommand(sessionCmd)
}
diff --git a/cmd/pinchtab/cmd_session_test.go b/cmd/pinchtab/cmd_session_test.go
new file mode 100644
index 00000000..5cbce491
--- /dev/null
+++ b/cmd/pinchtab/cmd_session_test.go
@@ -0,0 +1,182 @@
+package main
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+)
+
+// sessionServer captures the last request and serves a canned JSON response.
+type sessionServer struct {
+ server *httptest.Server
+ lastMethod string
+ lastPath string
+ lastBody string
+ response string
+ status int
+}
+
+func newSessionServer(response string, status int) *sessionServer {
+ s := &sessionServer{response: response, status: status}
+ s.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ s.lastMethod = r.Method
+ s.lastPath = r.URL.Path
+ if r.Body != nil {
+ body, _ := io.ReadAll(r.Body)
+ s.lastBody = string(body)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(s.status)
+ _, _ = w.Write([]byte(s.response))
+ }))
+ return s
+}
+
+func (s *sessionServer) close() { s.server.Close() }
+
+func (s *sessionServer) rt() cliRuntime {
+ return cliRuntime{
+ client: &http.Client{},
+ base: s.server.URL,
+ token: "test-token",
+ }
+}
+
+func TestSessionCLI_Create_SendsCorrectRequest(t *testing.T) {
+ srv := newSessionServer(
+ `{"id":"ses_abc","agentId":"agent-1","label":"ci","sessionToken":"ses_newtoken","status":"active"}`,
+ http.StatusCreated,
+ )
+ defer srv.close()
+
+ out := captureStdout(t, func() {
+ rt := srv.rt()
+ apiclient.DoPost(rt.client, rt.base, rt.token, "/sessions", map[string]any{"agentId": "agent-1", "label": "ci"})
+ })
+
+ if srv.lastMethod != "POST" {
+ t.Fatalf("method = %q, want POST", srv.lastMethod)
+ }
+ if srv.lastPath != "/sessions" {
+ t.Fatalf("path = %q, want /sessions", srv.lastPath)
+ }
+ var sent map[string]any
+ if err := json.Unmarshal([]byte(srv.lastBody), &sent); err != nil {
+ t.Fatalf("unmarshal body: %v", err)
+ }
+ if sent["agentId"] != "agent-1" {
+ t.Fatalf("agentId = %q, want agent-1", sent["agentId"])
+ }
+ if sent["label"] != "ci" {
+ t.Fatalf("label = %q, want ci", sent["label"])
+ }
+ if !strings.Contains(out, "ses_newtoken") {
+ t.Fatalf("expected sessionToken in output, got:\n%s", out)
+ }
+}
+
+func TestSessionCLI_Create_NoLabel_OmitsField(t *testing.T) {
+ srv := newSessionServer(
+ `{"id":"ses_abc","agentId":"agent-1","sessionToken":"ses_newtoken","status":"active"}`,
+ http.StatusCreated,
+ )
+ defer srv.close()
+
+ captureStdout(t, func() {
+ rt := srv.rt()
+ apiclient.DoPost(rt.client, rt.base, rt.token, "/sessions", map[string]any{"agentId": "agent-1"})
+ })
+
+ var sent map[string]any
+ if err := json.Unmarshal([]byte(srv.lastBody), &sent); err != nil {
+ t.Fatalf("unmarshal body: %v", err)
+ }
+ if _, hasLabel := sent["label"]; hasLabel {
+ t.Fatal("expected label to be absent when not provided")
+ }
+}
+
+func TestSessionCLI_List_SendsCorrectRequest(t *testing.T) {
+ srv := newSessionServer(`[]`, http.StatusOK)
+ defer srv.close()
+
+ captureStdout(t, func() {
+ rt := srv.rt()
+ apiclient.DoGet(rt.client, rt.base, rt.token, "/sessions", nil)
+ })
+
+ if srv.lastMethod != "GET" {
+ t.Fatalf("method = %q, want GET", srv.lastMethod)
+ }
+ if srv.lastPath != "/sessions" {
+ t.Fatalf("path = %q, want /sessions", srv.lastPath)
+ }
+}
+
+func TestSessionCLI_Info_SendsCorrectRequest(t *testing.T) {
+ srv := newSessionServer(`{"id":"ses_abc","agentId":"agent-1","status":"active"}`, http.StatusOK)
+ defer srv.close()
+
+ captureStdout(t, func() {
+ rt := srv.rt()
+ apiclient.DoGet(rt.client, rt.base, rt.token, "/sessions/me", nil)
+ })
+
+ if srv.lastMethod != "GET" {
+ t.Fatalf("method = %q, want GET", srv.lastMethod)
+ }
+ if srv.lastPath != "/sessions/me" {
+ t.Fatalf("path = %q, want /sessions/me", srv.lastPath)
+ }
+}
+
+func TestSessionCLI_Revoke_SendsCorrectRequest(t *testing.T) {
+ srv := newSessionServer(`{"status":"ok"}`, http.StatusOK)
+ defer srv.close()
+
+ const sessionID = "ses_abc123"
+
+ captureStdout(t, func() {
+ rt := srv.rt()
+ apiclient.DoPost(rt.client, rt.base, rt.token, "/sessions/"+sessionID+"/revoke", nil)
+ })
+
+ if srv.lastMethod != "POST" {
+ t.Fatalf("method = %q, want POST", srv.lastMethod)
+ }
+ if srv.lastPath != "/sessions/"+sessionID+"/revoke" {
+ t.Fatalf("path = %q, want /sessions/%s/revoke", srv.lastPath, sessionID)
+ }
+}
+
+func TestSessionCLI_Info_SendsSessionAuthHeader(t *testing.T) {
+ srv := newSessionServer(`{"id":"ses_abc","agentId":"agent-1","status":"active"}`, http.StatusOK)
+ defer srv.close()
+
+ var gotAuth string
+ srv.server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotAuth = r.Header.Get("Authorization")
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{"id":"ses_abc","agentId":"agent-1","status":"active"}`))
+ })
+
+ const sessionToken = "ses_mytoken"
+ captureStdout(t, func() {
+ rt := cliRuntime{
+ client: &http.Client{},
+ base: srv.server.URL,
+ token: sessionToken,
+ }
+ apiclient.DoGet(rt.client, rt.base, rt.token, "/sessions/me", nil)
+ })
+
+ if gotAuth != "Session "+sessionToken {
+ t.Fatalf("Authorization = %q, want %q", gotAuth, "Session "+sessionToken)
+ }
+}
diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx
index 80893682..2f5086c3 100644
--- a/dashboard/src/App.tsx
+++ b/dashboard/src/App.tsx
@@ -11,7 +11,11 @@ import { ActivityPage, AgentsPage } from "./activities";
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 {
+ AUTH_REQUIRED_EVENT,
+ AUTH_STATE_CHANGED_EVENT,
+ SERVER_UNREACHABLE_EVENT,
+} from "./services/auth";
import { acquireDashboardRealtime } from "./services/dashboardRealtime";
import { useAppStore } from "./stores/useAppStore";
@@ -106,15 +110,23 @@ function AppContent() {
setAuthMode("probing");
setAuthRetryCount(0);
};
+ const handleServerUnreachable = () => {
+ setAuthMode("unreachable");
+ };
window.addEventListener(AUTH_REQUIRED_EVENT, handleAuthRequired);
window.addEventListener(AUTH_STATE_CHANGED_EVENT, handleAuthStateChanged);
+ window.addEventListener(SERVER_UNREACHABLE_EVENT, handleServerUnreachable);
return () => {
window.removeEventListener(AUTH_REQUIRED_EVENT, handleAuthRequired);
window.removeEventListener(
AUTH_STATE_CHANGED_EVENT,
handleAuthStateChanged,
);
+ window.removeEventListener(
+ SERVER_UNREACHABLE_EVENT,
+ handleServerUnreachable,
+ );
};
}, [location.pathname, navigate]);
diff --git a/dashboard/src/activities/ActivityExplorer.tsx b/dashboard/src/activities/ActivityExplorer.tsx
index e8b90d18..eebb7a96 100644
--- a/dashboard/src/activities/ActivityExplorer.tsx
+++ b/dashboard/src/activities/ActivityExplorer.tsx
@@ -13,6 +13,20 @@ import {
} from "./helpers";
import type { ActivityFilters, DashboardActivityEvent } from "./types";
+const ANONYMOUS_AGENT_ID = "anonymous";
+
+function normalizeDashboardActivityEvent(
+ event: DashboardActivityEvent,
+): DashboardActivityEvent {
+ const source = (event.source || "").trim().toLowerCase();
+ const agentId = (event.agentId || "").trim();
+ return {
+ ...event,
+ source,
+ agentId: source === "client" && !agentId ? ANONYMOUS_AGENT_ID : agentId,
+ };
+}
+
interface Props {
initialFilters?: Partial<ActivityFilters>;
lockedFilters?: Partial<ActivityFilters>;
@@ -47,14 +61,33 @@ export default function ActivityExplorer({
() => applyLockedFilters(deferredFilters, lockedFilters),
[deferredFilters, lockedFilters],
);
- const query = useMemo(
- () => buildActivityQuery(effectiveFilters),
- [effectiveFilters],
- );
+ const query = useMemo(() => {
+ const q = buildActivityQuery(effectiveFilters);
+ if (embedded) {
+ q.source = "client";
+ }
+ return q;
+ }, [effectiveFilters, embedded]);
const queryKey = JSON.stringify(query);
const stableQuery = useRef(query);
stableQuery.current = query;
+ const [sessions, setSessions] = useState<api.Session[]>([]);
+
+ useEffect(() => {
+ if (!embedded) return;
+ let cancelled = false;
+ void api
+ .fetchSessions()
+ .then((s) => {
+ if (!cancelled) setSessions(s);
+ })
+ .catch(() => {});
+ return () => {
+ cancelled = true;
+ };
+ }, [embedded]);
+
useEffect(() => {
setFilters((current) => {
const next = {
@@ -93,7 +126,7 @@ export default function ActivityExplorer({
try {
const response = await fetchActivity(stableQuery.current);
if (cancelled) return;
- setEvents(response.events);
+ setEvents(response.events.map(normalizeDashboardActivityEvent));
setCount(response.count);
} catch (err) {
if (cancelled) return;
@@ -155,6 +188,25 @@ export default function ActivityExplorer({
[count, stats.agents, stats.instances, stats.tabs, embedded],
);
+ const agentOptions = useMemo(() => {
+ const ids = new Set<string>();
+ for (const e of events) {
+ const agentId = (e.agentId || "").trim();
+ if (agentId) ids.add(agentId);
+ }
+ return Array.from(ids).sort();
+ }, [events]);
+
+ const sessionOptions = useMemo(() => {
+ if (!effectiveFilters.agentId) return [];
+ return sessions
+ .filter((s) => s.agentId === effectiveFilters.agentId)
+ .sort(
+ (a, b) =>
+ new Date(b.lastSeenAt).getTime() - new Date(a.lastSeenAt).getTime(),
+ );
+ }, [sessions, effectiveFilters.agentId]);
+
const updateFilter = (key: keyof ActivityFilters, value: string) => {
if (lockedFilters?.[key] !== undefined) {
return;
@@ -216,6 +268,7 @@ export default function ActivityExplorer({
profileOptions={profiles}
instanceOptions={filteredInstances}
tabOptions={visibleTabs}
+ agentOptions={agentOptions}
loading={loading}
onClear={clearFilters}
onRefresh={() => setFilters((current) => ({ ...current }))}
@@ -226,12 +279,55 @@ export default function ActivityExplorer({
</aside>
)}
+ {embedded && agentOptions.length > 0 && (
+ <div className="flex items-center gap-2 border-b border-border-subtle px-4 py-1.5">
+ <label className="flex items-center gap-1.5 text-xs text-text-muted">
+ Agent
+ <select
+ value={effectiveFilters.agentId}
+ onChange={(e) => {
+ updateFilter("agentId", e.target.value);
+ if (!e.target.value) updateFilter("sessionId", "");
+ }}
+ className="rounded border border-border-subtle bg-bg-surface px-2 py-1 text-xs text-text-primary"
+ >
+ <option value="">All</option>
+ {agentOptions.map((id) => (
+ <option key={id} value={id}>
+ {id}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="flex items-center gap-1.5 text-xs text-text-muted">
+ Session
+ <select
+ value={effectiveFilters.sessionId}
+ onChange={(e) => updateFilter("sessionId", e.target.value)}
+ disabled={!effectiveFilters.agentId}
+ className="rounded border border-border-subtle bg-bg-surface px-2 py-1 text-xs text-text-primary disabled:opacity-40"
+ >
+ <option value="">All</option>
+ {sessionOptions.map((s) => (
+ <option key={s.id} value={s.id}>
+ {s.label || s.id}
+ </option>
+ ))}
+ </select>
+ </label>
+ <span className="ml-auto text-[0.68rem] text-text-muted">
+ {summary}
+ </span>
+ </div>
+ )}
+
<ActivityTimeline
events={events}
loading={loading}
error={error}
summary={summary}
embedded={embedded}
+ showTab={!embedded}
onFilterChange={updateFilter}
/>
</div>
diff --git a/dashboard/src/activities/ActivityFilterMenu.tsx b/dashboard/src/activities/ActivityFilterMenu.tsx
index a8d47c48..7ef23be3 100644
--- a/dashboard/src/activities/ActivityFilterMenu.tsx
+++ b/dashboard/src/activities/ActivityFilterMenu.tsx
@@ -9,6 +9,7 @@ interface Props {
profileOptions: Profile[];
instanceOptions: Instance[];
tabOptions: InstanceTab[];
+ agentOptions?: string[];
loading: boolean;
showAgentFilter?: boolean;
onClear: () => void;
@@ -36,7 +37,7 @@ function FilterSelect({
aria-label={label}
value={value}
onChange={onChange}
- className="rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.72)] px-3 py-2 text-sm text-text-primary transition-all duration-150 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20"
+ className="appearance-none rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.72)] bg-[url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2020%2020%22%20fill%3D%22%236b7280%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20d%3D%22M5.23%207.21a.75.75%200%20011.06.02L10%2011.168l3.71-3.938a.75.75%200%20111.08%201.04l-4.25%204.5a.75.75%200%2001-1.08%200l-4.25-4.5a.75.75%200%2001.02-1.06z%22%20clip-rule%3D%22evenodd%22%2F%3E%3C%2Fsvg%3E')] bg-[length:1.25rem_1.25rem] bg-[position:right_0.5rem_center] bg-no-repeat pl-3 pr-8 py-2 text-sm text-text-primary transition-all duration-150 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20"
>
{options.map((option) => (
<option key={option.value || "all"} value={option.value}>
@@ -53,6 +54,7 @@ export default function ActivityFilterMenu({
profileOptions,
instanceOptions,
tabOptions,
+ agentOptions = [],
loading,
showAgentFilter = true,
onClear,
@@ -95,10 +97,13 @@ export default function ActivityFilterMenu({
<div className="space-y-3 border-t border-border-subtle pt-4">
{showAgentFilter && (
- <Input
+ <FilterSelect
label="Agent"
- placeholder="cli, mcp, custom"
value={filters.agentId}
+ options={[
+ { value: "", label: "Any agent" },
+ ...agentOptions.map((id) => ({ value: id, label: id })),
+ ]}
onChange={(event) =>
onFilterChange("agentId", event.target.value)
}
@@ -147,14 +152,6 @@ export default function ActivityFilterMenu({
]}
onChange={(event) => onInstanceChange(event.target.value)}
/>
- <Input
- label="Session"
- placeholder="session_xxx"
- value={filters.sessionId}
- onChange={(event) =>
- onFilterChange("sessionId", event.target.value)
- }
- />
<Input
label="Path prefix"
placeholder="/tabs/ or /instances/"
@@ -201,7 +198,7 @@ export default function ActivityFilterMenu({
loading={loading}
className="flex-1"
>
- Refresh
+ Search
</Button>
</div>
</>
diff --git a/dashboard/src/activities/ActivityItemLine.tsx b/dashboard/src/activities/ActivityItemLine.tsx
new file mode 100644
index 00000000..1f574085
--- /dev/null
+++ b/dashboard/src/activities/ActivityItemLine.tsx
@@ -0,0 +1,160 @@
+import {
+ IconCamera,
+ IconCompass,
+ IconFileText,
+ IconHandClick,
+ IconKeyboard,
+ IconMessageCircle,
+ IconPointer,
+ IconScreenShare,
+} from "../components/atoms/Icon";
+import { 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 }: { event: DashboardActivityEvent }) {
+ if (event.channel === "progress") return <IconMessageCircle />;
+ if (event.action === "click" || event.action === "dblclick")
+ return <IconHandClick />;
+ if (event.action === "type") return <IconKeyboard />;
+ if (event.action === "hover") return <IconPointer />;
+ if (event.path.includes("/navigate")) return <IconCompass />;
+ if (event.path.includes("/snapshot")) return <IconCamera />;
+ if (event.path.includes("/screencast")) return <IconScreenShare />;
+ return <IconFileText />;
+}
+
+function quoted(value: string): string {
+ return `"${value}"`;
+}
+
+function eventDescription(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";
+ }
+ if (event.path.includes("/screenshot")) {
+ return "Take screenshot";
+ }
+ if (event.path.includes("/pdf")) {
+ return "Export page as PDF";
+ }
+ 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";
+ case "fill":
+ return event.ref ? `Fill ${quoted(event.ref)}` : "Fill field";
+ case "select":
+ return event.ref ? `Select ${quoted(event.ref)}` : "Select option";
+ case "scroll":
+ return "Scroll page";
+ case "press":
+ return event.ref ? `Press key on ${quoted(event.ref)}` : "Press key";
+ case "wait":
+ return "Wait for condition";
+ case "evaluate":
+ return "Evaluate JavaScript";
+ case "upload":
+ return "Upload file";
+ case "download":
+ return "Download file";
+ default:
+ if (event.action) {
+ return `${event.action} ${event.ref ? quoted(event.ref) : ""}`.trim();
+ }
+ return `${event.method} ${event.path}`;
+ }
+}
+
+const statusColor: Record<string, string> = {
+ success: "text-success",
+ warning: "text-warning",
+ danger: "text-destructive",
+ default: "text-text-muted",
+};
+
+interface Props {
+ event: DashboardActivityEvent;
+ showTab?: boolean;
+ copyTabId?: boolean;
+ sessionLabel?: string;
+ onFilterChange?: (key: keyof ActivityFilters, value: string) => void;
+}
+
+export default function ActivityItemLine({
+ event,
+ showTab = true,
+ copyTabId = false,
+ sessionLabel,
+ onFilterChange,
+}: Props) {
+ const variant = activityStatusVariant(event.status);
+
+ return (
+ <div className="flex items-center gap-2.5 px-4 py-2 text-sm transition-colors hover:bg-white/2">
+ <span className="shrink-0 text-text-muted">
+ <EventIcon event={event} />
+ </span>
+
+ <span className="dashboard-mono w-16 shrink-0 text-[0.68rem] text-text-muted">
+ {formatTime(event.timestamp)}
+ </span>
+
+ <span className="min-w-0 flex-1 truncate text-text-primary">
+ {eventDescription(event)}
+ </span>
+
+ {sessionLabel && (
+ <span className="truncate rounded-sm border border-border-subtle bg-white/3 px-1.5 py-0.5 text-[0.68rem] text-text-muted">
+ {sessionLabel}
+ </span>
+ )}
+
+ {showTab &&
+ event.tabId &&
+ onFilterChange &&
+ (copyTabId ? (
+ <CopyIdPill id={event.tabId} compact />
+ ) : (
+ <FilterPill
+ label={`tab:${event.tabId}`}
+ onClick={() => onFilterChange("tabId", event.tabId || "")}
+ />
+ ))}
+
+ <span
+ className={`dashboard-mono shrink-0 text-[0.68rem] ${statusColor[variant] || "text-text-muted"}`}
+ >
+ {event.status}
+ </span>
+ </div>
+ );
+}
diff --git a/dashboard/src/activities/ActivityPage.test.tsx b/dashboard/src/activities/ActivityPage.test.tsx
index 75b0dedc..9dd9c4ca 100644
--- a/dashboard/src/activities/ActivityPage.test.tsx
+++ b/dashboard/src/activities/ActivityPage.test.tsx
@@ -79,7 +79,7 @@ describe("ActivityPage", () => {
events: [
{
timestamp: now,
- source: "cli",
+ source: "client",
requestId: "req_123",
agentId: "cli",
instanceId: "inst_123",
@@ -106,12 +106,12 @@ describe("ActivityPage", () => {
expect(fetchActivity).toHaveBeenCalled();
});
- expect(screen.getByText("/tabs/tab_123/action")).toBeInTheDocument();
- expect(screen.getByText("agent:cli")).toBeInTheDocument();
+ expect(screen.getByText("Click on page")).toBeInTheDocument();
+ expect(screen.getByText("200")).toBeInTheDocument();
expect(screen.getAllByText("tab:tab_123").length).toBeGreaterThan(0);
});
- it("defaults to the current running profile and tab", async () => {
+ it("starts unfiltered showing all client events", async () => {
render(
<MemoryRouter>
<ActivityPage />
@@ -121,15 +121,20 @@ describe("ActivityPage", () => {
await waitFor(() => {
expect(fetchActivity).toHaveBeenCalledWith(
expect.objectContaining({
- profileName: "default",
- instanceId: "inst_123",
- tabId: "tab_123",
+ source: "client",
+ limit: 1000,
}),
);
});
+
+ const query = vi.mocked(fetchActivity).mock.calls[0][0];
+ expect(query).not.toHaveProperty("profileName");
+ expect(query).not.toHaveProperty("instanceId");
+ expect(query).not.toHaveProperty("tabId");
+ expect(query).not.toHaveProperty("ageSec");
});
- it("clears back to default filters instead of reapplying landing context", async () => {
+ it("clears back to unfiltered state", async () => {
render(
<MemoryRouter>
<ActivityPage />
@@ -137,33 +142,30 @@ describe("ActivityPage", () => {
);
await waitFor(() => {
- expect(fetchActivity).toHaveBeenCalledWith(
- expect.objectContaining({
- profileName: "default",
- instanceId: "inst_123",
- tabId: "tab_123",
- }),
- );
+ expect(fetchActivity).toHaveBeenCalledTimes(1);
});
- await userEvent.click(screen.getByRole("button", { name: "Clear" }));
+ await userEvent.click(
+ screen.getByRole("button", { name: /advanced filters/i }),
+ );
+ await userEvent.selectOptions(
+ screen.getByLabelText("Instance"),
+ "inst_123",
+ );
await waitFor(() => {
expect(fetchActivity).toHaveBeenLastCalledWith(
- expect.objectContaining({
- ageSec: 3600,
- limit: 200,
- }),
+ expect.objectContaining({ instanceId: "inst_123" }),
);
});
- expect(vi.mocked(fetchActivity).mock.lastCall?.[0]).not.toEqual(
- expect.objectContaining({
- profileName: "default",
- instanceId: "inst_123",
- tabId: "tab_123",
- }),
- );
+ await userEvent.click(screen.getByRole("button", { name: "Clear" }));
+
+ await waitFor(() => {
+ const lastQuery = vi.mocked(fetchActivity).mock.lastCall?.[0];
+ expect(lastQuery).not.toHaveProperty("instanceId");
+ expect(lastQuery).not.toHaveProperty("profileName");
+ });
});
it("applies the tab filter from the dropdown filter panel", async () => {
@@ -215,6 +217,6 @@ describe("ActivityPage", () => {
);
expect(screen.getByLabelText("Instance")).toBeInTheDocument();
- expect(screen.getByLabelText("Session")).toBeInTheDocument();
+ expect(screen.queryByLabelText("Session")).not.toBeInTheDocument();
});
});
diff --git a/dashboard/src/activities/ActivityPage.tsx b/dashboard/src/activities/ActivityPage.tsx
index dd083870..4695eef7 100644
--- a/dashboard/src/activities/ActivityPage.tsx
+++ b/dashboard/src/activities/ActivityPage.tsx
@@ -1,6 +1,5 @@
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useMemo } from "react";
import { useLocation } from "react-router-dom";
-import { useAppStore } from "../stores/useAppStore";
import type { ActivityFilters } from "./types";
import AgentActivityWorkspace from "./AgentActivityWorkspace";
@@ -10,120 +9,24 @@ interface ActivityPageLocationState {
tabId?: string;
}
-function hasInitialSelection(filters: Partial<ActivityFilters>): boolean {
- return Boolean(filters.profileName || filters.instanceId || filters.tabId);
-}
-
export default function ActivityPage() {
const location = useLocation();
- const { profiles, instances, currentTabs } = useAppStore();
const routeState = location.state as ActivityPageLocationState | null;
- const locationKeyRef = useRef(location.key);
- const routeInitialFilters = useMemo<Partial<ActivityFilters>>(
+ const initialFilters = useMemo<Partial<ActivityFilters>>(
() => ({
profileName: routeState?.profileName ?? "",
instanceId: routeState?.instanceId ?? "",
tabId: routeState?.tabId ?? "",
+ ageSec: "",
+ limit: "1000",
}),
[routeState],
);
- const derivedInitialFilters = useMemo<Partial<ActivityFilters>>(() => {
- let profileName = routeInitialFilters.profileName ?? "";
- let instanceId = routeInitialFilters.instanceId ?? "";
- let tabId = routeInitialFilters.tabId ?? "";
-
- const runningInstances = instances.filter(
- (instance) => instance.status === "running",
- );
-
- let selectedInstance =
- (instanceId
- ? instances.find((instance) => instance.id === instanceId)
- : undefined) ?? null;
-
- if (!selectedInstance) {
- const candidateInstances = profileName
- ? runningInstances.filter(
- (instance) => instance.profileName === profileName,
- )
- : runningInstances;
- if (candidateInstances.length === 1) {
- selectedInstance = candidateInstances[0];
- }
- }
-
- if (!profileName) {
- if (selectedInstance) {
- profileName = selectedInstance.profileName;
- } else if (profiles.length === 1) {
- profileName = profiles[0].name;
- }
- }
-
- if (!selectedInstance && profileName) {
- const matchingInstances = runningInstances.filter(
- (instance) => instance.profileName === profileName,
- );
- if (matchingInstances.length === 1) {
- selectedInstance = matchingInstances[0];
- }
- }
-
- if (selectedInstance && !instanceId) {
- instanceId = selectedInstance.id;
- }
-
- if (!tabId && selectedInstance) {
- const activeTabs = currentTabs[selectedInstance.id] ?? [];
- if (activeTabs.length > 0) {
- tabId = activeTabs[0].id;
- }
- }
-
- return {
- profileName,
- instanceId,
- tabId,
- };
- }, [currentTabs, instances, profiles, routeInitialFilters]);
-
- const [initialFilters, setInitialFilters] = useState<
- Partial<ActivityFilters>
- >(() =>
- hasInitialSelection(routeInitialFilters)
- ? routeInitialFilters
- : derivedInitialFilters,
- );
- const [didAutoSelect, setDidAutoSelect] = useState<boolean>(
- () =>
- hasInitialSelection(routeInitialFilters) ||
- hasInitialSelection(derivedInitialFilters),
- );
-
- useEffect(() => {
- if (locationKeyRef.current === location.key) {
- return;
- }
- locationKeyRef.current = location.key;
- const nextInitialFilters = hasInitialSelection(routeInitialFilters)
- ? routeInitialFilters
- : derivedInitialFilters;
- setInitialFilters(nextInitialFilters);
- setDidAutoSelect(hasInitialSelection(nextInitialFilters));
- }, [derivedInitialFilters, location.key, routeInitialFilters]);
-
- useEffect(() => {
- if (didAutoSelect || !hasInitialSelection(derivedInitialFilters)) {
- return;
- }
- setInitialFilters(derivedInitialFilters);
- setDidAutoSelect(true);
- }, [derivedInitialFilters, didAutoSelect]);
-
return (
<AgentActivityWorkspace
+ key={location.key}
initialFilters={initialFilters}
defaultSidebarTab="activities"
preferKnownAgents
diff --git a/dashboard/src/activities/ActivityTimeline.tsx b/dashboard/src/activities/ActivityTimeline.tsx
index 88f4ba7a..fad91ce0 100644
--- a/dashboard/src/activities/ActivityTimeline.tsx
+++ b/dashboard/src/activities/ActivityTimeline.tsx
@@ -1,10 +1,6 @@
-import { Badge, EmptyState } from "../components/atoms";
+import { EmptyState } from "../components/atoms";
import type { DashboardActivityEvent, ActivityFilters } from "./types";
-import {
- activityMethodVariant,
- activityStatusVariant,
- formatActivityTimestamp,
-} from "./helpers";
+import ActivityItemLine from "./ActivityItemLine";
interface Props {
events: DashboardActivityEvent[];
@@ -12,44 +8,21 @@ interface Props {
error: string;
summary: string;
embedded?: boolean;
+ showTab?: boolean;
+ copyTabId?: boolean;
onFilterChange: (key: keyof ActivityFilters, value: string) => void;
}
-function FilterChip({
- label,
- onClick,
- className = "",
-}: {
- label: string;
- onClick: () => void;
- className?: string;
-}) {
- return (
- <button
- type="button"
- className={`rounded-sm border border-border-subtle bg-white/3 px-1.5 py-0.5 text-[0.62rem] font-semibold tracking-[0.08em] text-text-secondary transition-all hover:border-primary/30 hover:bg-primary/10 hover:text-primary ${className}`}
- onClick={onClick}
- title={label}
- >
- <span className="block truncate">{label}</span>
- </button>
- );
-}
-
export default function ActivityTimeline({
events,
loading,
error,
summary,
embedded = false,
+ showTab = true,
+ copyTabId = false,
onFilterChange,
}: Props) {
- const filteredEvents = embedded
- ? events.filter(
- (e) => !e.source || !["dashboard", "server"].includes(e.source),
- )
- : events;
-
return (
<section
className={`flex min-h-0 flex-1 flex-col overflow-hidden ${embedded ? "" : "dashboard-panel"}`}
@@ -75,7 +48,7 @@ export default function ActivityTimeline({
)}
<div className="min-h-0 flex-1 overflow-auto">
- {!loading && filteredEvents.length === 0 ? (
+ {!loading && events.length === 0 ? (
<EmptyState
icon="📜"
title="No matching activity"
@@ -83,90 +56,14 @@ export default function ActivityTimeline({
/>
) : (
<div className="divide-y divide-border-subtle/70">
- {filteredEvents.map((event, index) => (
- <div
+ {events.map((event, index) => (
+ <ActivityItemLine
key={`${event.requestId || event.timestamp}-${index}`}
- className="px-4 py-2 transition-colors hover:bg-white/2"
- >
- <div className="flex flex-wrap items-center gap-1.5">
- <span className="dashboard-mono text-[0.68rem] text-text-muted">
- {formatActivityTimestamp(event.timestamp)}
- </span>
- <Badge variant={activityMethodVariant(event.method)}>
- {event.method}
- </Badge>
- <Badge variant={activityStatusVariant(event.status)}>
- {event.status}
- </Badge>
- {event.source && <Badge>{event.source}</Badge>}
- {event.action && (
- <Badge variant="warning">{event.action}</Badge>
- )}
- {event.engine && <Badge variant="info">{event.engine}</Badge>}
- <span className="ml-auto dashboard-mono text-[0.68rem] text-text-muted">
- {event.durationMs} ms
- </span>
- </div>
-
- <div className="mt-1 grid grid-cols-1 gap-1.5 xl:grid-cols-[minmax(0,1fr)_20rem] xl:items-start">
- <div className="min-w-0">
- <div className="dashboard-mono break-all text-[0.82rem] text-text-primary">
- {event.path}
- </div>
- {event.tabId && (
- <div className="mt-1">
- <FilterChip
- label={`tab:${event.tabId}`}
- className="max-w-full xl:max-w-[18rem]"
- onClick={() =>
- onFilterChange("tabId", event.tabId || "")
- }
- />
- </div>
- )}
- {event.url && (
- <div className="dashboard-mono mt-0.5 break-all text-[0.68rem] text-text-muted">
- {event.url}
- </div>
- )}
- </div>
- <div className="dashboard-mono flex flex-wrap gap-1 text-[0.68rem] text-text-muted xl:justify-end">
- {event.agentId && (
- <FilterChip
- label={`agent:${event.agentId}`}
- onClick={() =>
- onFilterChange("agentId", event.agentId || "")
- }
- />
- )}
- {event.profileName && (
- <FilterChip
- label={`profile:${event.profileName}`}
- onClick={() =>
- onFilterChange("profileName", event.profileName || "")
- }
- />
- )}
- </div>
- </div>
-
- <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-[0.68rem] text-text-muted">
- {event.requestId && (
- <span className="dashboard-mono">{event.requestId}</span>
- )}
- {event.ref && (
- <span className="dashboard-mono">ref:{event.ref}</span>
- )}
- {event.actorId && (
- <span className="dashboard-mono">
- actor:{event.actorId}
- </span>
- )}
- {event.remoteAddr && (
- <span className="dashboard-mono">{event.remoteAddr}</span>
- )}
- </div>
- </div>
+ event={event}
+ showTab={showTab}
+ copyTabId={copyTabId}
+ onFilterChange={onFilterChange}
+ />
))}
</div>
)}
diff --git a/dashboard/src/activities/AgentActivityWorkspace.tsx b/dashboard/src/activities/AgentActivityWorkspace.tsx
index aa5855e7..88225042 100644
--- a/dashboard/src/activities/AgentActivityWorkspace.tsx
+++ b/dashboard/src/activities/AgentActivityWorkspace.tsx
@@ -13,6 +13,7 @@ import {
import type { ActivityFilters, DashboardActivityEvent } from "./types";
type WorkspaceTab = "agents" | "activities";
+const ANONYMOUS_AGENT_ID = "anonymous";
interface Props {
initialFilters?: Partial<ActivityFilters>;
@@ -22,7 +23,6 @@ interface Props {
requireSelectedAgent?: boolean;
showAllAgentsOption?: boolean;
showAgentFilter?: boolean;
- simplifyEventRows?: boolean;
copyTabId?: boolean;
preferKnownAgents?: boolean;
useAgentEventStore?: boolean;
@@ -49,7 +49,7 @@ function toDashboardActivityEvent(
event: ActivityEvent,
): DashboardActivityEvent {
const details = (event.details ?? {}) as Record<string, unknown>;
- return {
+ return normalizeDashboardActivityEvent({
channel: event.channel,
message: event.message,
progress: event.progress,
@@ -58,7 +58,6 @@ function toDashboardActivityEvent(
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,
@@ -72,27 +71,44 @@ function toDashboardActivityEvent(
action: detailString(details, "action"),
engine: detailString(details, "engine"),
ref: detailString(details, "ref"),
+ });
+}
+
+function normalizeDashboardActivityEvent(
+ event: DashboardActivityEvent,
+): DashboardActivityEvent {
+ const source = (event.source || "").trim().toLowerCase();
+ const agentId = (event.agentId || "").trim();
+ return {
+ ...event,
+ source,
+ agentId: source === "client" && !agentId ? ANONYMOUS_AGENT_ID : agentId,
};
}
+function eventIdentity(event: DashboardActivityEvent): string {
+ const agentId = (event.agentId || "").trim();
+ if (agentId) {
+ return agentId;
+ }
+ return "";
+}
+
function matchesVisibleEvent(
event: DashboardActivityEvent,
filters: ActivityFilters,
hiddenSources: string[],
requireAgentIdentity: boolean,
): boolean {
- if (hiddenSources.includes(event.source)) {
+ const source = (event.source || "").trim().toLowerCase();
+ const identity = eventIdentity(event);
+ if (source !== "client") {
return false;
}
- // Hide API management calls (sessions, activity queries, health) from the stream
- if (
- event.path.startsWith("/api/") ||
- event.path === "/health" ||
- event.path === "/metrics"
- ) {
+ if (hiddenSources.includes(source)) {
return false;
}
- if (requireAgentIdentity && !(event.agentId || "").trim()) {
+ if (requireAgentIdentity && !identity) {
return false;
}
if (filters.agentId && event.agentId !== filters.agentId) {
@@ -128,6 +144,34 @@ function matchesVisibleEvent(
return true;
}
+function withClearedSessionFilter(filters: ActivityFilters): ActivityFilters {
+ return {
+ ...filters,
+ sessionId: "",
+ };
+}
+
+function mergeDashboardActivityEvents(
+ first: DashboardActivityEvent[],
+ second: DashboardActivityEvent[],
+): DashboardActivityEvent[] {
+ const merged = new Map<string, DashboardActivityEvent>();
+
+ for (const event of first) {
+ const key = event.requestId || `${event.timestamp}:${event.path}`;
+ merged.set(key, event);
+ }
+ for (const event of second) {
+ const key = event.requestId || `${event.timestamp}:${event.path}`;
+ merged.set(key, event);
+ }
+
+ return [...merged.values()].sort(
+ (left, right) =>
+ new Date(left.timestamp).getTime() - new Date(right.timestamp).getTime(),
+ );
+}
+
export default function AgentActivityWorkspace({
initialFilters,
defaultSidebarTab = "agents",
@@ -136,14 +180,12 @@ export default function AgentActivityWorkspace({
requireSelectedAgent = false,
showAllAgentsOption = true,
showAgentFilter = true,
- simplifyEventRows = false,
copyTabId = false,
preferKnownAgents = false,
useAgentEventStore = false,
clearToInitialFilters = false,
}: Props) {
- const { instances, profiles, agents, agentEventsById, hydrateAgentEvents } =
- useAppStore();
+ const { instances, profiles, agents, agentEventsById } = useAppStore();
const normalizedHiddenSources = useMemo(
() => [...hiddenSources],
[hiddenSources],
@@ -158,9 +200,18 @@ export default function AgentActivityWorkspace({
const [sidebarTab, setSidebarTab] = useState<WorkspaceTab>(defaultSidebarTab);
const [filters, setFilters] = useState<ActivityFilters>(initialBaseFilters);
- const [activityEvents, setActivityEvents] = useState<
- DashboardActivityEvent[]
- >([]);
+ const [activityScopedAgentId, setActivityScopedAgentId] = useState(
+ initialBaseFilters.agentId,
+ );
+ const [activityScopedSessionId, setActivityScopedSessionId] = useState(
+ initialBaseFilters.sessionId,
+ );
+ const [catalogEvents, setCatalogEvents] = useState<DashboardActivityEvent[]>(
+ [],
+ );
+ const [threadEvents, setThreadEvents] = useState<DashboardActivityEvent[]>(
+ [],
+ );
const [tabs, setTabs] = useState<InstanceTab[]>([]);
const [activityLoading, setActivityLoading] = useState(false);
const [agentLoading, setAgentLoading] = useState(false);
@@ -168,13 +219,27 @@ export default function AgentActivityWorkspace({
const [error, setError] = useState("");
const [refreshNonce, setRefreshNonce] = useState(0);
- const deferredFilters = useDeferredValue(filters);
- const activityQuery = useMemo(
- () => buildActivityQuery(deferredFilters),
- [deferredFilters],
- );
- const activityQueryKey = JSON.stringify(activityQuery);
const usesAgentThreadView = useAgentEventStore && sidebarTab === "agents";
+ const deferredFilters = useDeferredValue(filters);
+ const catalogQuery = useMemo(() => {
+ const q = buildActivityQuery(deferredFilters);
+ if (usesAgentThreadView) {
+ delete q.agentId;
+ delete q.sessionId;
+ }
+ q.source = "client";
+ return q;
+ }, [deferredFilters, usesAgentThreadView]);
+ const catalogQueryKey = JSON.stringify(catalogQuery);
+ const threadQuery = useMemo(() => {
+ if (!usesAgentThreadView || !deferredFilters.agentId.trim()) {
+ return null;
+ }
+ const q = buildActivityQuery(withClearedSessionFilter(deferredFilters));
+ q.source = "client";
+ return q;
+ }, [deferredFilters, usesAgentThreadView]);
+ const threadQueryKey = JSON.stringify(threadQuery);
useEffect(() => {
setSidebarTab(defaultSidebarTab);
@@ -185,6 +250,8 @@ export default function AgentActivityWorkspace({
setFilters((current) =>
sameActivityFilters(current, next) ? current : next,
);
+ setActivityScopedAgentId(next.agentId);
+ setActivityScopedSessionId(next.sessionId);
}, [initialBaseFilters]);
useEffect(() => {
@@ -220,21 +287,16 @@ export default function AgentActivityWorkspace({
}, []);
useEffect(() => {
- if (usesAgentThreadView) {
- setActivityLoading(false);
- return;
- }
-
let cancelled = false;
const load = async () => {
setActivityLoading(true);
setError("");
try {
- const response = await fetchActivity(activityQuery);
+ const response = await fetchActivity(catalogQuery);
if (cancelled) {
return;
}
- setActivityEvents(response.events);
+ setCatalogEvents(response.events.map(normalizeDashboardActivityEvent));
} catch (err) {
if (cancelled) {
return;
@@ -253,10 +315,11 @@ export default function AgentActivityWorkspace({
return () => {
cancelled = true;
};
- }, [activityQuery, activityQueryKey, refreshNonce, usesAgentThreadView]);
+ }, [catalogQuery, catalogQueryKey, refreshNonce]);
useEffect(() => {
- if (!usesAgentThreadView || !filters.agentId) {
+ if (!usesAgentThreadView || !threadQuery) {
+ setThreadEvents([]);
setAgentLoading(false);
return;
}
@@ -266,11 +329,11 @@ export default function AgentActivityWorkspace({
setAgentLoading(true);
setError("");
try {
- const response = await api.fetchAgent(filters.agentId, "both");
+ const response = await fetchActivity(threadQuery);
if (cancelled) {
return;
}
- hydrateAgentEvents(filters.agentId, response.events);
+ setThreadEvents(response.events.map(normalizeDashboardActivityEvent));
} catch (err) {
if (cancelled) {
return;
@@ -289,7 +352,7 @@ export default function AgentActivityWorkspace({
return () => {
cancelled = true;
};
- }, [filters.agentId, hydrateAgentEvents, refreshNonce, usesAgentThreadView]);
+ }, [refreshNonce, threadQuery, threadQueryKey, usesAgentThreadView]);
const filteredInstances = useMemo(
() =>
@@ -309,9 +372,20 @@ export default function AgentActivityWorkspace({
[filters.instanceId, tabs],
);
+ const agentOptions = useMemo(() => {
+ const ids = new Set<string>();
+ for (const event of catalogEvents) {
+ const agentId = (event.agentId || "").trim();
+ if (agentId) {
+ ids.add(agentId);
+ }
+ }
+ return Array.from(ids).sort();
+ }, [catalogEvents]);
+
const visibleEvents = useMemo(
() =>
- activityEvents.filter((event) =>
+ catalogEvents.filter((event) =>
matchesVisibleEvent(
event,
filters,
@@ -319,28 +393,94 @@ export default function AgentActivityWorkspace({
requireAgentIdentity,
),
),
- [activityEvents, filters, normalizedHiddenSources, requireAgentIdentity],
+ [catalogEvents, filters, normalizedHiddenSources, requireAgentIdentity],
);
- const agentThreadEvents = useMemo(() => {
- if (!filters.agentId) {
- return [] as DashboardActivityEvent[];
- }
+ const sessionCatalogEvents = useMemo(
+ () =>
+ catalogEvents.filter((event) =>
+ matchesVisibleEvent(
+ event,
+ withClearedSessionFilter(filters),
+ normalizedHiddenSources,
+ requireAgentIdentity,
+ ),
+ ),
+ [catalogEvents, filters, normalizedHiddenSources, requireAgentIdentity],
+ );
- return (agentEventsById[filters.agentId] ?? [])
- .map(toDashboardActivityEvent)
- .filter((event) =>
+ const agentCatalogEvents = useMemo(
+ () =>
+ catalogEvents.filter((event) =>
matchesVisibleEvent(
event,
{
- ...filters,
+ ...withClearedSessionFilter(filters),
agentId: "",
},
normalizedHiddenSources,
requireAgentIdentity,
),
+ ),
+ [catalogEvents, filters, normalizedHiddenSources, requireAgentIdentity],
+ );
+
+ const agentThreadBaseEvents = useMemo(() => {
+ const liveEvents = (agentEventsById[filters.agentId] ?? []).map(
+ toDashboardActivityEvent,
+ );
+ return mergeDashboardActivityEvents(threadEvents, liveEvents);
+ }, [agentEventsById, filters.agentId, threadEvents]);
+
+ const agentThreadEvents = useMemo(() => {
+ const effectiveFilters = filters;
+
+ return agentThreadBaseEvents.filter((event) => {
+ if (
+ effectiveFilters.agentId &&
+ eventIdentity(event).toLowerCase() !==
+ effectiveFilters.agentId.toLowerCase()
+ ) {
+ return false;
+ }
+ return matchesVisibleEvent(
+ event,
+ effectiveFilters,
+ normalizedHiddenSources,
+ requireAgentIdentity,
+ );
+ });
+ }, [
+ agentThreadBaseEvents,
+ filters,
+ normalizedHiddenSources,
+ requireAgentIdentity,
+ ]);
+
+ const agentThreadSessionCatalogEvents = useMemo(() => {
+ const effectiveFilters = withClearedSessionFilter(filters);
+
+ return agentThreadBaseEvents.filter((event) => {
+ if (
+ effectiveFilters.agentId &&
+ eventIdentity(event).toLowerCase() !==
+ effectiveFilters.agentId.toLowerCase()
+ ) {
+ return false;
+ }
+ return matchesVisibleEvent(
+ event,
+ effectiveFilters,
+ normalizedHiddenSources,
+ requireAgentIdentity,
);
- }, [agentEventsById, filters, normalizedHiddenSources, requireAgentIdentity]);
+ });
+ }, [
+ agentThreadBaseEvents,
+ filters,
+ normalizedHiddenSources,
+ requireAgentIdentity,
+ ]);
const displayedEvents = usesAgentThreadView
? agentThreadEvents
@@ -368,17 +508,18 @@ export default function AgentActivityWorkspace({
const sourceEvents =
usesAgentThreadView && filters.agentId
- ? (agentEventsById[filters.agentId] ?? []).map(toDashboardActivityEvent)
- : visibleEvents;
+ ? agentThreadSessionCatalogEvents
+ : sessionCatalogEvents;
for (const event of sourceEvents) {
const sid = event.sessionId?.trim();
if (!sid) continue;
+ const identity = eventIdentity(event);
const existing = bySession.get(sid);
if (!existing) {
bySession.set(sid, {
- agentId: event.agentId || "",
+ agentId: identity,
earliest: event.timestamp,
latest: event.timestamp,
});
@@ -409,8 +550,8 @@ export default function AgentActivityWorkspace({
}, [
usesAgentThreadView,
filters.agentId,
- agentEventsById,
- visibleEvents,
+ agentThreadSessionCatalogEvents,
+ sessionCatalogEvents,
agentSessions,
]);
@@ -444,17 +585,17 @@ export default function AgentActivityWorkspace({
const derivedAgents = useMemo<Agent[]>(() => {
const byId = new Map<string, Agent>();
- for (const event of visibleEvents) {
- const agentId = event.agentId?.trim();
- if (!agentId) {
+ for (const event of agentCatalogEvents) {
+ const identity = eventIdentity(event);
+ if (!identity) {
continue;
}
- const existing = byId.get(agentId);
+ const existing = byId.get(identity);
if (!existing) {
- byId.set(agentId, {
- id: agentId,
- name: agentId,
+ byId.set(identity, {
+ id: identity,
+ name: identity,
connectedAt: event.timestamp,
lastActivity: event.timestamp,
requestCount: 1,
@@ -476,20 +617,28 @@ export default function AgentActivityWorkspace({
new Date(right.lastActivity || right.connectedAt).getTime() -
new Date(left.lastActivity || left.connectedAt).getTime(),
);
- }, [visibleEvents]);
+ }, [agentCatalogEvents]);
const visibleAgents = useMemo<Agent[]>(() => {
if (!preferKnownAgents) {
return derivedAgents;
}
- return [...agents]
- .filter((agent) => {
- if (requireAgentIdentity && !(agent.id || "").trim()) {
- return false;
- }
- return true;
- })
+ const merged = new Map<string, Agent>();
+ for (const agent of derivedAgents) {
+ merged.set(agent.id, agent);
+ }
+ for (const agent of agents) {
+ merged.set(agent.id, {
+ ...merged.get(agent.id),
+ ...agent,
+ });
+ }
+
+ return [...merged.values()]
+ .filter((agent) =>
+ !requireAgentIdentity ? true : !!(agent.id || "").trim(),
+ )
.sort(
(left, right) =>
new Date(right.lastActivity || right.connectedAt).getTime() -
@@ -497,21 +646,10 @@ export default function AgentActivityWorkspace({
);
}, [agents, derivedAgents, preferKnownAgents, requireAgentIdentity]);
- const summary = useMemo(() => {
- const agentsSeen = new Set(
- displayedEvents.map((event) => event.agentId).filter(Boolean),
- );
- const tabsSeen = new Set(
- displayedEvents.map((event) => event.tabId).filter(Boolean),
- );
- const instancesSeen = new Set(
- displayedEvents.map((event) => event.instanceId).filter(Boolean),
- );
-
- return `${displayedEvents.length} events • ${agentsSeen.size} agents • ${tabsSeen.size} tabs • ${instancesSeen.size} instances`;
- }, [displayedEvents]);
-
useEffect(() => {
+ if (sidebarTab !== "agents") {
+ return;
+ }
if (!requireSelectedAgent || visibleAgents.length === 0) {
return;
}
@@ -520,28 +658,31 @@ export default function AgentActivityWorkspace({
(agent) => agent.id === filters.agentId,
);
const targetAgent = hasAgent ? filters.agentId : visibleAgents[0].id;
- const agentSessionList = derivedSessions.filter(
- (s) => s.agentId === targetAgent,
- );
- const latestSession =
- agentSessionList.length > 0 ? agentSessionList[0].id : "";
-
- if (!hasAgent || (!filters.sessionId && latestSession)) {
+ if (!hasAgent) {
setFilters((current) => ({
...current,
agentId: targetAgent,
- sessionId: latestSession,
+ sessionId: "",
}));
}
- }, [
- filters.agentId,
- filters.sessionId,
- requireSelectedAgent,
- visibleAgents,
- derivedSessions,
- ]);
+ }, [filters.agentId, requireSelectedAgent, sidebarTab, visibleAgents]);
const updateFilter = (key: keyof ActivityFilters, value: string) => {
+ if (sidebarTab === "activities") {
+ if (key === "agentId") {
+ setActivityScopedAgentId(value);
+ setActivityScopedSessionId("");
+ setFilters((current) => ({
+ ...current,
+ agentId: value,
+ sessionId: "",
+ }));
+ return;
+ }
+ if (key === "sessionId") {
+ setActivityScopedSessionId(value);
+ }
+ }
setFilters((current) => ({ ...current, [key]: value }));
};
@@ -573,6 +714,10 @@ export default function AgentActivityWorkspace({
const resetBaseFilters = clearToInitialFilters
? initialBaseFilters
: defaultActivityFilters;
+ if (sidebarTab === "activities") {
+ setActivityScopedAgentId(resetBaseFilters.agentId);
+ setActivityScopedSessionId(resetBaseFilters.sessionId);
+ }
setFilters((current) => ({
...resetBaseFilters,
agentId:
@@ -583,7 +728,9 @@ export default function AgentActivityWorkspace({
};
const sidebarLoading =
- sidebarTab === "activities" ? activityLoading : agentLoading;
+ sidebarTab === "activities"
+ ? activityLoading
+ : activityLoading || agentLoading;
return (
<div className="flex h-full min-h-0 flex-col overflow-hidden xl:flex-row">
@@ -598,13 +745,23 @@ export default function AgentActivityWorkspace({
profiles={profiles}
filteredInstances={filteredInstances}
visibleTabs={visibleTabs}
+ agentOptions={agentOptions}
loading={sidebarLoading}
- onSidebarTabChange={setSidebarTab}
- onSelectAgent={(agentId, autoSessionId) => {
+ onSidebarTabChange={(nextTab) => {
+ setSidebarTab(nextTab);
+ if (nextTab === "activities") {
+ setFilters((current) => ({
+ ...current,
+ agentId: activityScopedAgentId,
+ sessionId: activityScopedSessionId,
+ }));
+ }
+ }}
+ onSelectAgent={(agentId) => {
setFilters((current) => ({
...current,
agentId,
- sessionId: autoSessionId || "",
+ sessionId: "",
}));
}}
onSelectSession={(sessionId) => {
@@ -621,17 +778,11 @@ export default function AgentActivityWorkspace({
/>
<AgentStreamPanel
- filters={filters}
events={displayedEvents}
sessions={derivedSessions}
- summary={summary}
error={error}
- loading={usesAgentThreadView ? agentLoading : activityLoading}
+ loading={activityLoading || agentLoading}
copyTabId={copyTabId}
- hideAgentFilter={requireSelectedAgent}
- hideSessionFilter={requireSelectedAgent}
- simplifyMeta={simplifyEventRows}
- onClearFilters={clearFilters}
onFilterChange={updateFilter}
/>
</div>
diff --git a/dashboard/src/activities/AgentStreamPanel.tsx b/dashboard/src/activities/AgentStreamPanel.tsx
index 7deff35f..4b7a18ab 100644
--- a/dashboard/src/activities/AgentStreamPanel.tsx
+++ b/dashboard/src/activities/AgentStreamPanel.tsx
@@ -1,51 +1,36 @@
import { useLayoutEffect, useRef } from "react";
import { EmptyState } from "../components/atoms";
import type { Session } from "../services/api";
-import ActiveFilterBar from "./ActiveFilterBar";
-import SessionDivider from "./SessionDivider";
-import StreamRow from "./StreamRow";
+import ActivityItemLine from "./ActivityItemLine";
import type { ActivityFilters, DashboardActivityEvent } from "./types";
interface AgentStreamPanelProps {
- filters: ActivityFilters;
events: DashboardActivityEvent[];
sessions?: Session[];
- summary: string;
error: string;
loading: boolean;
copyTabId?: boolean;
- hideAgentFilter?: boolean;
- hideSessionFilter?: boolean;
- simplifyMeta?: boolean;
- onClearFilters: () => void;
onFilterChange: (key: keyof ActivityFilters, value: string) => void;
}
export default function AgentStreamPanel({
- filters,
events,
sessions = [],
- summary,
error,
loading,
copyTabId = false,
- hideAgentFilter = false,
- hideSessionFilter = false,
- simplifyMeta = false,
- onClearFilters,
onFilterChange,
}: AgentStreamPanelProps) {
- const sessionMap = new Map(sessions.map((s) => [s.id, s]));
+ const sessionLabels = new Map(
+ sessions
+ .filter((session) => session.label?.trim())
+ .map((session) => [session.id, session.label!.trim()] as const),
+ );
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;
@@ -58,12 +43,9 @@ export default function AgentStreamPanel({
if (eventCountChanged && shouldStickToBottomRef.current) {
container.scrollTop = container.scrollHeight;
}
- }, [events, simplifyMeta]);
+ }, [events]);
const handleScroll = () => {
- if (!simplifyMeta) {
- return;
- }
const container = scrollContainerRef.current;
if (!container) {
return;
@@ -74,21 +56,7 @@ export default function AgentStreamPanel({
};
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">
- <div></div>
- <div className="dashboard-mono text-[0.72rem] text-text-muted">
- {summary}
- </div>
- </div>
-
- <ActiveFilterBar
- filters={filters}
- hideAgentFilter={hideAgentFilter}
- hideSessionFilter={hideSessionFilter}
- onClear={onClearFilters}
- />
-
+ <section className="dashboard-panel flex min-h-0 flex-1 flex-col overflow-hidden rounded-none">
{error && (
<div className="border-b border-destructive/30 bg-destructive/10 px-4 py-2 text-xs text-destructive">
{error}
@@ -107,35 +75,21 @@ export default function AgentStreamPanel({
description="Adjust the filters or generate some traffic from the CLI, MCP, or dashboard."
/>
) : (
- <div
- className={
- simplifyMeta ? "flex min-h-full flex-col justify-end py-2" : ""
- }
- >
- {events.map((event, index) => {
- const prevSessionId =
- index > 0 ? events[index - 1].sessionId : undefined;
- const showDivider =
- event.sessionId && event.sessionId !== prevSessionId;
- return (
- <div key={`${event.requestId || event.timestamp}-${index}`}>
- {showDivider && (
- <SessionDivider
- session={sessionMap.get(event.sessionId || "")}
- sessionId={event.sessionId || ""}
- timestamp={event.timestamp}
- />
- )}
- <StreamRow
- event={event}
- copyTabId={copyTabId}
- hideAgentFilter={hideAgentFilter}
- simplifyMeta={simplifyMeta}
- onFilterChange={onFilterChange}
- />
- </div>
- );
- })}
+ <div className="divide-y divide-border-subtle/70">
+ {events.map((event, index) => (
+ <ActivityItemLine
+ key={`${event.requestId || event.timestamp}-${index}`}
+ event={event}
+ showTab
+ copyTabId={copyTabId}
+ sessionLabel={
+ event.sessionId
+ ? sessionLabels.get(event.sessionId)
+ : "anonymous"
+ }
+ onFilterChange={onFilterChange}
+ />
+ ))}
</div>
)}
</div>
diff --git a/dashboard/src/activities/AgentWorkspaceSidebar.tsx b/dashboard/src/activities/AgentWorkspaceSidebar.tsx
index 2499870d..cb51d88e 100644
--- a/dashboard/src/activities/AgentWorkspaceSidebar.tsx
+++ b/dashboard/src/activities/AgentWorkspaceSidebar.tsx
@@ -18,6 +18,7 @@ interface AgentWorkspaceSidebarProps {
profiles: Profile[];
filteredInstances: Instance[];
visibleTabs: InstanceTab[];
+ agentOptions?: string[];
loading: boolean;
onSidebarTabChange: (tab: WorkspaceTab) => void;
onSelectAgent: (agentId: string, autoSessionId?: string) => void;
@@ -40,6 +41,7 @@ export default function AgentWorkspaceSidebar({
profiles,
filteredInstances,
visibleTabs,
+ agentOptions,
loading,
onSidebarTabChange,
onSelectAgent,
@@ -120,9 +122,7 @@ export default function AgentWorkspaceSidebar({
selected={activeAgentId === agent.id}
sessions={sessionsByAgent.get(agent.id) || []}
activeSessionId={filters.sessionId}
- onClick={(autoSessionId) =>
- onSelectAgent(agent.id, autoSessionId)
- }
+ onClick={() => onSelectAgent(agent.id)}
onSelectSession={onSelectSession}
/>
))}
@@ -135,6 +135,7 @@ export default function AgentWorkspaceSidebar({
profileOptions={profiles}
instanceOptions={filteredInstances}
tabOptions={visibleTabs}
+ agentOptions={agentOptions}
loading={loading}
showAgentFilter={showAgentFilter}
onClear={onClearFilters}
diff --git a/dashboard/src/activities/AgentsPage.test.tsx b/dashboard/src/activities/AgentsPage.test.tsx
index 7a3667f7..8bb8247f 100644
--- a/dashboard/src/activities/AgentsPage.test.tsx
+++ b/dashboard/src/activities/AgentsPage.test.tsx
@@ -11,12 +11,11 @@ vi.mock("./api", () => ({
vi.mock("../services/api", () => ({
fetchAllTabs: vi.fn(),
- fetchAgent: vi.fn(),
fetchSessions: vi.fn(),
}));
import { fetchActivity } from "./api";
-import { fetchAgent, fetchSessions, fetchAllTabs } from "../services/api";
+import { fetchSessions, fetchAllTabs } from "../services/api";
describe("AgentsPage", () => {
beforeEach(() => {
@@ -37,83 +36,67 @@ describe("AgentsPage", () => {
currentTabs: {},
});
vi.mocked(fetchAllTabs).mockResolvedValue([]);
- vi.mocked(fetchSessions).mockResolvedValue([]);
- vi.mocked(fetchAgent).mockResolvedValue({
- agent: {
- id: "cli",
- name: "CLI",
- connectedAt: "2026-03-16T08:00:00Z",
- lastActivity: "2026-03-16T08:10:00Z",
- requestCount: 3,
+ vi.mocked(fetchSessions).mockResolvedValue([
+ {
+ id: "ses_123",
+ agentId: "cli",
+ label: "Checkout flow",
+ createdAt: "2026-03-16T08:59:00Z",
+ lastSeenAt: "2026-03-16T09:05:00Z",
+ expiresAt: "",
+ status: "active",
},
+ ]);
+ vi.mocked(fetchActivity).mockResolvedValue({
+ count: 4,
events: [
{
- id: "evt_1",
+ timestamp: "2026-03-16T09:00:00Z",
+ source: "client",
+ requestId: "req_123",
+ sessionId: "ses_123",
agentId: "cli",
- channel: "tool_call",
- type: "click",
method: "POST",
path: "/tabs/tab_123/action",
- timestamp: "2026-03-16T09:00:00Z",
- details: {
- source: "bridge",
- requestId: "req_123",
- status: 200,
- durationMs: 87,
- tabId: "tab_123",
- action: "click",
- },
+ status: 200,
+ durationMs: 87,
+ tabId: "tab_123",
+ action: "click",
},
{
- id: "evt_2",
+ timestamp: "2026-03-16T09:00:01Z",
+ source: "client",
+ requestId: "req_124",
agentId: "cli",
- channel: "tool_call",
- type: "text",
method: "GET",
- path: "/tabs/tab_123/text",
- timestamp: "2026-03-16T09:00:02Z",
- details: {
- source: "server",
- requestId: "req_125",
- status: 200,
- durationMs: 11,
- tabId: "tab_123",
- },
+ path: "/text",
+ status: 200,
+ durationMs: 22,
+ tabId: "tab_123",
+ action: "text",
},
{
- id: "evt_hidden",
+ timestamp: "2026-03-16T09:00:02Z",
+ source: "server",
+ requestId: "req_125",
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",
- },
+ method: "GET",
+ path: "/tabs/tab_123/text",
+ status: 200,
+ durationMs: 11,
+ tabId: "tab_123",
},
- ],
- });
- vi.mocked(fetchActivity).mockResolvedValue({
- count: 1,
- events: [
{
- timestamp: "2026-03-16T09:01:00Z",
- source: "bridge",
- requestId: "req_activity",
+ timestamp: "2026-03-16T09:00:03Z",
+ source: "dashboard",
+ requestId: "req_hidden",
agentId: "cli",
method: "POST",
- path: "/tabs/tab_555/navigate",
+ path: "/tabs/tab_123/navigate",
status: 200,
- durationMs: 10,
- tabId: "tab_555",
- url: "https://pinchtab.com",
+ durationMs: 9,
+ tabId: "tab_123",
+ url: "https://hidden.example",
action: "navigate",
},
],
@@ -128,14 +111,30 @@ describe("AgentsPage", () => {
);
await waitFor(() => {
- expect(fetchAgent).toHaveBeenCalledWith("cli", "both");
+ expect(fetchActivity).toHaveBeenCalledWith(
+ expect.objectContaining({
+ source: "client",
+ limit: 1000,
+ }),
+ );
+ });
+ expect(vi.mocked(fetchActivity).mock.calls[0]?.[0]).not.toHaveProperty(
+ "agentId",
+ );
+ await waitFor(() => {
+ expect(fetchActivity).toHaveBeenCalledWith(
+ expect.objectContaining({
+ source: "client",
+ limit: 1000,
+ agentId: "cli",
+ }),
+ );
});
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 including agent filter", async () => {
@@ -146,7 +145,7 @@ describe("AgentsPage", () => {
);
await waitFor(() => {
- expect(fetchAgent).toHaveBeenCalled();
+ expect(fetchActivity).toHaveBeenCalled();
});
await userEvent.click(screen.getByRole("button", { name: "Activities" }));
@@ -155,11 +154,16 @@ describe("AgentsPage", () => {
expect(fetchActivity).toHaveBeenCalled();
});
+ await waitFor(() => {
+ const lastQuery = vi.mocked(fetchActivity).mock.lastCall?.[0];
+ expect(lastQuery).not.toHaveProperty("agentId");
+ });
+
expect(screen.getByLabelText("Profile")).toBeInTheDocument();
expect(screen.getByLabelText("Agent")).toBeInTheDocument();
});
- it("keeps the simplified event rows and inline copyable tab ids", async () => {
+ it("keeps the simplified event rows and copyable tab ids", async () => {
render(
<MemoryRouter>
<AgentsPage />
@@ -167,7 +171,7 @@ describe("AgentsPage", () => {
);
await waitFor(() => {
- expect(screen.getByText(/Click on page on tab/)).toBeInTheDocument();
+ expect(screen.getByText("Click on page")).toBeInTheDocument();
});
expect(
@@ -175,12 +179,14 @@ describe("AgentsPage", () => {
).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);
+ expect(screen.getAllByText("200").length).toBeGreaterThan(0);
+ expect(screen.getAllByText("Checkout flow").length).toBeGreaterThan(0);
+ expect(screen.getAllByTitle(/Copy tab ID tab_123/).length).toBeGreaterThan(
+ 0,
+ );
});
- it("shows all agent activity in the thread regardless of source", async () => {
+ it("shows only client-sourced agent activity in the thread", async () => {
render(
<MemoryRouter>
<AgentsPage />
@@ -188,24 +194,13 @@ describe("AgentsPage", () => {
);
await waitFor(() => {
- expect(screen.getByText(/3 events • 1 agents/)).toBeInTheDocument();
+ expect(screen.getByText("Click on page")).toBeInTheDocument();
});
-
+ expect(screen.getByText("Extract text from page")).toBeInTheDocument();
+ expect(screen.getAllByText("anonymous").length).toBeGreaterThan(0);
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);
+ screen.queryByText("Navigate to https://hidden.example"),
+ ).not.toBeInTheDocument();
});
it("updates the open agent thread and sidebar list from the shared store", async () => {
@@ -216,7 +211,7 @@ describe("AgentsPage", () => {
);
await waitFor(() => {
- expect(fetchAgent).toHaveBeenCalled();
+ expect(fetchActivity).toHaveBeenCalled();
});
act(() => {
@@ -249,6 +244,159 @@ describe("AgentsPage", () => {
});
expect(screen.getByText("worker-2")).toBeInTheDocument();
- expect(screen.getByText("Planning next step")).toBeInTheDocument();
+ expect(screen.queryByText("Planning next step")).not.toBeInTheDocument();
+ });
+
+ it("keeps sibling sessions visible after selecting a derived session", async () => {
+ vi.mocked(fetchSessions).mockResolvedValue([]);
+ vi.mocked(fetchActivity).mockResolvedValue({
+ count: 2,
+ events: [
+ {
+ timestamp: "2026-03-16T09:00:00Z",
+ source: "client",
+ requestId: "req_session_1",
+ sessionId: "ses_123",
+ agentId: "cli",
+ method: "POST",
+ path: "/tabs/tab_123/action",
+ status: 200,
+ durationMs: 87,
+ tabId: "tab_123",
+ action: "click",
+ },
+ {
+ timestamp: "2026-03-16T09:10:00Z",
+ source: "client",
+ requestId: "req_session_2",
+ sessionId: "ses_456",
+ agentId: "cli",
+ method: "GET",
+ path: "/text",
+ status: 200,
+ durationMs: 22,
+ tabId: "tab_123",
+ action: "text",
+ },
+ ],
+ });
+
+ render(
+ <MemoryRouter>
+ <AgentsPage />
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getAllByRole("button", { name: /^Session / })).toHaveLength(
+ 2,
+ );
+ });
+
+ await userEvent.click(
+ screen.getAllByRole("button", { name: /^Session / })[0],
+ );
+
+ await waitFor(() => {
+ expect(screen.getAllByRole("button", { name: /^Session / })).toHaveLength(
+ 2,
+ );
+ });
+ });
+
+ it("shows client events without agent ids as anonymous", async () => {
+ useAppStore.setState({
+ agents: [],
+ agentEventsById: {},
+ profiles: [],
+ instances: [],
+ currentTabs: {},
+ });
+ vi.mocked(fetchActivity).mockImplementation(async (query) => {
+ if (query?.agentId && query.agentId !== "anonymous") {
+ return { count: 0, events: [] };
+ }
+ return {
+ count: 1,
+ events: [
+ {
+ timestamp: "2026-04-08T18:02:26.983381Z",
+ source: "client",
+ requestId: "66f833fb1a65b720",
+ method: "POST",
+ path: "/navigate",
+ status: 200,
+ durationMs: 1066,
+ instanceId: "inst_990e5062",
+ profileId: "prof_37a8eec1",
+ profileName: "default",
+ tabId: "ACDF218287DBE662F237F064618A624D",
+ url: "https://github.com/",
+ action: "navigate",
+ },
+ ],
+ };
+ });
+
+ render(
+ <MemoryRouter>
+ <AgentsPage />
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => {
+ expect(
+ screen.getByText("Navigate to https://github.com/"),
+ ).toBeInTheDocument();
+ });
+
+ expect(screen.getAllByText("anonymous").length).toBeGreaterThan(0);
+ });
+
+ it("hydrates the selected agent thread from a scoped activity query", async () => {
+ vi.mocked(fetchActivity).mockImplementation(async (query) => {
+ if (query?.agentId === "cli") {
+ return {
+ count: 1,
+ events: [
+ {
+ timestamp: "2026-03-16T07:45:00Z",
+ source: "client",
+ requestId: "req_thread_only",
+ sessionId: "ses_789",
+ agentId: "cli",
+ method: "GET",
+ path: "/text",
+ status: 200,
+ durationMs: 14,
+ tabId: "tab_123",
+ action: "text",
+ },
+ ],
+ };
+ }
+ return {
+ count: 0,
+ events: [],
+ };
+ });
+
+ render(
+ <MemoryRouter>
+ <AgentsPage />
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => {
+ expect(fetchActivity).toHaveBeenCalledWith(
+ expect.objectContaining({
+ source: "client",
+ limit: 1000,
+ agentId: "cli",
+ }),
+ );
+ });
+
+ expect(screen.getByText("Extract text from page")).toBeInTheDocument();
});
});
diff --git a/dashboard/src/activities/AgentsPage.tsx b/dashboard/src/activities/AgentsPage.tsx
index bc95e80c..fa93109f 100644
--- a/dashboard/src/activities/AgentsPage.tsx
+++ b/dashboard/src/activities/AgentsPage.tsx
@@ -11,7 +11,6 @@ export default function AgentsPage() {
requireSelectedAgent
showAllAgentsOption={false}
showAgentFilter
- simplifyEventRows
copyTabId
preferKnownAgents
useAgentEventStore
diff --git a/dashboard/src/activities/index.ts b/dashboard/src/activities/index.ts
index ad03894e..35c4c625 100644
--- a/dashboard/src/activities/index.ts
+++ b/dashboard/src/activities/index.ts
@@ -1,4 +1,5 @@
export { default as ActivityExplorer } from "./ActivityExplorer";
+export { default as ActivityItemLine } from "./ActivityItemLine";
export { default as ActivityPage } from "./ActivityPage";
export { default as AgentsPage } from "./AgentsPage";
export { default as ActivityLine } from "./ActivityLine";
diff --git a/dashboard/src/activities/types.ts b/dashboard/src/activities/types.ts
index 5b2a7d56..7459f12d 100644
--- a/dashboard/src/activities/types.ts
+++ b/dashboard/src/activities/types.ts
@@ -24,7 +24,6 @@ export interface ActivityQuery {
source?: string;
requestId?: string;
sessionId?: string;
- actorId?: string;
agentId?: string;
instanceId?: string;
profileId?: string;
diff --git a/dashboard/src/components/molecules/AgentItem.tsx b/dashboard/src/components/molecules/AgentItem.tsx
index 4000d14c..36a7ba65 100644
--- a/dashboard/src/components/molecules/AgentItem.tsx
+++ b/dashboard/src/components/molecules/AgentItem.tsx
@@ -7,7 +7,7 @@ interface Props {
selected: boolean;
sessions: Session[];
activeSessionId?: string;
- onClick: (autoSessionId?: string) => void;
+ onClick: () => void;
onSelectSession: (sessionId: string) => void;
}
@@ -43,11 +43,6 @@ export default function AgentItem({
onClick,
onSelectSession,
}: Props) {
- const handleAgentClick = () => {
- const latestSession = sessions.length > 0 ? sessions[0].id : undefined;
- onClick(latestSession);
- };
-
return (
<div>
<button
@@ -56,7 +51,7 @@ export default function AgentItem({
? "bg-primary/8 text-text-primary"
: "text-text-secondary hover:bg-bg-elevated hover:text-text-primary"
}`}
- onClick={handleAgentClick}
+ onClick={onClick}
>
<div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-primary">
<IconRobot />
diff --git a/dashboard/src/components/molecules/NavBar.test.tsx b/dashboard/src/components/molecules/NavBar.test.tsx
new file mode 100644
index 00000000..f50eafbf
--- /dev/null
+++ b/dashboard/src/components/molecules/NavBar.test.tsx
@@ -0,0 +1,52 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { MemoryRouter } from "react-router-dom";
+import NavBar from "./NavBar";
+import { useAppStore } from "../../stores/useAppStore";
+
+vi.mock("../../services/api", () => ({
+ logout: vi.fn(),
+}));
+
+describe("NavBar", () => {
+ it("uses the first instance when none is selected", () => {
+ useAppStore.setState({
+ serverInfo: {
+ status: "ok",
+ mode: "dashboard",
+ version: "1.0.0",
+ uptime: 120000,
+ profiles: 1,
+ instances: 1,
+ agents: 0,
+ restartRequired: false,
+ restartReasons: [],
+ },
+ instances: [
+ {
+ id: "inst_alpha",
+ profileId: "prof_alpha",
+ profileName: "alpha",
+ port: "9988",
+ headless: false,
+ status: "running",
+ startTime: "2026-04-09T10:00:00Z",
+ attached: false,
+ },
+ ],
+ currentTabs: {
+ inst_alpha: [],
+ },
+ selectedMonitoringInstanceId: null,
+ monitoringSidebarCollapsed: true,
+ });
+
+ render(
+ <MemoryRouter initialEntries={["/dashboard/profiles"]}>
+ <NavBar />
+ </MemoryRouter>,
+ );
+
+ expect(screen.getByTitle("alpha · running · 9988")).toBeInTheDocument();
+ });
+});
diff --git a/dashboard/src/components/molecules/NavBar.tsx b/dashboard/src/components/molecules/NavBar.tsx
index c95f51d7..b712edfc 100644
--- a/dashboard/src/components/molecules/NavBar.tsx
+++ b/dashboard/src/components/molecules/NavBar.tsx
@@ -43,7 +43,12 @@ export default function NavBar({ onRefresh, showLogout = false }: NavBarProps) {
"/dashboard/monitoring",
);
const selectedInstance =
- instances.find((i) => i.id === selectedMonitoringInstanceId) ?? null;
+ instances.find((i) => i.id === selectedMonitoringInstanceId) ??
+ instances[0] ??
+ null;
+ const hasRunningInstance = instances.some(
+ (instance) => instance.status === "running",
+ );
// Close mobile menu on route change
useEffect(() => {
@@ -118,6 +123,7 @@ export default function NavBar({ onRefresh, showLogout = false }: NavBarProps) {
instance={selectedInstance}
compact={!isMonitoringPage}
sidebarCollapsed={monitoringSidebarCollapsed}
+ hasRunningInstance={hasRunningInstance}
tabCount={
selectedInstance
? (currentTabs[selectedInstance.id]?.length ?? 0)
diff --git a/dashboard/src/components/molecules/ServerStatusBadge.test.tsx b/dashboard/src/components/molecules/ServerStatusBadge.test.tsx
new file mode 100644
index 00000000..fe2262f8
--- /dev/null
+++ b/dashboard/src/components/molecules/ServerStatusBadge.test.tsx
@@ -0,0 +1,77 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import type { DashboardServerInfo } from "../../types";
+import type { Instance } from "../../generated/types";
+import ServerStatusBadge from "./ServerStatusBadge";
+
+const runningInstance: Instance = {
+ id: "inst_alpha",
+ profileId: "prof_alpha",
+ profileName: "alpha",
+ port: "9988",
+ headless: false,
+ status: "running",
+ startTime: "2026-04-09T10:00:00Z",
+ attached: false,
+};
+
+const serverInfo: DashboardServerInfo = {
+ status: "ok",
+ mode: "dashboard",
+ version: "1.0.0",
+ uptime: 120000,
+ profiles: 1,
+ instances: 1,
+ agents: 0,
+ restartRequired: false,
+ restartReasons: [],
+};
+
+describe("ServerStatusBadge", () => {
+ it("hides the port in compact mode", () => {
+ const { container } = render(
+ <ServerStatusBadge
+ serverInfo={serverInfo}
+ instance={runningInstance}
+ compact
+ hasRunningInstance
+ />,
+ );
+
+ expect(screen.queryByText("9988")).not.toBeInTheDocument();
+ expect(container.querySelector(".bg-success")).toBeInTheDocument();
+ });
+
+ it("shows only a warning dot when the server is up but no instance is running", () => {
+ const { container } = render(
+ <ServerStatusBadge
+ serverInfo={serverInfo}
+ instance={{
+ ...runningInstance,
+ status: "starting",
+ }}
+ compact
+ hasRunningInstance={false}
+ />,
+ );
+
+ expect(screen.queryByText("Running")).not.toBeInTheDocument();
+ expect(screen.queryByText("9988")).not.toBeInTheDocument();
+ expect(container.querySelector(".bg-warning")).toBeInTheDocument();
+ });
+
+ it("shows the detailed instance summary outside compact mode", () => {
+ render(
+ <ServerStatusBadge
+ serverInfo={serverInfo}
+ instance={runningInstance}
+ tabCount={3}
+ hasRunningInstance
+ />,
+ );
+
+ expect(screen.getByText("alpha ·")).toBeInTheDocument();
+ expect(screen.getByText("running · 3 tabs ·")).toBeInTheDocument();
+ expect(screen.getByText("9988")).toBeInTheDocument();
+ });
+});
diff --git a/dashboard/src/components/molecules/ServerStatusBadge.tsx b/dashboard/src/components/molecules/ServerStatusBadge.tsx
index 8663e2f6..7ea7c6be 100644
--- a/dashboard/src/components/molecules/ServerStatusBadge.tsx
+++ b/dashboard/src/components/molecules/ServerStatusBadge.tsx
@@ -7,6 +7,7 @@ interface Props {
compact?: boolean;
sidebarCollapsed?: boolean;
tabCount?: number;
+ hasRunningInstance?: boolean;
onToggleSidebar?: () => void;
}
@@ -16,8 +17,23 @@ export default function ServerStatusBadge({
compact = false,
sidebarCollapsed = false,
tabCount = 0,
+ hasRunningInstance = false,
onToggleSidebar,
}: Props) {
+ const serverRunning = !!serverInfo && serverInfo.status !== "error";
+
+ if (serverRunning && !hasRunningInstance) {
+ const title = serverInfo.restartRequired
+ ? serverInfo.restartReasons?.join(", ") || "Server running, no instances"
+ : "Server running, no instances";
+
+ return (
+ <div className="mr-2 flex items-center px-2 py-1" title={title}>
+ <div className="h-1.5 w-1.5 rounded-full bg-warning" />
+ </div>
+ );
+ }
+
if (instance) {
const statusColor =
instance.status === "running"
@@ -33,7 +49,6 @@ export default function ServerStatusBadge({
title={`${instance.profileName} · ${instance.status} · ${instance.port}`}
>
<div className={`h-1.5 w-1.5 shrink-0 rounded-full ${statusColor}`} />
- <span className="text-[10px] tracking-wider">{instance.port}</span>
</div>
);
}
diff --git a/dashboard/src/generated/types.ts b/dashboard/src/generated/types.ts
index 1c7622f3..0af26508 100644
--- a/dashboard/src/generated/types.ts
+++ b/dashboard/src/generated/types.ts
@@ -89,7 +89,6 @@ export interface ActivityLogEvent {
source: string;
requestId?: string;
sessionId?: string;
- actorId?: string;
agentId?: string;
method: string;
path: string;
diff --git a/dashboard/src/index.css b/dashboard/src/index.css
index 9c080af8..63a0cc6e 100644
--- a/dashboard/src/index.css
+++ b/dashboard/src/index.css
@@ -153,14 +153,11 @@ pre {
}
.dashboard-panel {
- border: 1px solid rgb(var(--brand-border-subtle-rgb) / 0.1);
- border-radius: 16px;
background: linear-gradient(
180deg,
rgb(var(--brand-surface-rgb) / 0.98),
rgb(var(--brand-surface-rgb) / 0.9)
);
- box-shadow: var(--panel-shadow);
}
.dashboard-panel-hover {
diff --git a/dashboard/src/pages/MonitoringPage.test.tsx b/dashboard/src/pages/MonitoringPage.test.tsx
index 9eae7ffb..586ac111 100644
--- a/dashboard/src/pages/MonitoringPage.test.tsx
+++ b/dashboard/src/pages/MonitoringPage.test.tsx
@@ -1,15 +1,31 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
import MonitoringPage from "./MonitoringPage";
import { useAppStore } from "../stores/useAppStore";
import type { Instance } from "../generated/types";
+import * as api from "../services/api";
vi.mock("../services/api", () => ({
stopInstance: vi.fn(),
+ fetchInstances: vi.fn().mockResolvedValue([]),
+ launchInstance: vi.fn().mockResolvedValue({
+ id: "inst_default",
+ profileId: "default",
+ profileName: "default",
+ port: "9868",
+ headless: false,
+ status: "starting",
+ startTime: "2026-03-06T10:00:00Z",
+ attached: false,
+ }),
fetchBackendConfig: vi.fn().mockResolvedValue({
- config: { multiInstance: { strategy: "always-on" } },
+ config: {
+ multiInstance: { strategy: "always-on" },
+ profiles: { defaultProfile: "default" },
+ instanceDefaults: { mode: "headed" },
+ },
}),
fetchActivity: vi.fn(),
fetchAllTabs: vi.fn(),
@@ -43,6 +59,7 @@ function ProfilesRouteProbe() {
describe("MonitoringPage", () => {
beforeEach(() => {
vi.clearAllMocks();
+ vi.useRealTimers();
useAppStore.setState({
instances,
tabsChartData: [],
@@ -66,6 +83,10 @@ describe("MonitoringPage", () => {
});
});
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
it("opens the selected profile from the active instance header", async () => {
render(
<MemoryRouter initialEntries={["/dashboard/monitoring"]}>
@@ -87,4 +108,94 @@ describe("MonitoringPage", () => {
});
expect(screen.getByText("prof_beta")).toBeInTheDocument();
});
+
+ it("retries while waiting for an expected default instance", async () => {
+ useAppStore.setState({
+ instances: [],
+ currentTabs: {},
+ selectedMonitoringInstanceId: null,
+ });
+
+ render(
+ <MemoryRouter initialEntries={["/dashboard/monitoring"]}>
+ <Routes>
+ <Route path="/dashboard/monitoring" element={<MonitoringPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ expect(
+ screen.getByText("Starting default instance..."),
+ ).toBeInTheDocument();
+
+ await waitFor(() => {
+ expect(api.fetchInstances).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ it("shows manual actions when no auto-started instance is expected", async () => {
+ vi.mocked(api.fetchBackendConfig).mockResolvedValueOnce({
+ config: {
+ multiInstance: { strategy: "no-instance" },
+ profiles: { defaultProfile: "default" },
+ instanceDefaults: { mode: "headed" },
+ },
+ } as never);
+ useAppStore.setState({
+ instances: [],
+ currentTabs: {},
+ selectedMonitoringInstanceId: null,
+ });
+
+ render(
+ <MemoryRouter initialEntries={["/dashboard/monitoring"]}>
+ <Routes>
+ <Route path="/dashboard/monitoring" element={<MonitoringPage />} />
+ <Route path="/dashboard/profiles" element={<ProfilesRouteProbe />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ expect(
+ await screen.findByRole("button", { name: "Start Default Instance" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Open Default Profile" }),
+ ).toBeInTheDocument();
+ });
+
+ it("starts the configured default instance from the empty state", async () => {
+ vi.mocked(api.fetchBackendConfig).mockResolvedValueOnce({
+ config: {
+ multiInstance: { strategy: "no-instance" },
+ profiles: { defaultProfile: "default" },
+ instanceDefaults: { mode: "headed" },
+ },
+ } as never);
+ useAppStore.setState({
+ instances: [],
+ currentTabs: {},
+ selectedMonitoringInstanceId: null,
+ });
+
+ render(
+ <MemoryRouter initialEntries={["/dashboard/monitoring"]}>
+ <Routes>
+ <Route path="/dashboard/monitoring" element={<MonitoringPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Start Default Instance" }),
+ );
+
+ await waitFor(() => {
+ expect(api.launchInstance).toHaveBeenCalledWith({
+ profileId: "default",
+ mode: "headed",
+ });
+ });
+ expect(api.fetchInstances).toHaveBeenCalled();
+ });
});
diff --git a/dashboard/src/pages/MonitoringPage.tsx b/dashboard/src/pages/MonitoringPage.tsx
index 67629a9a..a9374c8b 100644
--- a/dashboard/src/pages/MonitoringPage.tsx
+++ b/dashboard/src/pages/MonitoringPage.tsx
@@ -1,11 +1,14 @@
-import { useEffect, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useAppStore } from "../stores/useAppStore";
-import { EmptyState, ErrorBoundary } from "../components/atoms";
+import { Button, EmptyState, ErrorBoundary } from "../components/atoms";
import InstanceListItem from "../instances/InstanceListItem";
import InstanceTabsPanel from "../tabs/InstanceTabsPanel";
import * as api from "../services/api";
+const AUTO_INSTANCE_STRATEGIES = new Set(["always-on", "simple-autorestart"]);
+const STARTUP_REFRESH_DELAYS_MS = [500, 1000, 1500, 2500, 4000] as const;
+
export default function MonitoringPage() {
const {
instances,
@@ -16,11 +19,19 @@ export default function MonitoringPage() {
setMonitoringSidebarCollapsed: setSidebarCollapsed,
selectedMonitoringInstanceId,
setSelectedMonitoringInstanceId,
+ setInstances,
} = useAppStore();
const navigate = useNavigate();
const selectedId = selectedMonitoringInstanceId;
const setSelectedId = setSelectedMonitoringInstanceId;
const [strategy, setStrategy] = useState<string>("always-on");
+ const [defaultProfileId, setDefaultProfileId] = useState("default");
+ const [defaultLaunchMode, setDefaultLaunchMode] = useState<
+ "headed" | undefined
+ >(undefined);
+ const [startupRetryCount, setStartupRetryCount] = useState(0);
+ const [startingDefaultInstance, setStartingDefaultInstance] = useState(false);
+ const [launchError, setLaunchError] = useState("");
const memoryEnabled = settings.monitoring?.memoryMetrics ?? false;
// Fetch backend strategy once
@@ -29,20 +40,82 @@ export default function MonitoringPage() {
try {
const cfg = await api.fetchBackendConfig();
setStrategy(cfg.config.multiInstance.strategy);
+ setDefaultProfileId(cfg.config.profiles.defaultProfile || "default");
+ setDefaultLaunchMode(
+ cfg.config.instanceDefaults.mode === "headed" ? "headed" : undefined,
+ );
} catch {
// ignore — default to always-on
}
};
- load();
+ void load();
}, []);
- // Auto-select first running instance
+ const refreshInstances = useCallback(async () => {
+ const updated = await api.fetchInstances();
+ setInstances(updated);
+ return updated;
+ }, [setInstances]);
+
+ const expectsAutoInstance = AUTO_INSTANCE_STRATEGIES.has(strategy);
+ const availableInstance = useMemo(
+ () =>
+ instances.find((instance) => instance.status === "running") ??
+ instances.find((instance) => instance.status === "starting") ??
+ null,
+ [instances],
+ );
+ const hasAvailableInstance = availableInstance !== null;
+ const selectedInstance = instances.find(
+ (instance) => instance.id === selectedId,
+ );
+ const selectedTabs = selectedId ? currentTabs?.[selectedId] || [] : [];
+
+ // Auto-select the best available instance, including instances that are still starting.
useEffect(() => {
- if (!selectedId) {
- const firstRunning = instances.find((i) => i.status === "running");
- if (firstRunning) setSelectedId(firstRunning.id);
+ if (selectedInstance) {
+ return;
+ }
+ if (availableInstance) {
+ setSelectedId(availableInstance.id);
+ return;
+ }
+ if (selectedId) {
+ setSelectedId(null);
}
- }, [instances, selectedId, setSelectedId]);
+ }, [availableInstance, selectedId, selectedInstance, setSelectedId]);
+
+ // When the config expects a default instance, poll a few times during startup
+ // so the monitoring page doesn't immediately fall back to the manual empty state.
+ useEffect(() => {
+ if (
+ !expectsAutoInstance ||
+ hasAvailableInstance ||
+ startupRetryCount >= STARTUP_REFRESH_DELAYS_MS.length
+ ) {
+ return;
+ }
+
+ let cancelled = false;
+ const timer = window.setTimeout(() => {
+ setStartupRetryCount((count) => count + 1);
+ void refreshInstances().catch(() => {
+ if (!cancelled) {
+ // Ignore transient startup fetch failures; the retry window remains active.
+ }
+ });
+ }, STARTUP_REFRESH_DELAYS_MS[startupRetryCount]);
+
+ return () => {
+ cancelled = true;
+ window.clearTimeout(timer);
+ };
+ }, [
+ expectsAutoInstance,
+ hasAvailableInstance,
+ refreshInstances,
+ startupRetryCount,
+ ]);
const handleStop = async (id: string) => {
try {
@@ -52,24 +125,100 @@ export default function MonitoringPage() {
}
};
- const selectedInstance = instances?.find((i) => i.id === selectedId);
- const selectedTabs = selectedId ? currentTabs?.[selectedId] || [] : [];
+ const handleStartDefaultInstance = async () => {
+ setLaunchError("");
+ setStartingDefaultInstance(true);
+ try {
+ await api.launchInstance({
+ profileId: defaultProfileId,
+ mode: defaultLaunchMode,
+ });
+ await refreshInstances();
+ setStartupRetryCount(0);
+ } catch (error) {
+ console.error("Failed to start default instance", error);
+ setLaunchError(
+ error instanceof Error ? error.message : "Failed to start instance",
+ );
+ } finally {
+ setStartingDefaultInstance(false);
+ }
+ };
+
+ const startupRetriesRemaining = Math.max(
+ 0,
+ STARTUP_REFRESH_DELAYS_MS.length - startupRetryCount,
+ );
+ const waitingForExpectedInstance =
+ expectsAutoInstance && !hasAvailableInstance && startupRetriesRemaining > 0;
+
+ const manualActions = (
+ <div className="flex flex-wrap items-center justify-center gap-2">
+ <Button
+ variant="primary"
+ onClick={() => {
+ void handleStartDefaultInstance();
+ }}
+ loading={startingDefaultInstance}
+ >
+ Start Default Instance
+ </Button>
+ <Button
+ variant="secondary"
+ onClick={() =>
+ navigate("/dashboard/profiles", {
+ state: { selectedProfileKey: defaultProfileId },
+ })
+ }
+ >
+ Open Default Profile
+ </Button>
+ </div>
+ );
+
+ const renderEmptyMonitoringState = () => {
+ if (waitingForExpectedInstance) {
+ return (
+ <EmptyState
+ title="Starting default instance..."
+ description={`PinchTab is waiting for the default profile to come online. Checking again automatically (${startupRetriesRemaining} checks left).`}
+ icon="⏳"
+ />
+ );
+ }
+
+ return (
+ <div className="flex flex-col items-center gap-4">
+ {launchError && (
+ <div className="max-w-md rounded border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm text-destructive">
+ {launchError}
+ </div>
+ )}
+ <EmptyState
+ title="No active instances"
+ description={
+ expectsAutoInstance
+ ? "PinchTab expected a default instance, but it never became available. Start it manually or inspect the profile."
+ : "Start the default instance or open Profiles to launch a different one."
+ }
+ icon="📡"
+ action={manualActions}
+ />
+ </div>
+ );
+ };
return (
<ErrorBoundary>
<div className="flex h-full flex-col overflow-hidden">
{instances.length === 0 && (
<div className="flex flex-1 items-center justify-center">
- <EmptyState
- title="No instances yet"
- description="Start a profile to see instance data"
- icon="📡"
- />
+ {renderEmptyMonitoringState()}
</div>
)}
{instances.length > 0 && (
- <div className="dashboard-panel flex flex-1 flex-col overflow-hidden rounded-none!">
+ <div className="dashboard-panel flex flex-1 flex-col overflow-hidden rounded-none! border-t-0">
<div className="flex flex-1 overflow-hidden">
{!sidebarCollapsed && (
<div className="w-64 shrink-0 overflow-auto border-r border-border-subtle bg-bg-surface/50">
@@ -136,8 +285,8 @@ export default function MonitoringPage() {
instanceId={selectedId || undefined}
/>
) : (
- <div className="flex flex-1 items-center justify-center text-sm text-text-muted">
- Select an instance to view details
+ <div className="flex flex-1 items-center justify-center px-6">
+ {renderEmptyMonitoringState()}
</div>
)}
</div>
diff --git a/dashboard/src/pages/ProfilesPage.tsx b/dashboard/src/pages/ProfilesPage.tsx
index dd6ce71b..3d832806 100644
--- a/dashboard/src/pages/ProfilesPage.tsx
+++ b/dashboard/src/pages/ProfilesPage.tsx
@@ -189,7 +189,7 @@ export default function ProfilesPage() {
}
/>
) : (
- <div className="dashboard-panel flex h-full min-h-0 flex-col overflow-hidden rounded-none! lg:flex-row">
+ <div className="dashboard-panel flex h-full min-h-0 flex-col overflow-hidden rounded-none! border-t-0 lg:flex-row">
<div className="flex max-h-88 w-full shrink-0 flex-col overflow-hidden border-r border-border-subtle bg-bg-surface/50 lg:max-h-none lg:w-80">
<div className="flex items-center justify-between border-b border-border-subtle px-4 py-2.5">
<span className="text-xs font-medium text-text-muted">
diff --git a/dashboard/src/pages/SettingsPage.tsx b/dashboard/src/pages/SettingsPage.tsx
index ebf9ff59..a06b63f4 100644
--- a/dashboard/src/pages/SettingsPage.tsx
+++ b/dashboard/src/pages/SettingsPage.tsx
@@ -331,56 +331,6 @@ export default function SettingsPage() {
return (
<div className="flex h-full flex-col overflow-hidden">
- <div className="sticky top-0 z-10 border-b border-border-subtle bg-bg-surface/95 px-4 py-3 backdrop-blur">
- <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
- <div>
- <div className="dashboard-mono text-sm text-text-secondary">
- Server Version: {serverInfo?.version || "Unknown version"}
- </div>
- </div>
- <div className="flex flex-wrap items-center gap-2">
- {restartRequired && (
- <div className="rounded-sm border border-warning/25 bg-warning/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.08em] text-warning">
- Restart required
- </div>
- )}
- <Button
- variant="secondary"
- onClick={handleReset}
- disabled={!hasChanges || saving}
- >
- Reset
- </Button>
- <Button
- variant="primary"
- onClick={handleSave}
- disabled={!hasChanges || saving || !backendConfig}
- >
- {saving ? "Saving..." : "Save"}
- </Button>
- </div>
- </div>
- {(error || notice || restartReasons.length > 0) && (
- <div className="mt-3 flex flex-col gap-2">
- {error && (
- <div className="rounded-sm border border-destructive/35 bg-destructive/10 px-3 py-2 text-sm text-destructive">
- {error}
- </div>
- )}
- {notice && (
- <div className="rounded-sm border border-primary/30 bg-primary/10 px-3 py-2 text-sm text-primary">
- {notice}
- </div>
- )}
- {restartRequired && restartReasons.length > 0 && (
- <div className="rounded-sm border border-warning/25 bg-warning/10 px-3 py-2 text-sm text-warning">
- Restart needed for: {restartReasons.join(", ")}.
- </div>
- )}
- </div>
- )}
- </div>
-
<Modal
open={pendingElevatedAction !== null}
onClose={closeElevationPrompt}
@@ -436,10 +386,13 @@ export default function SettingsPage() {
</form>
</Modal>
- <div className="flex flex-1 flex-col gap-6 overflow-hidden p-4 lg:flex-row lg:p-6">
- <aside className="flex w-full shrink-0 flex-col gap-4 overflow-y-auto lg:w-72">
+ <div className="flex flex-1 flex-col overflow-hidden lg:flex-row">
+ <aside className="flex w-full shrink-0 flex-col overflow-y-auto border-b border-border-subtle lg:w-72 lg:border-b-0 lg:border-r">
<Card className="p-3">
- <div className="dashboard-section-label mb-3">Sections</div>
+ <div className="dashboard-section-label">Settings</div>
+ <div className="mb-3 dashboard-mono text-xs text-text-muted">
+ Version: {serverInfo?.version || "dev"}
+ </div>
<div className="flex flex-col gap-1.5">
{sections.map((section) => (
<button
@@ -463,6 +416,47 @@ export default function SettingsPage() {
</aside>
<div className="flex-1 overflow-y-auto pr-1">
+ <div className="sticky top-0 z-10 flex flex-wrap items-center gap-2 border-b border-border-subtle bg-bg-surface/95 p-3 backdrop-blur">
+ {restartRequired && (
+ <div className="rounded-sm border border-warning/25 bg-warning/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.08em] text-warning">
+ Restart required
+ </div>
+ )}
+ <div className="flex-1" />
+ <Button
+ variant="secondary"
+ onClick={handleReset}
+ disabled={!hasChanges || saving}
+ >
+ Reset
+ </Button>
+ <Button
+ variant="primary"
+ onClick={handleSave}
+ disabled={!hasChanges || saving || !backendConfig}
+ >
+ {saving ? "Saving..." : "Save"}
+ </Button>
+ </div>
+ {(error || notice || restartReasons.length > 0) && (
+ <div className="flex flex-col gap-2 px-3 pb-3">
+ {error && (
+ <div className="rounded-sm border border-destructive/35 bg-destructive/10 px-3 py-2 text-sm text-destructive">
+ {error}
+ </div>
+ )}
+ {notice && (
+ <div className="rounded-sm border border-primary/30 bg-primary/10 px-3 py-2 text-sm text-primary">
+ {notice}
+ </div>
+ )}
+ {restartRequired && restartReasons.length > 0 && (
+ <div className="rounded-sm border border-warning/25 bg-warning/10 px-3 py-2 text-sm text-warning">
+ Restart needed for: {restartReasons.join(", ")}.
+ </div>
+ )}
+ </div>
+ )}
{loading || !backendConfig ? (
<Card className="p-6">
<div className="text-sm text-text-muted">Loading settings…</div>
diff --git a/dashboard/src/services/api.test.ts b/dashboard/src/services/api.test.ts
index a2bf5dcd..567c559a 100644
--- a/dashboard/src/services/api.test.ts
+++ b/dashboard/src/services/api.test.ts
@@ -1,5 +1,11 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { createProfile, fetchProfiles, probeBackendAuth } from "./api";
+import {
+ createProfile,
+ fetchProfiles,
+ handleRealtimeAuthFailure,
+ probeBackendAuth,
+} from "./api";
+import { SERVER_UNREACHABLE_EVENT } from "./auth";
describe("api request headers", () => {
beforeEach(() => {
@@ -58,4 +64,28 @@ describe("api request headers", () => {
"dashboard",
);
});
+
+ it("dispatches a server-unreachable event when requests lose transport", async () => {
+ const handler = vi.fn();
+ const fetchMock = vi.fn().mockRejectedValue(new TypeError("NetworkError"));
+ vi.stubGlobal("fetch", fetchMock);
+ window.addEventListener(SERVER_UNREACHABLE_EVENT, handler);
+
+ await expect(fetchProfiles()).rejects.toThrow("NetworkError");
+
+ expect(handler).toHaveBeenCalledTimes(1);
+ window.removeEventListener(SERVER_UNREACHABLE_EVENT, handler);
+ });
+
+ it("dispatches a server-unreachable event when realtime auth probing fails", async () => {
+ const handler = vi.fn();
+ const fetchMock = vi.fn().mockRejectedValue(new TypeError("NetworkError"));
+ vi.stubGlobal("fetch", fetchMock);
+ window.addEventListener(SERVER_UNREACHABLE_EVENT, handler);
+
+ await handleRealtimeAuthFailure();
+
+ expect(handler).toHaveBeenCalledTimes(1);
+ window.removeEventListener(SERVER_UNREACHABLE_EVENT, handler);
+ });
});
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 068a32e6..59195627 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -26,7 +26,11 @@ import {
normalizeDashboardServerInfo,
normalizeMonitoringSnapshot,
} from "../types";
-import { dispatchAuthRequired, sameOriginUrl } from "./auth";
+import {
+ dispatchAuthRequired,
+ dispatchServerUnreachable,
+ sameOriginUrl,
+} from "./auth";
const BASE = ""; // Uses proxy in dev
const DASHBOARD_SOURCE_HEADER = "X-PinchTab-Source";
@@ -75,10 +79,16 @@ async function request<T>(
options?: RequestInit,
meta?: RequestMeta,
): Promise<T> {
- const res = await fetch(BASE + url, {
- ...withDashboardSource(options),
- credentials: "same-origin",
- });
+ let res: Response;
+ try {
+ res = await fetch(BASE + url, {
+ ...withDashboardSource(options),
+ credentials: "same-origin",
+ });
+ } catch (error) {
+ dispatchServerUnreachable();
+ throw error;
+ }
if (!res.ok) {
const err = await parseError(res);
if (res.status === 401) {
@@ -94,10 +104,16 @@ async function requestText(
options?: RequestInit,
meta?: RequestMeta,
): Promise<string> {
- const res = await fetch(BASE + url, {
- ...withDashboardSource(options),
- credentials: "same-origin",
- });
+ let res: Response;
+ try {
+ res = await fetch(BASE + url, {
+ ...withDashboardSource(options),
+ credentials: "same-origin",
+ });
+ } catch (error) {
+ dispatchServerUnreachable();
+ throw error;
+ }
if (!res.ok) {
const err = await parseError(res);
if (res.status === 401) {
@@ -113,10 +129,16 @@ async function requestBlob(
options?: RequestInit,
meta?: RequestMeta,
): Promise<Blob> {
- const res = await fetch(BASE + url, {
- ...withDashboardSource(options),
- credentials: "same-origin",
- });
+ let res: Response;
+ try {
+ res = await fetch(BASE + url, {
+ ...withDashboardSource(options),
+ credentials: "same-origin",
+ });
+ } catch (error) {
+ dispatchServerUnreachable();
+ throw error;
+ }
if (!res.ok) {
const err = await parseError(res);
if (res.status === 401) {
@@ -332,7 +354,7 @@ export interface Session {
}
export async function fetchSessions(): Promise<Session[]> {
- return request<Session[]>("/api/sessions");
+ return request<Session[]>("/sessions");
}
export async function fetchAgent(
@@ -472,6 +494,15 @@ export interface SystemEvent {
instance?: Instance;
}
+export function activityEventSource(event: ActivityEvent): string {
+ const source = event.details?.source;
+ return typeof source === "string" ? source.trim().toLowerCase() : "";
+}
+
+export function isClientActivityEvent(event: ActivityEvent): boolean {
+ return activityEventSource(event) === "client";
+}
+
export type EventHandler = {
onSystem?: (event: SystemEvent) => void;
onActivity?: (event: ActivityEvent) => void;
@@ -591,6 +622,6 @@ export async function handleRealtimeAuthFailure(): Promise<void> {
dispatchAuthRequired("missing_token");
}
} catch {
- // ignore transient network failures
+ dispatchServerUnreachable();
}
}
diff --git a/dashboard/src/services/auth.test.ts b/dashboard/src/services/auth.test.ts
index 55a63222..cdc9660f 100644
--- a/dashboard/src/services/auth.test.ts
+++ b/dashboard/src/services/auth.test.ts
@@ -2,8 +2,10 @@ import { describe, expect, it, vi } from "vitest";
import {
AUTH_REQUIRED_EVENT,
AUTH_STATE_CHANGED_EVENT,
+ SERVER_UNREACHABLE_EVENT,
dispatchAuthRequired,
dispatchAuthStateChanged,
+ dispatchServerUnreachable,
sameOriginUrl,
} from "./auth";
@@ -30,6 +32,16 @@ describe("auth helpers", () => {
window.removeEventListener(AUTH_STATE_CHANGED_EVENT, handler);
});
+ it("dispatches the server-unreachable event", () => {
+ const handler = vi.fn();
+ window.addEventListener(SERVER_UNREACHABLE_EVENT, handler);
+
+ dispatchServerUnreachable();
+
+ expect(handler).toHaveBeenCalledTimes(1);
+ window.removeEventListener(SERVER_UNREACHABLE_EVENT, handler);
+ });
+
it("keeps dashboard URLs same-origin without appending auth state", () => {
vi.stubGlobal("location", new URL("https://pinchtab.com/dashboard"));
diff --git a/dashboard/src/services/auth.ts b/dashboard/src/services/auth.ts
index 70141eb0..a82c7838 100644
--- a/dashboard/src/services/auth.ts
+++ b/dashboard/src/services/auth.ts
@@ -1,5 +1,6 @@
const AUTH_REQUIRED_EVENT = "pinchtab-auth-required";
const AUTH_STATE_CHANGED_EVENT = "pinchtab-auth-state-changed";
+const SERVER_UNREACHABLE_EVENT = "pinchtab-server-unreachable";
export function dispatchAuthRequired(reason: string): void {
window.dispatchEvent(
@@ -13,9 +14,17 @@ export function dispatchAuthStateChanged(): void {
window.dispatchEvent(new Event(AUTH_STATE_CHANGED_EVENT));
}
+export function dispatchServerUnreachable(): void {
+ window.dispatchEvent(new Event(SERVER_UNREACHABLE_EVENT));
+}
+
export function sameOriginUrl(url: string): string {
const absolute = new URL(url, window.location.origin);
return absolute.pathname + absolute.search;
}
-export { AUTH_REQUIRED_EVENT, AUTH_STATE_CHANGED_EVENT };
+export {
+ AUTH_REQUIRED_EVENT,
+ AUTH_STATE_CHANGED_EVENT,
+ SERVER_UNREACHABLE_EVENT,
+};
diff --git a/dashboard/src/services/dashboardRealtime.ts b/dashboard/src/services/dashboardRealtime.ts
index 1cd4f276..42aa9d83 100644
--- a/dashboard/src/services/dashboardRealtime.ts
+++ b/dashboard/src/services/dashboardRealtime.ts
@@ -1,6 +1,6 @@
import type { Agent } from "../generated/types";
import { useAppStore } from "../stores/useAppStore";
-import { subscribeToEvents } from "./api";
+import { isClientActivityEvent, subscribeToEvents } from "./api";
interface RealtimeHandle {
consumers: number;
@@ -69,6 +69,9 @@ function startDashboardRealtime(includeMemory: boolean) {
console.log("System event:", event);
},
onActivity: (event) => {
+ if (!isClientActivityEvent(event)) {
+ return;
+ }
const state = useAppStore.getState();
state.upsertAgentFromEvent(event);
state.appendAgentEvent(event);
diff --git a/dashboard/src/stores/useAppStore.ts b/dashboard/src/stores/useAppStore.ts
index 76711d25..4d4e71b0 100644
--- a/dashboard/src/stores/useAppStore.ts
+++ b/dashboard/src/stores/useAppStore.ts
@@ -426,7 +426,7 @@ export const useAppStore = create<AppState>((set) => ({
selectedMonitoringInstanceId: null,
setSelectedMonitoringInstanceId: (selectedMonitoringInstanceId) =>
set({ selectedMonitoringInstanceId }),
- monitoringShowTelemetry: false,
+ monitoringShowTelemetry: true,
setMonitoringShowTelemetry: (monitoringShowTelemetry) =>
set({ monitoringShowTelemetry }),
}));
diff --git a/dashboard/src/tabs/InstanceTabsPanel.test.tsx b/dashboard/src/tabs/InstanceTabsPanel.test.tsx
index ea2d3016..f88539b5 100644
--- a/dashboard/src/tabs/InstanceTabsPanel.test.tsx
+++ b/dashboard/src/tabs/InstanceTabsPanel.test.tsx
@@ -1,20 +1,24 @@
import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
-import { describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import type { InstanceTab } from "../generated/types";
import InstanceTabsPanel from "./InstanceTabsPanel";
-vi.mock("../stores/useAppStore", () => ({
- useAppStore: () => ({
- instances: [],
- tabsChartData: [],
- memoryChartData: [],
- serverChartData: [],
- currentMetrics: {},
- settings: {},
- monitoringShowTelemetry: false,
- setMonitoringShowTelemetry: vi.fn(),
+const mockStore = {
+ instances: [],
+ tabsChartData: [],
+ memoryChartData: [],
+ serverChartData: [],
+ currentMetrics: {},
+ settings: {},
+ monitoringShowTelemetry: true,
+ setMonitoringShowTelemetry: vi.fn((show: boolean) => {
+ mockStore.monitoringShowTelemetry = show;
}),
+};
+
+vi.mock("../stores/useAppStore", () => ({
+ useAppStore: () => mockStore,
}));
const tabs: InstanceTab[] = [
@@ -33,7 +37,47 @@ const tabs: InstanceTab[] = [
];
describe("InstanceTabsPanel", () => {
+ beforeEach(() => {
+ mockStore.monitoringShowTelemetry = true;
+ mockStore.setMonitoringShowTelemetry.mockClear();
+ });
+
+ it("enables telemetry once when tabs disappear", () => {
+ mockStore.monitoringShowTelemetry = false;
+ render(<InstanceTabsPanel tabs={[]} />);
+
+ expect(mockStore.setMonitoringShowTelemetry).toHaveBeenCalledTimes(1);
+ expect(mockStore.setMonitoringShowTelemetry).toHaveBeenCalledWith(true);
+ });
+
+ it("shows telemetry by default without marking existing tabs as new", () => {
+ render(<InstanceTabsPanel tabs={tabs} />);
+
+ expect(screen.getByText("Collecting data...")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Tabs" })).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Tabs \(\d+ new\)/ }),
+ ).toBeNull();
+ });
+
+ it("marks only newly added tabs and clears the badge after visiting tabs", async () => {
+ const user = userEvent.setup();
+ const { rerender } = render(<InstanceTabsPanel tabs={[tabs[0]]} />);
+
+ rerender(<InstanceTabsPanel tabs={tabs} />);
+ expect(
+ screen.getByRole("button", { name: "Tabs (1 new)" }),
+ ).toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: "Tabs (1 new)" }));
+ rerender(<InstanceTabsPanel tabs={tabs} />);
+
+ expect(screen.getByRole("button", { name: "Tabs" })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Tabs (1 new)" })).toBeNull();
+ });
+
it("auto-selects the first tab and shows its details", () => {
+ mockStore.monitoringShowTelemetry = false;
render(<InstanceTabsPanel tabs={tabs} />);
const titleHeading = screen.getByRole("heading", { name: "Alpha Tab" });
@@ -48,10 +92,11 @@ describe("InstanceTabsPanel", () => {
it("updates the selected tab details when a tab is clicked", async () => {
const user = userEvent.setup();
- render(<InstanceTabsPanel tabs={tabs} />);
+ const { rerender } = render(<InstanceTabsPanel tabs={tabs} />);
const betaTabItem = screen.getByRole("button", { name: /^Beta Tab$/ });
await user.click(betaTabItem);
+ rerender(<InstanceTabsPanel tabs={tabs} />);
const titleHeading = screen.getByRole("heading", { name: "Beta Tab" });
const detailPanel = titleHeading.closest(".rounded-xl") as HTMLElement;
@@ -67,6 +112,7 @@ describe("InstanceTabsPanel", () => {
it("follows the focused tab until a manual selection is pinned", async () => {
const user = userEvent.setup();
+ mockStore.monitoringShowTelemetry = false;
const { rerender } = render(<InstanceTabsPanel tabs={tabs} />);
rerender(<InstanceTabsPanel tabs={[tabs[1], tabs[0]]} />);
@@ -99,6 +145,7 @@ describe("InstanceTabsPanel", () => {
});
it("shows an empty state when there are no tabs", () => {
+ mockStore.monitoringShowTelemetry = false;
render(<InstanceTabsPanel tabs={[]} />);
expect(screen.getByText("No tabs open")).toBeInTheDocument();
diff --git a/dashboard/src/tabs/InstanceTabsPanel.tsx b/dashboard/src/tabs/InstanceTabsPanel.tsx
index 30c1c6d2..2a95d897 100644
--- a/dashboard/src/tabs/InstanceTabsPanel.tsx
+++ b/dashboard/src/tabs/InstanceTabsPanel.tsx
@@ -13,6 +13,13 @@ interface Props {
instanceId?: string;
}
+function sameIds(left: string[], right: string[]): boolean {
+ return (
+ left.length === right.length &&
+ left.every((value, index) => value === right[index])
+ );
+}
+
export default function InstanceTabsPanel({
tabs,
emptyMessage = "No tabs open",
@@ -20,7 +27,10 @@ export default function InstanceTabsPanel({
}: Props) {
const [selectedTabId, setSelectedTabId] = useState<string | null>(null);
const [selectionPinned, setSelectionPinned] = useState(false);
- const manualTabsRef = useRef(false);
+ const [acknowledgedTabIds, setAcknowledgedTabIds] = useState<string[]>(() =>
+ tabs.map((tab) => tab.id),
+ );
+ const previousInstanceIdRef = useRef(instanceId);
const {
instances,
@@ -34,6 +44,7 @@ export default function InstanceTabsPanel({
} = useAppStore();
const memoryEnabled = settings.monitoring?.memoryMetrics ?? false;
+ const currentTabIds = useMemo(() => tabs.map((tab) => tab.id), [tabs]);
const selectedInstance = instances.find((i) => i.id === instanceId);
const chartInstances = useMemo(
@@ -53,17 +64,12 @@ export default function InstanceTabsPanel({
if (tabs.length === 0) {
setSelectedTabId(null);
setSelectionPinned(false);
- if (!manualTabsRef.current) {
+ if (!showTelemetry) {
setShowTelemetry(true);
}
return;
}
- if (showTelemetry && !manualTabsRef.current) {
- setShowTelemetry(false);
- }
- manualTabsRef.current = false;
-
if (selectionPinned && tabs.some((tab) => tab.id === selectedTabId)) {
return;
}
@@ -85,6 +91,32 @@ export default function InstanceTabsPanel({
() => tabs.find((tab) => tab.id === selectedTabId) ?? null,
[selectedTabId, tabs],
);
+ const newTabsCount = useMemo(() => {
+ if (!showTelemetry) {
+ return 0;
+ }
+ const acknowledged = new Set(acknowledgedTabIds);
+ return currentTabIds.reduce(
+ (count, tabId) => count + (acknowledged.has(tabId) ? 0 : 1),
+ 0,
+ );
+ }, [acknowledgedTabIds, currentTabIds, showTelemetry]);
+
+ useEffect(() => {
+ if (previousInstanceIdRef.current === instanceId) {
+ return;
+ }
+ previousInstanceIdRef.current = instanceId;
+ setAcknowledgedTabIds(currentTabIds);
+ }, [currentTabIds, instanceId]);
+
+ useEffect(() => {
+ if (!showTelemetry) {
+ setAcknowledgedTabIds((previous) =>
+ sameIds(previous, currentTabIds) ? previous : currentTabIds,
+ );
+ }
+ }, [currentTabIds, showTelemetry]);
return (
<div className="flex min-h-0 flex-1 flex-col">
@@ -93,10 +125,14 @@ export default function InstanceTabsPanel({
selectedTabId={selectedTabId}
pinnedTabId={selectionPinned ? selectedTabId : null}
telemetryActive={showTelemetry}
+ newTabsCount={newTabsCount}
onSelect={(id) => {
+ setAcknowledgedTabIds(currentTabIds);
setSelectedTabId(id);
setSelectionPinned(true);
- setShowTelemetry(false);
+ if (showTelemetry) {
+ setShowTelemetry(false);
+ }
}}
onTogglePinned={(id) => {
if (selectionPinned && selectedTabId === id) {
@@ -104,13 +140,20 @@ export default function InstanceTabsPanel({
setSelectedTabId(tabs[0]?.id ?? null);
return;
}
+ setAcknowledgedTabIds(currentTabIds);
setSelectedTabId(id);
setSelectionPinned(true);
- setShowTelemetry(false);
+ if (showTelemetry) {
+ setShowTelemetry(false);
+ }
}}
onSetTelemetry={(active) => {
- manualTabsRef.current = !active;
- setShowTelemetry(active);
+ if (!active) {
+ setAcknowledgedTabIds(currentTabIds);
+ }
+ if (active !== showTelemetry) {
+ setShowTelemetry(active);
+ }
}}
/>
diff --git a/dashboard/src/tabs/TabBar.tsx b/dashboard/src/tabs/TabBar.tsx
index 10b8b94c..6bc16148 100644
--- a/dashboard/src/tabs/TabBar.tsx
+++ b/dashboard/src/tabs/TabBar.tsx
@@ -6,6 +6,7 @@ interface Props {
selectedTabId: string | null;
pinnedTabId?: string | null;
telemetryActive?: boolean;
+ newTabsCount?: number;
onSelect: (id: string) => void;
onTogglePinned?: (id: string) => void;
onTabClosed?: () => void;
@@ -37,12 +38,15 @@ export default function TabBar({
selectedTabId,
pinnedTabId,
telemetryActive,
+ newTabsCount = 0,
onSelect,
onTogglePinned,
onTabClosed,
onToggleTelemetry,
onSetTelemetry,
}: Props) {
+ const showTabsAttention = newTabsCount > 0;
+
const handleClose = async (e: React.MouseEvent, tabId: string) => {
e.stopPropagation();
try {
@@ -53,7 +57,7 @@ export default function TabBar({
}
};
return (
- <div className="flex min-h-0 items-end gap-px overflow-x-auto border-b border-border-subtle bg-black/10">
+ <div className="flex h-9 items-end gap-px overflow-x-auto border-b border-border-subtle bg-black/10">
{tabs.map((tab) => {
const isSelected = tab.id === selectedTabId && !telemetryActive;
const isPinned = tab.id === pinnedTabId;
@@ -119,7 +123,10 @@ export default function TabBar({
onSetTelemetry ? onSetTelemetry(false) : onToggleTelemetry?.()
}
title="Tabs"
- className={`shrink-0 rounded p-1.5 transition-colors ${
+ aria-label={
+ showTabsAttention ? `Tabs (${newTabsCount} new)` : "Tabs"
+ }
+ className={`relative shrink-0 rounded p-1.5 transition-colors ${
!telemetryActive
? "bg-bg-hover text-text-primary"
: "text-text-muted hover:bg-white/10 hover:text-text-secondary"
@@ -139,6 +146,12 @@ export default function TabBar({
<path d="M3 9h18" />
<path d="M9 3v6" />
</svg>
+ {showTabsAttention && (
+ <span
+ aria-hidden="true"
+ className="absolute right-1 top-1 h-2 w-2 rounded-full bg-red-500 ring-2 ring-bg-surface"
+ />
+ )}
</button>
<button
type="button"
diff --git a/dashboard/src/types/index.ts b/dashboard/src/types/index.ts
index 4a9f44c9..c45f1487 100644
--- a/dashboard/src/types/index.ts
+++ b/dashboard/src/types/index.ts
@@ -74,6 +74,28 @@ export interface BackendSessionsConfig {
dashboard: BackendDashboardSessionConfig;
}
+export interface BackendActivityEventsConfig {
+ dashboard: boolean;
+ server: boolean;
+ bridge: boolean;
+ orchestrator: boolean;
+ scheduler: boolean;
+ mcp: boolean;
+ other: boolean;
+}
+
+export interface BackendActivityConfig {
+ enabled: boolean;
+ sessionIdleSec: number;
+ retentionDays: number;
+ stateDir: string;
+ events: BackendActivityEventsConfig;
+}
+
+export interface BackendObservabilityConfig {
+ activity: BackendActivityConfig;
+}
+
export interface BackendBrowserConfig {
version: string;
binary: string;
@@ -169,6 +191,7 @@ export interface BackendConfig {
profiles: BackendProfilesConfig;
multiInstance: BackendMultiInstanceConfig;
timeouts: BackendTimeoutsConfig;
+ observability: BackendObservabilityConfig;
sessions: BackendSessionsConfig;
autoSolver: BackendAutoSolverConfig;
}
@@ -251,6 +274,23 @@ export const defaultBackendConfig: BackendConfig = {
shutdownSec: 10,
waitNavMs: 1000,
},
+ observability: {
+ activity: {
+ enabled: true,
+ sessionIdleSec: 1800,
+ retentionDays: 1,
+ stateDir: "",
+ events: {
+ dashboard: false,
+ server: false,
+ bridge: false,
+ orchestrator: false,
+ scheduler: false,
+ mcp: false,
+ other: false,
+ },
+ },
+ },
sessions: {
dashboard: {
persist: true,
@@ -325,6 +365,18 @@ export function normalizeBackendConfig(
...defaultBackendConfig.timeouts,
...(input?.timeouts ?? {}),
},
+ observability: {
+ ...defaultBackendConfig.observability,
+ ...(input?.observability ?? {}),
+ activity: {
+ ...defaultBackendConfig.observability.activity,
+ ...(input?.observability?.activity ?? {}),
+ events: {
+ ...defaultBackendConfig.observability.activity.events,
+ ...(input?.observability?.activity?.events ?? {}),
+ },
+ },
+ },
sessions: {
...defaultBackendConfig.sessions,
...(input?.sessions ?? {}),
diff --git a/docs/endpoints.md b/docs/endpoints.md
index 3176f724..90881b5a 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -1,12 +1,13 @@
# Endpoints Reference
-This page lists the live HTTP surface exposed by PinchTab. Some routes are only available in bridge mode, some only in full server mode, and some are gated by security settings.
+This page summarizes the live HTTP surface exposed by PinchTab. Some routes are only available in bridge mode, some only in full server mode, and some are gated by security settings.
## Health And Server Metadata
```text
GET /health
POST /ensure-chrome
+POST /browser/restart
GET /openapi.json
GET /help (alias for /openapi.json)
GET /metrics
@@ -37,6 +38,22 @@ Notes:
- `server.token` is treated as write-only by `PUT /api/config`
- auth routes are for the dashboard session flow
+## Dashboard Events And Agents
+
+```text
+GET /api/events
+GET /api/agents
+GET /api/agents/{id}
+GET /api/agents/{id}/events
+POST /api/agents/{id}/events
+```
+
+Notes:
+
+- `/api/events` is the dashboard SSE stream
+- `/api/agents/{id}/events` streams one agent's recent events
+- `POST /api/agents/{id}/events` ingests agent activity into the dashboard feed
+
## Navigation And Tabs
```text
@@ -240,6 +257,8 @@ DELETE /tabs/{id}/storage
Storage is captured only for the current origin (active tab). Multi-origin storage is not supported.
+All storage routes are gated by `security.allowStateExport`.
+
GET query parameters:
- `type` — `local`, `session`, or empty (both)
@@ -274,7 +293,7 @@ State management saves and restores browser state (cookies, localStorage, sessio
Notes:
-- `POST /state/save` and `GET /state/show` are gated by `security.allowStateExport`
+- `/storage`, `/tabs/{id}/storage`, `GET /state/show`, `POST /state/save`, `POST /state/load`, `DELETE /state`, and `POST /state/clean` are gated by `security.allowStateExport`
- state files are stored in `{stateDir}/sessions/` with `0600` permissions
- optional AES-256-GCM encryption via `PINCHTAB_STATE_KEY` environment variable
- storage is captured only for the current origin (active tab)
@@ -408,6 +427,7 @@ POST /instances/launch
POST /instances/attach
POST /instances/attach-bridge
POST /instances/{id}/start
+POST /instances/{id}/restart
POST /instances/{id}/stop
GET /instances/{id}/logs
GET /instances/{id}/logs/stream
@@ -445,7 +465,6 @@ Activity query parameters include:
- `source`
- `requestId`
- `sessionId`
-- `actorId`
- `agentId`
- `instanceId`
- `profileId`
@@ -459,7 +478,7 @@ 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>`
+- named non-client sources such as `dashboard` or `orchestrator` are stored in source-specific daily files only when enabled under `observability.activity.events`, and can then be queried with `?source=<name>`
Scheduler routes are only present when `scheduler.enabled` is true.
@@ -467,16 +486,17 @@ Scheduler routes are only present when `scheduler.enabled` is true.
| Method | Path | Description |
|--------|------|-------------|
-| `POST` | `/api/agent-sessions` | Create a new agent session (body: `{agentId, label?}`) |
-| `GET` | `/api/agent-sessions` | List all agent sessions |
-| `GET` | `/api/agent-sessions/me` | Get current session (requires `Authorization: Session` auth) |
-| `GET` | `/api/agent-sessions/{id}` | Get session details by ID |
-| `POST` | `/api/agent-sessions/{id}/rotate` | Rotate session token |
-| `POST` | `/api/agent-sessions/{id}/revoke` | Revoke session |
+| `POST` | `/sessions` | Create a new agent session (body: `{agentId, label?}`) |
+| `GET` | `/sessions` | List all agent sessions |
+| `GET` | `/sessions/me` | Get current session (requires `Authorization: Session` auth) |
+| `GET` | `/sessions/{id}` | Get session details by ID |
+| `POST` | `/sessions/{id}/revoke` | Revoke session |
+
+`POST /sessions`, `GET /sessions`, and `GET /sessions/{id}` require dashboard auth (bearer or cookie). The `/me` endpoint requires session auth. `POST /sessions/{id}/revoke` allows dashboard auth or the owning session.
-All endpoints except `/me` require dashboard auth (bearer or cookie). The `/me` endpoint requires session auth.
+Create returns `sessionToken` — the plaintext token shown only once.
-Create and rotate return `sessionToken` — the plaintext token shown only once.
+Session-authenticated callers cannot reach dashboard/admin endpoint families such as config, dashboard agent listings, dashboard event streams, session management, profile management, instance management, or cache controls. They are intended for trusted automation in controlled environments, not for untrusted multi-tenant isolation.
## Feature Gates
@@ -490,7 +510,7 @@ These gates are not ordinary feature toggles. Enabling them is a documented, non
- clipboard routes -> `security.allowClipboard`
- attach routes -> `security.attach`
- screencast routes -> `security.allowScreencast`
-- `/state/save` and `/state/show` -> `security.allowStateExport`
+- storage routes and the full state-management family (`/state/show`, `/state/save`, `/state/load`, `DELETE /state`, `POST /state/clean`) -> `security.allowStateExport`
## Error Response Format
diff --git a/docs/guides/agent-identity.md b/docs/guides/agent-identity.md
index 3eda5813..ac1ae2ea 100644
--- a/docs/guides/agent-identity.md
+++ b/docs/guides/agent-identity.md
@@ -44,7 +44,7 @@ The `X-Agent-Id` header is sent with every request. No server-side setup require
## Agent Sessions
-> **⚠️ Security notice:** Agent sessions are designed for **trusted environments** — local machines, private networks, or setups where all agents are under your control. Do not expose the session management API (`/api/sessions`) to the public internet. Any authenticated caller (bearer token or dashboard cookie) can create, list, rotate, and revoke sessions for any agent. There is no per-agent authorization scoping — treat session management endpoints like admin APIs.
+> **⚠️ Security notice:** Agent sessions are designed for **trusted, controlled environments** — local machines, private networks, CI, and setups where all agents are under your control. Do not expose the session management API (`/sessions`) to the public internet. Any authenticated caller (bearer token or dashboard cookie) can create, list, and inspect sessions for any agent. Session-authenticated callers are blocked from dashboard/admin endpoint families, but sessions are still not a multi-tenant isolation boundary.
Sessions are the full identity solution. Each session is a revocable, server-managed token tied to a specific agent ID. Sessions provide:
@@ -53,7 +53,6 @@ Sessions are the full identity solution. Each session is a revocable, server-man
- **Idle timeout** — sessions expire after 12 hours of inactivity (configurable)
- **Max lifetime** — hard expiry after 24 hours (configurable)
- **Revocation** — kill a session without rotating the server token
-- **Rotation** — generate a new token for an existing session
### Enable Sessions
@@ -81,7 +80,7 @@ Modes:
### Create a Session
```bash
-curl -X POST http://localhost:9867/api/sessions \
+curl -X POST http://localhost:9867/sessions \
-H "Authorization: Bearer $PINCHTAB_TOKEN" \
-H "Content-Type: application/json" \
-d '{"agentId": "bosch", "label": "research task"}'
@@ -125,15 +124,11 @@ No need to set `--agent-id` — the session carries the agent identity.
```bash
# List all sessions
-curl http://localhost:9867/api/sessions \
- -H "Authorization: Bearer $PINCHTAB_TOKEN"
-
-# Rotate token (old token invalidated, new one returned)
-curl -X POST http://localhost:9867/api/sessions/ses_e6ac8132fe7e7016/rotate \
+curl http://localhost:9867/sessions \
-H "Authorization: Bearer $PINCHTAB_TOKEN"
# Revoke
-curl -X POST http://localhost:9867/api/sessions/ses_e6ac8132fe7e7016/revoke \
+curl -X POST http://localhost:9867/sessions/ses_e6ac8132fe7e7016/revoke \
-H "Authorization: Bearer $PINCHTAB_TOKEN"
```
@@ -146,6 +141,8 @@ curl -X POST http://localhost:9867/api/sessions/ses_e6ac8132fe7e7016/revoke \
| `sessions.agent.idleTimeoutSec` | `43200` (12h) | Session expires after this many seconds of inactivity |
| `sessions.agent.maxLifetimeSec` | `86400` (24h) | Hard session expiry |
+If a session record carries explicit grants, those grants narrow which endpoint groups the session may call. If a session has no explicit grants, it can use the normal non-admin automation API by default, while dashboard/admin routes remain blocked. That default is meant for trusted automation only.
+
## Choosing the Right Level
| Scenario | Recommendation |
@@ -153,4 +150,4 @@ curl -X POST http://localhost:9867/api/sessions/ses_e6ac8132fe7e7016/revoke \
| One agent, local only | Server token is enough |
| Multiple agents, want attribution | Add `--agent-id` or `PINCHTAB_AGENT_ID` |
| Production multi-agent, need revocation | Use agent sessions |
-| Shared server, untrusted agents | Use sessions with `mode: "required"` |
+| Shared server, untrusted agents | Run separate PinchTab instances; sessions are not sufficient isolation |
diff --git a/docs/guides/data-storage.md b/docs/guides/data-storage.md
index 64f2727a..c77e4251 100644
--- a/docs/guides/data-storage.md
+++ b/docs/guides/data-storage.md
@@ -119,13 +119,23 @@ By default PinchTab keeps 1 day of activity data and prunes older daily files wh
"observability": {
"activity": {
"retentionDays": 1,
- "sessionIdleSec": 1800
+ "sessionIdleSec": 1800,
+ "events": {
+ "dashboard": false,
+ "server": false,
+ "bridge": false,
+ "orchestrator": false,
+ "scheduler": false,
+ "mcp": false,
+ "other": false
+ }
}
}
}
```
`retentionDays` controls on-disk retention for activity logs. `sessionIdleSec` controls session grouping only.
+`events` controls which non-client sources are recorded. Client events are always recorded.
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.
@@ -139,7 +149,7 @@ In orchestrator mode, child instances get their own state directory under the pr
PinchTab writes a child `config.json` there so the launched instance can inherit the correct profile path, state directory, and port.
-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.
+Managed child bridges disable their local activity recorder. Dashboard-visible activity comes from the parent server handling client traffic, so orchestrator-managed child state directories should not accumulate their own `activity/events-*.jsonl` files for new runs.
Profile `logs` and `analytics` endpoints are derived from the activity store rather than a separate analytics file.
diff --git a/docs/guides/security.md b/docs/guides/security.md
index 3055537a..b93bb172 100644
--- a/docs/guides/security.md
+++ b/docs/guides/security.md
@@ -137,6 +137,16 @@ curl -H "Authorization: Bearer <token>" http://127.0.0.1:9867/health
CLI commands use the configured local server settings by default, and `PINCHTAB_TOKEN` can override the token for a single shell session.
+## Agent Sessions
+
+Agent sessions are reduced-distribution credentials for trusted automation, not a sandbox for untrusted clients.
+
+- session-authenticated callers are blocked from dashboard/admin endpoint families such as config, session management, profile management, instance management, dashboard agent listings, and cache controls
+- session records can optionally carry explicit grants that narrow access further
+- sessions without explicit grants can still use the normal non-admin automation API by default
+
+That means agent sessions are appropriate for controlled environments where the caller is already trusted to drive browser automation but should not receive the full dashboard bearer token. They are not sufficient for hostile multi-tenant sharing or public internet exposure. For that kind of isolation, run separate PinchTab instances behind separate network and credential boundaries.
+
## Sensitive Endpoints
Some endpoint families expose much more power than normal navigation and inspection. PinchTab keeps them disabled by default:
@@ -285,6 +295,6 @@ For automated agents, use **agent sessions** instead of sharing the server beare
- Has configurable idle timeout and max lifetime
- Never exposes the server bearer token to agents
-**Important:** Agent sessions are designed for trusted environments. The session management API (`/api/sessions`) has no per-agent authorization — any bearer-authenticated caller can manage all sessions. Do not expose these endpoints to untrusted networks.
+**Important:** Agent sessions are designed for trusted environments. The session management API (`/sessions`) has no per-agent authorization — any bearer-authenticated caller can manage all sessions. Do not expose these endpoints to untrusted networks.
See [Reference: Agent Sessions](../reference/sessions.md) for configuration and API details.
diff --git a/docs/reference/config.md b/docs/reference/config.md
index f82a806d..3f342528 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -253,7 +253,16 @@ Current nested file-config shape:
"activity": {
"enabled": true,
"sessionIdleSec": 1800,
- "retentionDays": 1
+ "retentionDays": 1,
+ "events": {
+ "dashboard": false,
+ "server": false,
+ "bridge": false,
+ "orchestrator": false,
+ "scheduler": false,
+ "mcp": false,
+ "other": false
+ }
}
}
}
@@ -299,7 +308,7 @@ For Linux container compatibility, use the runtime-managed path instead of `brow
| `multiInstance` | Orchestrator strategy, allocation, port range, and restart policy |
| `timeouts` | Action, navigation, shutdown, and navigation wait delays |
| `scheduler` | Optional task queue |
-| `observability` | Activity logging and retention |
+| `observability` | Activity logging, source selection, and retention |
## `config get` And `config set` Support
@@ -312,8 +321,9 @@ For Linux container compatibility, use the runtime-managed path instead of `brow
- `profiles`
- `multiInstance`
- `timeouts`
+- `observability`
-They do not expose every field in those sections, and they do not support `scheduler.*` or `observability.*`.
+They do not expose every field in those sections, and they do not support `scheduler.*`.
Use `pinchtab config patch` or edit `config.json` directly for fields such as:
@@ -325,7 +335,7 @@ Use `pinchtab config patch` or edit `config.json` directly for fields such as:
- `security.idpi.scanTimeoutSec`
- `security.idpi.shieldThreshold`
- `scheduler.*`
-- `observability.*`
+- `observability.activity.events.*`
## Common Examples
diff --git a/docs/reference/sessions.md b/docs/reference/sessions.md
index a6398a23..5e14e0e0 100644
--- a/docs/reference/sessions.md
+++ b/docs/reference/sessions.md
@@ -36,10 +36,9 @@ In `config.json`:
## Lifecycle
-1. **Create** — via dashboard API: `POST /api/sessions`
+1. **Create** — via dashboard API: `POST /sessions`
2. **Use** — agent sends `Authorization: Session ses_...` with each request
-3. **Rotate** — generate a new token, old one invalidated: `POST /api/sessions/{id}/rotate`
-4. **Revoke** — permanently disable: `POST /api/sessions/{id}/revoke`
+3. **Revoke** — permanently disable: `POST /sessions/{id}/revoke`
## Security
@@ -49,10 +48,20 @@ In `config.json`:
- Sessions persisted to `agent-sessions.json` (atomic writes)
- Each session bound to a specific agentId for activity tracking
-> **⚠️ Trusted environment only.** The session management API (`/api/sessions`) has no per-agent authorization scoping. Any caller authenticated with the server bearer token or a valid dashboard cookie can create, list, rotate, and revoke sessions for any agent. Do not expose these endpoints to untrusted networks or the public internet. If you need multi-tenant isolation, run separate PinchTab instances per tenant.
+> **⚠️ Trusted, controlled environments only.** Agent sessions are meant for operators and automation you already trust: local machines, private networks, CI, or other controlled systems. They are not a multi-tenant isolation boundary and should not be treated as safe for untrusted users, untrusted agents, or public internet exposure.
+>
+> The session management API (`/sessions`) still has admin-style authority for create, list, and inspect operations. Any caller authenticated with the server bearer token or a valid dashboard cookie can manage sessions for any agent. Session-authenticated callers are blocked from dashboard/admin endpoint families, but a session without explicit grants can still access the normal non-admin automation surface by default.
>
> In untrusted or shared environments where agent sessions are not needed, disable them entirely by setting `"enabled": false` or `"mode": "off"` in your config to reduce the auth surface.
+### Session Grants
+
+When a session record contains explicit `grants`, PinchTab enforces them in middleware and only allows routes covered by those grant groups. When a session has no explicit grants, PinchTab allows the normal non-admin automation routes by default but still blocks dashboard/admin endpoint families such as config, dashboard event streams, session management, profile management, instance management, and cache management.
+
+The built-in grant groups are: `browse`, `network`, `media`, `cookies`, `clipboard`, `evaluate`, `storage`, `console`, `solve`, `tasks`, and `activity`.
+
+That default is a convenience for trusted automation, not a sandbox. If you need hard isolation between agents or tenants, use separate PinchTab instances.
+
## CLI Usage
```bash
diff --git a/internal/activity/activity.go b/internal/activity/activity.go
index 8a119b2a..4a5c40ce 100644
--- a/internal/activity/activity.go
+++ b/internal/activity/activity.go
@@ -2,8 +2,6 @@ package activity
import (
"bufio"
- "crypto/sha256"
- "encoding/hex"
"encoding/json"
"fmt"
"os"
@@ -23,6 +21,17 @@ const (
type Config struct {
Enabled bool
RetentionDays int
+ Events EventSourceConfig
+}
+
+type EventSourceConfig struct {
+ Dashboard bool
+ Server bool
+ Bridge bool
+ Orchestrator bool
+ Scheduler bool
+ MCP bool
+ Other bool
}
type Event struct {
@@ -30,7 +39,6 @@ type Event struct {
Source string `json:"source"`
RequestID string `json:"requestId,omitempty"`
SessionID string `json:"sessionId,omitempty"`
- ActorID string `json:"actorId,omitempty"`
AgentID string `json:"agentId,omitempty"`
Method string `json:"method"`
Path string `json:"path"`
@@ -51,8 +59,8 @@ type Filter struct {
Source string
RequestID string
SessionID string
- ActorID string
AgentID string
+ AgentIDLike string
InstanceID string
ProfileID string
ProfileName string
@@ -74,6 +82,7 @@ type Recorder interface {
type Store struct {
dir string
retentionDays int
+ events EventSourceConfig
mu sync.Mutex
}
@@ -84,10 +93,22 @@ func NewRecorder(cfg Config, stateDir string) (Recorder, error) {
if !cfg.Enabled {
return noopRecorder{}, nil
}
- return NewStore(stateDir, cfg.RetentionDays)
+ return NewStoreWithEvents(stateDir, cfg.RetentionDays, cfg.Events)
}
func NewStore(stateDir string, retentionDays int) (*Store, error) {
+ return NewStoreWithEvents(stateDir, retentionDays, EventSourceConfig{
+ Dashboard: true,
+ Server: true,
+ Bridge: true,
+ Orchestrator: true,
+ Scheduler: true,
+ MCP: true,
+ Other: true,
+ })
+}
+
+func NewStoreWithEvents(stateDir string, retentionDays int, events EventSourceConfig) (*Store, error) {
activityDir := filepath.Join(stateDir, "activity")
if err := os.MkdirAll(activityDir, 0750); err != nil {
return nil, fmt.Errorf("create activity dir: %w", err)
@@ -99,6 +120,7 @@ func NewStore(stateDir string, retentionDays int) (*Store, error) {
store := &Store{
dir: activityDir,
retentionDays: retentionDays,
+ events: events,
}
if err := store.pruneExpiredFiles(time.Now().UTC()); err != nil {
return nil, err
@@ -123,6 +145,9 @@ func (s *Store) Record(evt Event) error {
} else {
evt.Timestamp = evt.Timestamp.UTC()
}
+ if !s.shouldRecordSource(evt.Source) {
+ return nil
+ }
evt.URL = sanitizeActivityURL(evt.URL)
if err := s.pruneExpiredFilesLocked(evt.Timestamp); err != nil {
@@ -207,6 +232,27 @@ func clampQueryLimit(limit int) int {
return limit
}
+func (s *Store) shouldRecordSource(source string) bool {
+ switch normalizeSourceName(source) {
+ case "client":
+ return true
+ case "dashboard":
+ return s.events.Dashboard
+ case "server":
+ return s.events.Server
+ case "bridge":
+ return s.events.Bridge
+ case "orchestrator":
+ return s.events.Orchestrator
+ case "scheduler":
+ return s.events.Scheduler
+ case "mcp":
+ return s.events.MCP
+ default:
+ return s.events.Other
+ }
+}
+
func (noopRecorder) Enabled() bool {
return false
}
@@ -229,9 +275,6 @@ func (f Filter) matches(evt Event) bool {
if f.SessionID != "" && evt.SessionID != f.SessionID {
return false
}
- if f.ActorID != "" && evt.ActorID != f.ActorID {
- return false
- }
if f.AgentID != "" && evt.AgentID != f.AgentID {
return false
}
@@ -265,15 +308,6 @@ func (f Filter) matches(evt Event) bool {
return true
}
-func FingerprintToken(token string) string {
- token = strings.TrimSpace(token)
- if token == "" {
- return ""
- }
- sum := sha256.Sum256([]byte(token))
- return "tok_" + hex.EncodeToString(sum[:6])
-}
-
func (s *Store) filePathFor(ts time.Time) string {
return filepath.Join(s.dir, fmt.Sprintf("events-%s.jsonl", ts.UTC().Format(time.DateOnly)))
}
diff --git a/internal/activity/activity_test.go b/internal/activity/activity_test.go
index 12627dfe..68a28ae3 100644
--- a/internal/activity/activity_test.go
+++ b/internal/activity/activity_test.go
@@ -38,6 +38,35 @@ func TestStoreRecordAndQuery(t *testing.T) {
}
}
+func TestStoreQueryFiltersByAgentID(t *testing.T) {
+ store, err := NewStore(t.TempDir(), 1)
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+
+ now := time.Now().UTC()
+ events := []Event{
+ {Timestamp: now.Add(-2 * time.Minute), Source: "server", AgentID: "cli", Path: "/tabs/tab-1/text", Method: "GET", Status: 200},
+ {Timestamp: now.Add(-1 * time.Minute), Source: "bridge", AgentID: "mcp", Path: "/tabs/tab-2/action", Method: "POST", Status: 200},
+ }
+ for _, evt := range events {
+ if err := store.Record(evt); err != nil {
+ t.Fatalf("Record: %v", err)
+ }
+ }
+
+ got, err := store.Query(Filter{AgentID: "cli", Limit: 10})
+ if err != nil {
+ t.Fatalf("Query: %v", err)
+ }
+ if len(got) != 1 {
+ t.Fatalf("len(got) = %d, want 1", len(got))
+ }
+ if got[0].AgentID != "cli" {
+ t.Fatalf("AgentID = %q, want cli", got[0].AgentID)
+ }
+}
+
func TestStoreWritesJSONLFile(t *testing.T) {
root := t.TempDir()
store, err := NewStore(root, 1)
@@ -134,6 +163,92 @@ func TestStorePartitionsDashboardEventsOutsidePrimaryLog(t *testing.T) {
}
}
+func TestStoreWritesServerEventsToSourcePartitionToo(t *testing.T) {
+ root := t.TempDir()
+ store, err := NewStore(root, 1)
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+
+ now := time.Now().UTC()
+ if err := store.Record(Event{
+ Timestamp: now,
+ Source: "server",
+ Method: "POST",
+ Path: "/sessions",
+ Status: 401,
+ }); err != nil {
+ t.Fatalf("Record: %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\":\"server\"") {
+ t.Fatal("primary activity log should include server events")
+ }
+
+ serverPath := filepath.Join(root, "activity", "events-server-"+now.Format(time.DateOnly)+".jsonl")
+ serverData, err := os.ReadFile(serverPath)
+ if err != nil {
+ t.Fatalf("ReadFile server: %v", err)
+ }
+ if !strings.Contains(string(serverData), "\"source\":\"server\"") {
+ t.Fatal("server partition log should include server events")
+ }
+}
+
+func TestStoreWithEventsRecordsClientOnlyByDefaultPolicy(t *testing.T) {
+ root := t.TempDir()
+ store, err := NewStoreWithEvents(root, 1, EventSourceConfig{})
+ if err != nil {
+ t.Fatalf("NewStoreWithEvents: %v", err)
+ }
+
+ now := time.Now().UTC()
+ for _, evt := range []Event{
+ {Timestamp: now, Source: "client", Method: "GET", Path: "/text", Status: 200},
+ {Timestamp: now.Add(time.Second), Source: "server", Method: "GET", Path: "/health", Status: 200},
+ {Timestamp: now.Add(2 * time.Second), Source: "dashboard", Method: "GET", Path: "/api/events", Status: 200},
+ {Timestamp: now.Add(3 * time.Second), Source: "orchestrator", Method: "GET", Path: "/instances", Status: 200},
+ } {
+ if err := store.Record(evt); err != nil {
+ t.Fatalf("Record(%s): %v", evt.Source, err)
+ }
+ }
+
+ gotAll, err := store.Query(Filter{Limit: 10})
+ if err != nil {
+ t.Fatalf("Query all: %v", err)
+ }
+ if len(gotAll) != 1 || gotAll[0].Source != "client" {
+ t.Fatalf("unfiltered query = %#v, want single client event", gotAll)
+ }
+
+ clientPath := filepath.Join(root, "activity", "events-client-"+now.Format(time.DateOnly)+".jsonl")
+ clientData, err := os.ReadFile(clientPath)
+ if err != nil {
+ t.Fatalf("ReadFile client: %v", err)
+ }
+ if !strings.Contains(string(clientData), "\"source\":\"client\"") {
+ t.Fatal("client activity log should include client events")
+ }
+ if strings.Contains(string(clientData), "\"source\":\"server\"") ||
+ strings.Contains(string(clientData), "\"source\":\"dashboard\"") ||
+ strings.Contains(string(clientData), "\"source\":\"orchestrator\"") {
+ t.Fatal("client activity log should exclude disabled non-client events")
+ }
+
+ for _, source := range []string{"dashboard", "server", "orchestrator"} {
+ path := filepath.Join(root, "activity", "events-"+source+"-"+now.Format(time.DateOnly)+".jsonl")
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("%s activity log should not exist, stat err = %v", source, err)
+ }
+ }
+}
+
func TestStorePrunesExpiredDailyFiles(t *testing.T) {
root := t.TempDir()
store, err := NewStore(root, 1)
diff --git a/internal/activity/api.go b/internal/activity/api.go
index c21076d0..8ff1f9db 100644
--- a/internal/activity/api.go
+++ b/internal/activity/api.go
@@ -38,7 +38,6 @@ func RegisterHandlers(mux *http.ServeMux, rec Recorder) {
Source: event.Source,
RequestID: event.RequestID,
SessionID: event.SessionID,
- ActorID: event.ActorID,
AgentID: event.AgentID,
Method: event.Method,
Path: event.Path,
@@ -66,7 +65,6 @@ func filterFromRequest(r *http.Request) (Filter, error) {
Source: strings.TrimSpace(q.Get("source")),
RequestID: strings.TrimSpace(q.Get("requestId")),
SessionID: strings.TrimSpace(q.Get("sessionId")),
- ActorID: strings.TrimSpace(q.Get("actorId")),
AgentID: strings.TrimSpace(q.Get("agentId")),
InstanceID: strings.TrimSpace(q.Get("instanceId")),
ProfileID: strings.TrimSpace(q.Get("profileId")),
diff --git a/internal/activity/api_test.go b/internal/activity/api_test.go
index ce9f2d48..0ad28bd8 100644
--- a/internal/activity/api_test.go
+++ b/internal/activity/api_test.go
@@ -17,6 +17,18 @@ func TestFilterFromRequest_ClampsLimit(t *testing.T) {
}
}
+func TestFilterFromRequest_ParsesAgentID(t *testing.T) {
+ req := httptest.NewRequest("GET", "/api/activity?agentId=cli", nil)
+
+ filter, err := filterFromRequest(req)
+ if err != nil {
+ t.Fatalf("filterFromRequest: %v", err)
+ }
+ if filter.AgentID != "cli" {
+ t.Fatalf("AgentID = %q, want cli", filter.AgentID)
+ }
+}
+
func TestFilterFromRequest_RejectsInvalidLimit(t *testing.T) {
req := httptest.NewRequest("GET", "/api/activity?limit=0", nil)
diff --git a/internal/activity/context.go b/internal/activity/context.go
index c3273647..6d1603a6 100644
--- a/internal/activity/context.go
+++ b/internal/activity/context.go
@@ -16,7 +16,6 @@ import (
const (
HeaderAgentID = "X-Agent-Id"
- HeaderPTActorID = "X-PinchTab-Actor-Id"
HeaderPTSessionID = "X-PinchTab-Session-Id"
HeaderPTSource = "X-PinchTab-Source"
HeaderPTInstance = "X-PinchTab-Instance-Id"
@@ -35,7 +34,6 @@ type requestState struct {
type Update struct {
RequestID string
SessionID string
- ActorID string
AgentID string
InstanceID string
ProfileID string
@@ -60,7 +58,6 @@ func Middleware(rec Recorder, source string, next http.Handler) http.Handler {
Timestamp: start.UTC(),
Source: sourceFor(r, source),
RequestID: requestIDFor(r, w),
- ActorID: actorIDFor(r),
AgentID: agentIDFor(r),
SessionID: strings.TrimSpace(r.Header.Get(HeaderPTSessionID)),
Method: r.Method,
@@ -88,9 +85,6 @@ func Middleware(rec Recorder, source string, next http.Handler) http.Handler {
if evt.AgentID == "" {
evt.AgentID = agentIDFor(r)
}
- if evt.ActorID == "" {
- evt.ActorID = actorIDFor(r)
- }
if evt.Path == "" {
evt.Path = r.URL.Path
}
@@ -133,9 +127,6 @@ func EnrichRequest(r *http.Request, update Update) {
if update.SessionID != "" {
state.event.SessionID = update.SessionID
}
- if update.ActorID != "" {
- state.event.ActorID = update.ActorID
- }
if update.AgentID != "" {
state.event.AgentID = update.AgentID
}
@@ -178,9 +169,6 @@ func PropagateHeaders(ctx context.Context, req *http.Request) {
if evt.RequestID != "" {
req.Header.Set("X-Request-Id", evt.RequestID)
}
- if evt.ActorID != "" {
- req.Header.Set(HeaderPTActorID, evt.ActorID)
- }
if evt.AgentID != "" {
req.Header.Set(HeaderAgentID, evt.AgentID)
}
@@ -213,13 +201,6 @@ func requestIDFor(r *http.Request, w http.ResponseWriter) string {
return strings.TrimSpace(r.Header.Get("X-Request-Id"))
}
-func actorIDFor(r *http.Request) string {
- if actorID := strings.TrimSpace(r.Header.Get(HeaderPTActorID)); actorID != "" {
- return actorID
- }
- return FingerprintToken(authn.TokenFromRequest(r))
-}
-
func agentIDFor(r *http.Request) string {
if value := strings.TrimSpace(r.Header.Get(HeaderAgentID)); value != "" {
return value
diff --git a/internal/agentsession/store.go b/internal/agentsession/store.go
index 50ebc7c3..64948aef 100644
--- a/internal/agentsession/store.go
+++ b/internal/agentsession/store.go
@@ -201,32 +201,6 @@ func (s *Store) Revoke(sessionID string) bool {
return true
}
-// Rotate invalidates the current token and returns a new one.
-func (s *Store) Rotate(sessionID string) (string, error) {
- if s == nil {
- return "", fmt.Errorf("store is nil")
- }
- s.mu.Lock()
- defer s.mu.Unlock()
-
- sess, ok := s.sessions[strings.TrimSpace(sessionID)]
- if !ok {
- return "", fmt.Errorf("session not found")
- }
- if sess.Status != StatusActive {
- return "", fmt.Errorf("session is %s", sess.Status)
- }
-
- token, err := generateToken()
- if err != nil {
- return "", err
- }
- sess.TokenHash = hashToken(token)
- sess.LastSeenAt = s.now()
- s.saveLocked()
- return token, nil
-}
-
// UpdateConfig applies new configuration.
func (s *Store) UpdateConfig(cfg Config) {
if s == nil {
diff --git a/internal/agentsession/store_test.go b/internal/agentsession/store_test.go
index 81e4a861..31211fcf 100644
--- a/internal/agentsession/store_test.go
+++ b/internal/agentsession/store_test.go
@@ -131,42 +131,6 @@ func TestRevokeNotFound(t *testing.T) {
}
}
-func TestRotate(t *testing.T) {
- s := NewStore(Config{Enabled: true})
- id, oldToken, _ := s.Create("agent-1", "")
-
- newToken, err := s.Rotate(id)
- if err != nil {
- t.Fatal(err)
- }
- if newToken == oldToken {
- t.Fatal("expected new token to differ from old")
- }
-
- // Old token should fail
- sess, ok := s.Authenticate(oldToken)
- if ok || sess != nil {
- t.Fatal("expected old token to fail after rotation")
- }
-
- // New token should succeed
- sess, ok = s.Authenticate(newToken)
- if !ok || sess == nil {
- t.Fatal("expected new token to succeed after rotation")
- }
-}
-
-func TestRotateRevoked(t *testing.T) {
- s := NewStore(Config{Enabled: true})
- id, _, _ := s.Create("agent-1", "")
- s.Revoke(id)
-
- _, err := s.Rotate(id)
- if err == nil {
- t.Fatal("expected rotate to fail on revoked session")
- }
-}
-
func TestGet(t *testing.T) {
s := NewStore(Config{Enabled: true})
id, _, _ := s.Create("agent-1", "my label")
diff --git a/internal/api/types/types.go b/internal/api/types/types.go
index adbb24d3..7892bfce 100644
--- a/internal/api/types/types.go
+++ b/internal/api/types/types.go
@@ -79,7 +79,6 @@ type ActivityLogEvent struct {
Source string `json:"source"`
RequestID string `json:"requestId,omitempty"`
SessionID string `json:"sessionId,omitempty"`
- ActorID string `json:"actorId,omitempty"`
AgentID string `json:"agentId,omitempty"`
Method string `json:"method"`
Path string `json:"path"`
diff --git a/internal/bridge/action_text.go b/internal/bridge/action_text.go
index c319d8ea..7d044f5f 100644
--- a/internal/bridge/action_text.go
+++ b/internal/bridge/action_text.go
@@ -28,7 +28,14 @@ func (b *Bridge) actionFill(ctx context.Context, req ActionRequest) (map[string]
return map[string]any{"filled": req.Text}, chromedp.Run(ctx, chromedp.SetValue(req.Selector, req.Text, chromedp.ByQuery))
}
if req.NodeID > 0 {
- return map[string]any{"filled": req.Text}, FillByNodeID(ctx, req.NodeID, req.Text)
+ if err := FillByNodeID(ctx, req.NodeID, req.Text); err != nil {
+ return nil, err
+ }
+ result := map[string]any{"filled": req.Text}
+ if actual, err := ReadInputValue(ctx, req.NodeID); err == nil && req.Text != "" && actual != req.Text {
+ result["warning"] = "fill may not have been picked up by the page (e.g. React controlled input); try 'type' instead"
+ }
+ return result, nil
}
return nil, fmt.Errorf("need selector or ref")
}
diff --git a/internal/bridge/cdpops/element_ops.go b/internal/bridge/cdpops/element_ops.go
index 67c23c6f..8e2185f7 100644
--- a/internal/bridge/cdpops/element_ops.go
+++ b/internal/bridge/cdpops/element_ops.go
@@ -27,7 +27,21 @@ func FillByNodeID(ctx context.Context, nodeID int64, value string) error {
if err := json.Unmarshal(result, &resolved); err != nil {
return err
}
- js := `function(v) { this.value = v; this.dispatchEvent(new Event('input', {bubbles: true})); this.dispatchEvent(new Event('change', {bubbles: true})); }`
+ // Use the native value setter for the concrete element type to bypass
+ // framework-patched setters (e.g. React's value tracker). Calling the
+ // input setter on a textarea throws with an incompatible receiver.
+ js := `function(v) {
+ var proto = null;
+ if (this instanceof window.HTMLTextAreaElement) {
+ proto = window.HTMLTextAreaElement.prototype;
+ } else if (this instanceof window.HTMLInputElement) {
+ proto = window.HTMLInputElement.prototype;
+ }
+ var setter = proto && Object.getOwnPropertyDescriptor(proto, 'value').set;
+ if (setter) { setter.call(this, v); } else { this.value = v; }
+ this.dispatchEvent(new Event('input', {bubbles: true}));
+ this.dispatchEvent(new Event('change', {bubbles: true}));
+ }`
return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
"functionDeclaration": js,
"objectId": resolved.Object.ObjectID,
@@ -67,6 +81,63 @@ func SelectByNodeID(ctx context.Context, nodeID int64, value string) error {
)
}
+// ReadInputValue reads back the effective value of an input element. For React
+// controlled inputs it checks the fiber's memoizedProps.value (which reflects
+// React state) rather than the DOM value, since the DOM value can be stale.
+// Returns the effective value the framework considers current.
+func ReadInputValue(ctx context.Context, nodeID int64) (string, error) {
+ var value string
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ var result json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
+ "backendNodeId": nodeID,
+ }, &result); err != nil {
+ return err
+ }
+ var resolved struct {
+ Object struct {
+ ObjectID string `json:"objectId"`
+ } `json:"object"`
+ }
+ if err := json.Unmarshal(result, &resolved); err != nil {
+ return err
+ }
+ js := `function() {
+ var el = this;
+ var fiberKey = Object.keys(el).find(function(k) {
+ return k.startsWith('__reactFiber$') || k.startsWith('__reactInternalInstance$');
+ });
+ if (fiberKey) {
+ var fiber = el[fiberKey];
+ var props = fiber && fiber.memoizedProps;
+ if (props && 'value' in props) {
+ return props.value || "";
+ }
+ }
+ return el.value || "";
+ }`
+ var callResult json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
+ "functionDeclaration": js,
+ "objectId": resolved.Object.ObjectID,
+ "returnByValue": true,
+ }, &callResult); err != nil {
+ return err
+ }
+ var cr struct {
+ Result struct {
+ Value string `json:"value"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(callResult, &cr); err != nil {
+ return err
+ }
+ value = cr.Result.Value
+ return nil
+ }))
+ return value, err
+}
+
func ScrollByNodeID(ctx context.Context, nodeID int64) error {
return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)
diff --git a/internal/bridge/cdpops_facade.go b/internal/bridge/cdpops_facade.go
index 68e5dc04..865a7b4a 100644
--- a/internal/bridge/cdpops_facade.go
+++ b/internal/bridge/cdpops_facade.go
@@ -83,6 +83,10 @@ func SelectByNodeID(ctx context.Context, nodeID int64, value string) error {
return bridgecdpops.SelectByNodeID(ctx, nodeID, value)
}
+func ReadInputValue(ctx context.Context, nodeID int64) (string, error) {
+ return bridgecdpops.ReadInputValue(ctx, nodeID)
+}
+
func ScrollByNodeID(ctx context.Context, nodeID int64) error {
return bridgecdpops.ScrollByNodeID(ctx, nodeID)
}
diff --git a/internal/config/config_file.go b/internal/config/config_file.go
index 86ad988f..a656854e 100644
--- a/internal/config/config_file.go
+++ b/internal/config/config_file.go
@@ -37,6 +37,13 @@ func DefaultFileConfig() FileConfig {
activityEnabled := true
activitySessionIdleSec := 1800
activityRetentionDays := 1
+ activityDashboardEvents := false
+ activityServerEvents := false
+ activityBridgeEvents := false
+ activityOrchestratorEvents := false
+ activitySchedulerEvents := false
+ activityMCPEvents := false
+ activityOtherEvents := false
dashboardSessionPersist := true
dashboardSessionIdleSec := 7 * 24 * 60 * 60
dashboardSessionMaxLifetimeSec := 7 * 24 * 60 * 60
@@ -117,6 +124,15 @@ func DefaultFileConfig() FileConfig {
SessionIdleSec: &activitySessionIdleSec,
RetentionDays: &activityRetentionDays,
StateDir: "",
+ Events: ActivityEventsFileConfig{
+ Dashboard: &activityDashboardEvents,
+ Server: &activityServerEvents,
+ Bridge: &activityBridgeEvents,
+ Orchestrator: &activityOrchestratorEvents,
+ Scheduler: &activitySchedulerEvents,
+ MCP: &activityMCPEvents,
+ Other: &activityOtherEvents,
+ },
},
},
Sessions: SessionsFileConfig{
@@ -262,10 +278,21 @@ type observabilityFileConfigJSON struct {
}
type activityConfigJSON struct {
- Enabled *bool `json:"enabled"`
- SessionIdleSec *int `json:"sessionIdleSec"`
- RetentionDays *int `json:"retentionDays"`
- StateDir string `json:"stateDir"`
+ Enabled *bool `json:"enabled"`
+ SessionIdleSec *int `json:"sessionIdleSec"`
+ RetentionDays *int `json:"retentionDays"`
+ StateDir string `json:"stateDir"`
+ Events activityEventsConfigJSON `json:"events"`
+}
+
+type activityEventsConfigJSON struct {
+ Dashboard *bool `json:"dashboard,omitempty"`
+ Server *bool `json:"server,omitempty"`
+ Bridge *bool `json:"bridge,omitempty"`
+ Orchestrator *bool `json:"orchestrator,omitempty"`
+ Scheduler *bool `json:"scheduler,omitempty"`
+ MCP *bool `json:"mcp,omitempty"`
+ Other *bool `json:"other,omitempty"`
}
type sessionsFileConfigJSON struct {
@@ -409,6 +436,16 @@ 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,
+ Events: activityEventsConfigJSON{
+ Dashboard: fc.Observability.Activity.Events.Dashboard,
+ Server: fc.Observability.Activity.Events.Server,
+ Bridge: fc.Observability.Activity.Events.Bridge,
+ Orchestrator: fc.Observability.Activity.Events.Orchestrator,
+ Scheduler: fc.Observability.Activity.Events.Scheduler,
+ MCP: fc.Observability.Activity.Events.MCP,
+ Other: fc.Observability.Activity.Events.Other,
+ },
},
},
Sessions: sessionsFileConfigJSON{
@@ -474,6 +511,13 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
activityEnabled := cfg.Observability.Activity.Enabled
activitySessionIdleSec := cfg.Observability.Activity.SessionIdleSec
activityRetentionDays := cfg.Observability.Activity.RetentionDays
+ activityDashboardEvents := cfg.Observability.Activity.Events.Dashboard
+ activityServerEvents := cfg.Observability.Activity.Events.Server
+ activityBridgeEvents := cfg.Observability.Activity.Events.Bridge
+ activityOrchestratorEvents := cfg.Observability.Activity.Events.Orchestrator
+ activitySchedulerEvents := cfg.Observability.Activity.Events.Scheduler
+ activityMCPEvents := cfg.Observability.Activity.Events.MCP
+ activityOtherEvents := cfg.Observability.Activity.Events.Other
dashboardSessionPersist := cfg.Sessions.Dashboard.Persist
dashboardSessionIdleSec := int(cfg.Sessions.Dashboard.IdleTimeout / time.Second)
dashboardSessionMaxLifetimeSec := int(cfg.Sessions.Dashboard.MaxLifetime / time.Second)
@@ -575,6 +619,15 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
Enabled: &activityEnabled,
SessionIdleSec: &activitySessionIdleSec,
RetentionDays: &activityRetentionDays,
+ Events: ActivityEventsFileConfig{
+ Dashboard: &activityDashboardEvents,
+ Server: &activityServerEvents,
+ Bridge: &activityBridgeEvents,
+ Orchestrator: &activityOrchestratorEvents,
+ Scheduler: &activitySchedulerEvents,
+ MCP: &activityMCPEvents,
+ Other: &activityOtherEvents,
+ },
},
},
Sessions: SessionsFileConfig{
diff --git a/internal/config/config_file_test.go b/internal/config/config_file_test.go
index c012f461..e9af00e8 100644
--- a/internal/config/config_file_test.go
+++ b/internal/config/config_file_test.go
@@ -91,6 +91,15 @@ func TestDefaultFileConfig(t *testing.T) {
if fc.Observability.Activity.StateDir != "" {
t.Errorf("DefaultFileConfig.Observability.Activity.StateDir = %q, want empty string", fc.Observability.Activity.StateDir)
}
+ if fc.Observability.Activity.Events.Dashboard == nil || *fc.Observability.Activity.Events.Dashboard {
+ t.Errorf("DefaultFileConfig.Observability.Activity.Events.Dashboard = %v, want explicit false", formatBoolPtr(fc.Observability.Activity.Events.Dashboard))
+ }
+ if fc.Observability.Activity.Events.Server == nil || *fc.Observability.Activity.Events.Server {
+ t.Errorf("DefaultFileConfig.Observability.Activity.Events.Server = %v, want explicit false", formatBoolPtr(fc.Observability.Activity.Events.Server))
+ }
+ if fc.Observability.Activity.Events.Bridge == nil || *fc.Observability.Activity.Events.Bridge {
+ t.Errorf("DefaultFileConfig.Observability.Activity.Events.Bridge = %v, want explicit false", formatBoolPtr(fc.Observability.Activity.Events.Bridge))
+ }
}
// TestIsLegacyConfig tests the format detection logic.
@@ -241,6 +250,12 @@ func TestDefaultFileConfigJSON(t *testing.T) {
if parsed.Observability.Activity.StateDir != "" {
t.Errorf("round-trip Observability.Activity.StateDir = %q, want empty string", parsed.Observability.Activity.StateDir)
}
+ if parsed.Observability.Activity.Events.Dashboard == nil || *parsed.Observability.Activity.Events.Dashboard {
+ t.Errorf("round-trip Observability.Activity.Events.Dashboard = %v, want explicit false", formatBoolPtr(parsed.Observability.Activity.Events.Dashboard))
+ }
+ if parsed.Observability.Activity.Events.Server == nil || *parsed.Observability.Activity.Events.Server {
+ t.Errorf("round-trip Observability.Activity.Events.Server = %v, want explicit false", formatBoolPtr(parsed.Observability.Activity.Events.Server))
+ }
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.go
index d9e9f001..0624202f 100644
--- a/internal/config/config_load.go
+++ b/internal/config/config_load.go
@@ -282,6 +282,27 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
if fc.Observability.Activity.RetentionDays != nil {
cfg.Observability.Activity.RetentionDays = *fc.Observability.Activity.RetentionDays
}
+ if fc.Observability.Activity.Events.Dashboard != nil {
+ cfg.Observability.Activity.Events.Dashboard = *fc.Observability.Activity.Events.Dashboard
+ }
+ if fc.Observability.Activity.Events.Server != nil {
+ cfg.Observability.Activity.Events.Server = *fc.Observability.Activity.Events.Server
+ }
+ if fc.Observability.Activity.Events.Bridge != nil {
+ cfg.Observability.Activity.Events.Bridge = *fc.Observability.Activity.Events.Bridge
+ }
+ if fc.Observability.Activity.Events.Orchestrator != nil {
+ cfg.Observability.Activity.Events.Orchestrator = *fc.Observability.Activity.Events.Orchestrator
+ }
+ if fc.Observability.Activity.Events.Scheduler != nil {
+ cfg.Observability.Activity.Events.Scheduler = *fc.Observability.Activity.Events.Scheduler
+ }
+ if fc.Observability.Activity.Events.MCP != nil {
+ cfg.Observability.Activity.Events.MCP = *fc.Observability.Activity.Events.MCP
+ }
+ if fc.Observability.Activity.Events.Other != nil {
+ cfg.Observability.Activity.Events.Other = *fc.Observability.Activity.Events.Other
+ }
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.go
index 8710a648..93eb92df 100644
--- a/internal/config/config_load_test.go
+++ b/internal/config/config_load_test.go
@@ -103,6 +103,27 @@ func TestLoadConfigDefaults(t *testing.T) {
if cfg.Observability.Activity.RetentionDays != 1 {
t.Errorf("default Observability.Activity.RetentionDays = %d, want 1", cfg.Observability.Activity.RetentionDays)
}
+ if cfg.Observability.Activity.Events.Dashboard {
+ t.Errorf("default Observability.Activity.Events.Dashboard = %v, want false", cfg.Observability.Activity.Events.Dashboard)
+ }
+ if cfg.Observability.Activity.Events.Server {
+ t.Errorf("default Observability.Activity.Events.Server = %v, want false", cfg.Observability.Activity.Events.Server)
+ }
+ if cfg.Observability.Activity.Events.Bridge {
+ t.Errorf("default Observability.Activity.Events.Bridge = %v, want false", cfg.Observability.Activity.Events.Bridge)
+ }
+ if cfg.Observability.Activity.Events.Orchestrator {
+ t.Errorf("default Observability.Activity.Events.Orchestrator = %v, want false", cfg.Observability.Activity.Events.Orchestrator)
+ }
+ if cfg.Observability.Activity.Events.Scheduler {
+ t.Errorf("default Observability.Activity.Events.Scheduler = %v, want false", cfg.Observability.Activity.Events.Scheduler)
+ }
+ if cfg.Observability.Activity.Events.MCP {
+ t.Errorf("default Observability.Activity.Events.MCP = %v, want false", cfg.Observability.Activity.Events.MCP)
+ }
+ if cfg.Observability.Activity.Events.Other {
+ t.Errorf("default Observability.Activity.Events.Other = %v, want false", cfg.Observability.Activity.Events.Other)
+ }
if !cfg.Sessions.Dashboard.Persist {
t.Errorf("default Sessions.Dashboard.Persist = %v, want true", cfg.Sessions.Dashboard.Persist)
}
@@ -200,6 +221,58 @@ func TestConfigFileWithNestedValues(t *testing.T) {
}
}
+func TestLoadConfigActivityEvents(t *testing.T) {
+ clearConfigEnvVars(t)
+
+ tmpDir := t.TempDir()
+ configPath := filepath.Join(tmpDir, "config.json")
+ _ = os.Setenv("PINCHTAB_CONFIG", configPath)
+ defer func() {
+ _ = os.Unsetenv("PINCHTAB_CONFIG")
+ }()
+
+ if err := os.WriteFile(configPath, []byte(`{
+ "observability": {
+ "activity": {
+ "events": {
+ "dashboard": true,
+ "server": true,
+ "bridge": false,
+ "orchestrator": true,
+ "scheduler": true,
+ "mcp": false,
+ "other": true
+ }
+ }
+ }
+ }`), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ cfg := Load()
+ if !cfg.Observability.Activity.Events.Dashboard {
+ t.Error("dashboard events should load as enabled")
+ }
+ if !cfg.Observability.Activity.Events.Server {
+ t.Error("server events should load as enabled")
+ }
+ if cfg.Observability.Activity.Events.Bridge {
+ t.Error("bridge events should load as disabled")
+ }
+ if !cfg.Observability.Activity.Events.Orchestrator {
+ t.Error("orchestrator events should load as enabled")
+ }
+ if !cfg.Observability.Activity.Events.Scheduler {
+ t.Error("scheduler events should load as enabled")
+ }
+ if cfg.Observability.Activity.Events.MCP {
+ t.Error("mcp events should load as disabled")
+ }
+ if !cfg.Observability.Activity.Events.Other {
+ t.Error("other events should load as enabled")
+ }
+}
+
func TestLoadConfigActivityStateDirIgnoresConfigOverride(t *testing.T) {
clearConfigEnvVars(t)
diff --git a/internal/config/config_types.go b/internal/config/config_types.go
index 3782aa46..7eeef6bd 100644
--- a/internal/config/config_types.go
+++ b/internal/config/config_types.go
@@ -166,10 +166,21 @@ type ObservabilityConfig struct {
}
type ActivityConfig struct {
- Enabled bool `json:"enabled,omitempty"`
- SessionIdleSec int `json:"sessionIdleSec,omitempty"`
- RetentionDays int `json:"retentionDays,omitempty"`
- StateDir string `json:"stateDir,omitempty"`
+ Enabled bool `json:"enabled,omitempty"`
+ SessionIdleSec int `json:"sessionIdleSec,omitempty"`
+ RetentionDays int `json:"retentionDays,omitempty"`
+ StateDir string `json:"stateDir,omitempty"`
+ Events ActivityEventsConfig `json:"events,omitempty"`
+}
+
+type ActivityEventsConfig struct {
+ Dashboard bool `json:"dashboard,omitempty"`
+ Server bool `json:"server,omitempty"`
+ Bridge bool `json:"bridge,omitempty"`
+ Orchestrator bool `json:"orchestrator,omitempty"`
+ Scheduler bool `json:"scheduler,omitempty"`
+ MCP bool `json:"mcp,omitempty"`
+ Other bool `json:"other,omitempty"`
}
// FileConfig is the persistent configuration written to disk.
@@ -315,10 +326,21 @@ type ObservabilityFileConfig struct {
}
type ActivityFileConfig struct {
- Enabled *bool `json:"enabled,omitempty"`
- SessionIdleSec *int `json:"sessionIdleSec,omitempty"`
- RetentionDays *int `json:"retentionDays,omitempty"`
- StateDir string `json:"stateDir,omitempty"`
+ Enabled *bool `json:"enabled,omitempty"`
+ SessionIdleSec *int `json:"sessionIdleSec,omitempty"`
+ RetentionDays *int `json:"retentionDays,omitempty"`
+ StateDir string `json:"stateDir,omitempty"`
+ Events ActivityEventsFileConfig `json:"events,omitempty"`
+}
+
+type ActivityEventsFileConfig struct {
+ Dashboard *bool `json:"dashboard,omitempty"`
+ Server *bool `json:"server,omitempty"`
+ Bridge *bool `json:"bridge,omitempty"`
+ Orchestrator *bool `json:"orchestrator,omitempty"`
+ Scheduler *bool `json:"scheduler,omitempty"`
+ MCP *bool `json:"mcp,omitempty"`
+ Other *bool `json:"other,omitempty"`
}
// AutoSolverFileConfig is the persistent configuration for the autosolver system.
diff --git a/internal/config/editor_get.go b/internal/config/editor_get.go
index b31e6424..79bb38df 100644
--- a/internal/config/editor_get.go
+++ b/internal/config/editor_get.go
@@ -31,10 +31,12 @@ func GetConfigValue(fc *FileConfig, path string) (string, error) {
return getMultiInstanceField(&fc.MultiInstance, field)
case "timeouts":
return getTimeoutsField(&fc.Timeouts, field)
+ case "observability":
+ return getObservabilityField(&fc.Observability, field)
case "sessions":
return getSessionsField(&fc.Sessions, field)
default:
- return "", fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts, sessions)", section)
+ return "", fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts, observability, sessions)", section)
}
}
@@ -70,6 +72,53 @@ func getBrowserField(b *BrowserConfig, field string) (string, error) {
}
}
+func getObservabilityField(o *ObservabilityFileConfig, field string) (string, error) {
+ if strings.HasPrefix(field, "activity.") {
+ return getActivityField(&o.Activity, strings.TrimPrefix(field, "activity."))
+ }
+ return "", fmt.Errorf("unknown field observability.%s", field)
+}
+
+func getActivityField(a *ActivityFileConfig, field string) (string, error) {
+ if strings.HasPrefix(field, "events.") {
+ return getActivityEventField(&a.Events, strings.TrimPrefix(field, "events."))
+ }
+
+ switch field {
+ case "enabled":
+ return formatBoolPtr(a.Enabled), nil
+ case "sessionIdleSec":
+ return formatIntPtr(a.SessionIdleSec), nil
+ case "retentionDays":
+ return formatIntPtr(a.RetentionDays), nil
+ case "stateDir":
+ return a.StateDir, nil
+ default:
+ return "", fmt.Errorf("unknown field observability.activity.%s", field)
+ }
+}
+
+func getActivityEventField(e *ActivityEventsFileConfig, field string) (string, error) {
+ switch field {
+ case "dashboard":
+ return formatBoolPtr(e.Dashboard), nil
+ case "server":
+ return formatBoolPtr(e.Server), nil
+ case "bridge":
+ return formatBoolPtr(e.Bridge), nil
+ case "orchestrator":
+ return formatBoolPtr(e.Orchestrator), nil
+ case "scheduler":
+ return formatBoolPtr(e.Scheduler), nil
+ case "mcp":
+ return formatBoolPtr(e.MCP), nil
+ case "other":
+ return formatBoolPtr(e.Other), nil
+ default:
+ return "", fmt.Errorf("unknown field observability.activity.events.%s", field)
+ }
+}
+
func getSessionsField(s *SessionsFileConfig, field string) (string, error) {
if strings.HasPrefix(field, "dashboard.") {
return getDashboardSessionField(&s.Dashboard, strings.TrimPrefix(field, "dashboard."))
diff --git a/internal/config/editor_get_test.go b/internal/config/editor_get_test.go
index 7584d4e6..87387acc 100644
--- a/internal/config/editor_get_test.go
+++ b/internal/config/editor_get_test.go
@@ -17,6 +17,10 @@ func TestGetConfigValue_RoundTrip(t *testing.T) {
{"server.cookieSecure", "false", "false"},
{"sessions.dashboard.persist", "true", "true"},
{"sessions.dashboard.maxLifetimeSec", "604800", "604800"},
+ {"observability.activity.enabled", "true", "true"},
+ {"observability.activity.retentionDays", "14", "14"},
+ {"observability.activity.events.dashboard", "true", "true"},
+ {"observability.activity.events.mcp", "false", "false"},
{"browser.version", "120.0", "120.0"},
{"browser.binary", "/usr/bin/chrome", "/usr/bin/chrome"},
{"instanceDefaults.mode", "headed", "headed"},
@@ -111,6 +115,9 @@ func TestGetConfigValue_NilPointerReturnsEmpty(t *testing.T) {
"server.cookieSecure",
"sessions.dashboard.persist",
"sessions.dashboard.maxLifetimeSec",
+ "observability.activity.enabled",
+ "observability.activity.retentionDays",
+ "observability.activity.events.dashboard",
}
for _, path := range ptrs {
t.Run(path, func(t *testing.T) {
diff --git a/internal/config/editor_set.go b/internal/config/editor_set.go
index 709f60ad..51af8a27 100644
--- a/internal/config/editor_set.go
+++ b/internal/config/editor_set.go
@@ -30,10 +30,12 @@ func SetConfigValue(fc *FileConfig, path string, value string) error {
return setMultiInstanceField(&fc.MultiInstance, field, value)
case "timeouts":
return setTimeoutsField(&fc.Timeouts, field, value)
+ case "observability":
+ return setObservabilityField(&fc.Observability, field, value)
case "sessions":
return setSessionsField(&fc.Sessions, field, value)
default:
- return fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts, sessions)", section)
+ return fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts, observability, sessions)", section)
}
}
@@ -85,6 +87,72 @@ func setBrowserField(b *BrowserConfig, field, value string) error {
return nil
}
+func setObservabilityField(o *ObservabilityFileConfig, field, value string) error {
+ if strings.HasPrefix(field, "activity.") {
+ return setActivityField(&o.Activity, strings.TrimPrefix(field, "activity."), value)
+ }
+ return fmt.Errorf("unknown field observability.%s", field)
+}
+
+func setActivityField(a *ActivityFileConfig, field, value string) error {
+ if strings.HasPrefix(field, "events.") {
+ return setActivityEventField(&a.Events, strings.TrimPrefix(field, "events."), value)
+ }
+
+ switch field {
+ case "enabled":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("observability.activity.enabled: %w", err)
+ }
+ a.Enabled = &b
+ case "sessionIdleSec":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("observability.activity.sessionIdleSec must be a number: %w", err)
+ }
+ a.SessionIdleSec = &n
+ case "retentionDays":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("observability.activity.retentionDays must be a number: %w", err)
+ }
+ a.RetentionDays = &n
+ case "stateDir":
+ a.StateDir = value
+ default:
+ return fmt.Errorf("unknown field observability.activity.%s", field)
+ }
+ return nil
+}
+
+func setActivityEventField(e *ActivityEventsFileConfig, field, value string) error {
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("observability.activity.events.%s: %w", field, err)
+ }
+
+ switch field {
+ case "dashboard":
+ e.Dashboard = &b
+ case "server":
+ e.Server = &b
+ case "bridge":
+ e.Bridge = &b
+ case "orchestrator":
+ e.Orchestrator = &b
+ case "scheduler":
+ e.Scheduler = &b
+ case "mcp":
+ e.MCP = &b
+ case "other":
+ e.Other = &b
+ default:
+ return fmt.Errorf("unknown field observability.activity.events.%s", field)
+ }
+ return nil
+}
+
func setSessionsField(s *SessionsFileConfig, field, value string) error {
if strings.HasPrefix(field, "dashboard.") {
return setDashboardSessionField(&s.Dashboard, strings.TrimPrefix(field, "dashboard."), value)
diff --git a/internal/config/editor_set_test.go b/internal/config/editor_set_test.go
index 10b8a506..38da60db 100644
--- a/internal/config/editor_set_test.go
+++ b/internal/config/editor_set_test.go
@@ -20,6 +20,12 @@ func TestSetConfigValue_ServerFields(t *testing.T) {
{"sessions.dashboard.maxLifetimeSec", "604800", func(fc *FileConfig) bool {
return fc.Sessions.Dashboard.MaxLifetimeSec != nil && *fc.Sessions.Dashboard.MaxLifetimeSec == 604800
}, false},
+ {"observability.activity.enabled", "true", func(fc *FileConfig) bool {
+ return fc.Observability.Activity.Enabled != nil && *fc.Observability.Activity.Enabled
+ }, false},
+ {"observability.activity.events.dashboard", "true", func(fc *FileConfig) bool {
+ return fc.Observability.Activity.Events.Dashboard != nil && *fc.Observability.Activity.Events.Dashboard
+ }, false},
{"server.unknown", "value", nil, true},
}
diff --git a/internal/dashboard/agent_session_api.go b/internal/dashboard/agent_session_api.go
index bb73ba55..7e13644b 100644
--- a/internal/dashboard/agent_session_api.go
+++ b/internal/dashboard/agent_session_api.go
@@ -5,6 +5,7 @@ import (
"net/http"
"strings"
+ "github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/agentsession"
"github.com/pinchtab/pinchtab/internal/authn"
"github.com/pinchtab/pinchtab/internal/httpx"
@@ -22,12 +23,11 @@ func NewAgentSessionAPI(store *agentsession.Store) *AgentSessionAPI {
// RegisterHandlers registers agent session API routes.
func (a *AgentSessionAPI) RegisterHandlers(mux *http.ServeMux) {
- mux.HandleFunc("POST /api/sessions", a.handleCreate)
- mux.HandleFunc("GET /api/sessions", a.handleList)
- mux.HandleFunc("GET /api/sessions/me", a.handleMe)
- mux.HandleFunc("GET /api/sessions/{id}", a.handleGet)
- mux.HandleFunc("POST /api/sessions/{id}/rotate", a.handleRotate)
- mux.HandleFunc("POST /api/sessions/{id}/revoke", a.handleRevoke)
+ mux.HandleFunc("POST /sessions", a.handleCreate)
+ mux.HandleFunc("GET /sessions", a.handleList)
+ mux.HandleFunc("GET /sessions/me", a.handleMe)
+ mux.HandleFunc("GET /sessions/{id}", a.handleGet)
+ mux.HandleFunc("POST /sessions/{id}/revoke", a.handleRevoke)
}
func (a *AgentSessionAPI) handleCreate(w http.ResponseWriter, r *http.Request) {
@@ -51,6 +51,13 @@ func (a *AgentSessionAPI) handleCreate(w http.ResponseWriter, r *http.Request) {
}
sess, _ := a.store.Get(sessionID)
+
+ activity.EnrichRequest(r, activity.Update{
+ SessionID: sessionID,
+ AgentID: sess.AgentID,
+ Action: "sessions",
+ })
+
httpx.JSON(w, http.StatusCreated, map[string]any{
"id": sessionID,
"agentId": sess.AgentID,
@@ -83,7 +90,7 @@ func (a *AgentSessionAPI) handleGet(w http.ResponseWriter, r *http.Request) {
func (a *AgentSessionAPI) handleMe(w http.ResponseWriter, r *http.Request) {
creds := authn.CredentialsFromRequest(r)
if creds.Method != authn.MethodSession {
- httpx.ErrorCode(w, http.StatusBadRequest, "session_auth_required", "this endpoint requires session authentication", false, nil)
+ httpx.ErrorCode(w, http.StatusUnauthorized, "session_auth_required", "this endpoint requires session authentication", false, nil)
return
}
sess, ok := a.store.Authenticate(creds.Value)
@@ -94,24 +101,26 @@ func (a *AgentSessionAPI) handleMe(w http.ResponseWriter, r *http.Request) {
httpx.JSON(w, http.StatusOK, sess)
}
-func (a *AgentSessionAPI) handleRotate(w http.ResponseWriter, r *http.Request) {
+func (a *AgentSessionAPI) handleRevoke(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
- newToken, err := a.store.Rotate(id)
- if err != nil {
- httpx.ErrorCode(w, http.StatusBadRequest, "rotate_failed", err.Error(), false, nil)
+ creds := authn.CredentialsFromRequest(r)
+ switch creds.Method {
+ case authn.MethodSession:
+ sess, ok := a.store.Authenticate(creds.Value)
+ if !ok || sess == nil {
+ httpx.ErrorCode(w, http.StatusUnauthorized, "bad_session", "invalid or expired agent session", false, nil)
+ return
+ }
+ if sess.ID != id {
+ httpx.ErrorCode(w, http.StatusForbidden, "forbidden", "session callers may only revoke their own session", false, nil)
+ return
+ }
+ case authn.MethodHeader, authn.MethodCookie:
+ // Dashboard-authenticated callers may revoke any session.
+ default:
+ httpx.ErrorCode(w, http.StatusForbidden, "forbidden", "not allowed to revoke this session", false, nil)
return
}
- sess, _ := a.store.Get(id)
- httpx.JSON(w, http.StatusOK, map[string]any{
- "id": sess.ID,
- "agentId": sess.AgentID,
- "sessionToken": newToken,
- "status": sess.Status,
- })
-}
-
-func (a *AgentSessionAPI) handleRevoke(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
if !a.store.Revoke(id) {
httpx.ErrorCode(w, http.StatusNotFound, "session_not_found", "agent session not found", false, nil)
return
diff --git a/internal/dashboard/agent_session_api_test.go b/internal/dashboard/agent_session_api_test.go
new file mode 100644
index 00000000..bc7a24af
--- /dev/null
+++ b/internal/dashboard/agent_session_api_test.go
@@ -0,0 +1,302 @@
+package dashboard
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/agentsession"
+)
+
+func newTestSessionStore() *agentsession.Store {
+ return agentsession.NewStore(agentsession.Config{
+ Enabled: true,
+ IdleTimeout: 30 * time.Minute,
+ MaxLifetime: 24 * time.Hour,
+ })
+}
+
+func newTestSessionMux(store *agentsession.Store) *http.ServeMux {
+ mux := http.NewServeMux()
+ NewAgentSessionAPI(store).RegisterHandlers(mux)
+ return mux
+}
+
+func decodeSessionResponse(t *testing.T, w *httptest.ResponseRecorder) map[string]any {
+ t.Helper()
+ var m map[string]any
+ if err := json.NewDecoder(w.Body).Decode(&m); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ return m
+}
+
+func TestAgentSessionAPI_Create(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ req := httptest.NewRequest("POST", "/sessions", strings.NewReader(`{"agentId":"agent-1","label":"ci-run"}`))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusCreated)
+ }
+ resp := decodeSessionResponse(t, w)
+ if resp["id"] == "" || resp["id"] == nil {
+ t.Fatal("expected id in response")
+ }
+ if resp["sessionToken"] == "" || resp["sessionToken"] == nil {
+ t.Fatal("expected sessionToken in response")
+ }
+ if resp["agentId"] != "agent-1" {
+ t.Fatalf("agentId = %q, want agent-1", resp["agentId"])
+ }
+ if resp["label"] != "ci-run" {
+ t.Fatalf("label = %q, want ci-run", resp["label"])
+ }
+ if resp["status"] != "active" {
+ t.Fatalf("status = %q, want active", resp["status"])
+ }
+}
+
+func TestAgentSessionAPI_Create_MissingAgentID(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ req := httptest.NewRequest("POST", "/sessions", strings.NewReader(`{"label":"ci-run"}`))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusBadRequest)
+ }
+}
+
+func TestAgentSessionAPI_Create_InvalidJSON(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ req := httptest.NewRequest("POST", "/sessions", strings.NewReader(`not json`))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusBadRequest)
+ }
+}
+
+func TestAgentSessionAPI_List(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ _, _, _ = store.Create("agent-1", "first")
+ _, _, _ = store.Create("agent-2", "second")
+
+ req := httptest.NewRequest("GET", "/sessions", nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
+ }
+ var sessions []map[string]any
+ if err := json.NewDecoder(w.Body).Decode(&sessions); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if len(sessions) != 2 {
+ t.Fatalf("len(sessions) = %d, want 2", len(sessions))
+ }
+}
+
+func TestAgentSessionAPI_List_Empty(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ req := httptest.NewRequest("GET", "/sessions", nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
+ }
+ var sessions []map[string]any
+ if err := json.NewDecoder(w.Body).Decode(&sessions); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if len(sessions) != 0 {
+ t.Fatalf("len(sessions) = %d, want 0", len(sessions))
+ }
+}
+
+func TestAgentSessionAPI_Get(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ id, _, _ := store.Create("agent-1", "my-session")
+
+ req := httptest.NewRequest("GET", "/sessions/"+id, nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
+ }
+ resp := decodeSessionResponse(t, w)
+ if resp["id"] != id {
+ t.Fatalf("id = %q, want %q", resp["id"], id)
+ }
+ if resp["agentId"] != "agent-1" {
+ t.Fatalf("agentId = %q, want agent-1", resp["agentId"])
+ }
+}
+
+func TestAgentSessionAPI_Get_NotFound(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ req := httptest.NewRequest("GET", "/sessions/ses_doesnotexist", nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusNotFound)
+ }
+}
+
+func TestAgentSessionAPI_Me(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ _, token, _ := store.Create("agent-1", "my-session")
+
+ req := httptest.NewRequest("GET", "/sessions/me", nil)
+ req.Header.Set("Authorization", "Session "+token)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
+ }
+ resp := decodeSessionResponse(t, w)
+ if resp["agentId"] != "agent-1" {
+ t.Fatalf("agentId = %q, want agent-1", resp["agentId"])
+ }
+}
+
+func TestAgentSessionAPI_Me_RequiresSessionAuth(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ req := httptest.NewRequest("GET", "/sessions/me", nil)
+ req.Header.Set("Authorization", "Bearer some-bearer-token")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want %d (bearer should not work for /me)", w.Code, http.StatusUnauthorized)
+ }
+}
+
+func TestAgentSessionAPI_Me_InvalidToken(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ req := httptest.NewRequest("GET", "/sessions/me", nil)
+ req.Header.Set("Authorization", "Session ses_invalidtoken")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusUnauthorized)
+ }
+}
+
+func TestAgentSessionAPI_Revoke(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ id, token, _ := store.Create("agent-1", "")
+
+ req := httptest.NewRequest("POST", "/sessions/"+id+"/revoke", nil)
+ req.Header.Set("Authorization", "Bearer dashboard-token")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
+ }
+
+ // Token should no longer authenticate
+ if sess, ok := store.Authenticate(token); ok || sess != nil {
+ t.Fatal("expected token to be invalidated after revoke")
+ }
+}
+
+func TestAgentSessionAPI_Revoke_NotFound(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ req := httptest.NewRequest("POST", "/sessions/ses_doesnotexist/revoke", nil)
+ req.Header.Set("Authorization", "Bearer dashboard-token")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusNotFound)
+ }
+}
+
+func TestAgentSessionAPI_Revoke_SessionOwnerAllowed(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ id, token, _ := store.Create("agent-1", "")
+
+ req := httptest.NewRequest("POST", "/sessions/"+id+"/revoke", nil)
+ req.Header.Set("Authorization", "Session "+token)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
+ }
+}
+
+func TestAgentSessionAPI_Revoke_SessionCallerCannotRevokeOtherSession(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ _, token, _ := store.Create("agent-1", "")
+ otherID, _, _ := store.Create("agent-2", "")
+
+ req := httptest.NewRequest("POST", "/sessions/"+otherID+"/revoke", nil)
+ req.Header.Set("Authorization", "Session "+token)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusForbidden)
+ }
+}
+
+func TestAgentSessionAPI_Revoke_RejectsUnauthenticatedCaller(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ id, _, _ := store.Create("agent-1", "")
+
+ req := httptest.NewRequest("POST", "/sessions/"+id+"/revoke", nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusForbidden)
+ }
+}
diff --git a/internal/dashboard/dashboard.go b/internal/dashboard/dashboard.go
index 2e4f848d..ceaaa8ca 100644
--- a/internal/dashboard/dashboard.go
+++ b/internal/dashboard/dashboard.go
@@ -112,9 +112,6 @@ func activityEventToLiveEvent(evt activity.Event) apiTypes.ActivityEvent {
if evt.SessionID != "" {
details["sessionId"] = evt.SessionID
}
- if evt.ActorID != "" {
- details["actorId"] = evt.ActorID
- }
if evt.InstanceID != "" {
details["instanceId"] = evt.InstanceID
}
@@ -238,8 +235,9 @@ func (d *Dashboard) IngestPersistedAgentActivity(rec activity.Recorder, since ti
}
events, err := rec.Query(activity.Filter{
- Since: since,
- Limit: persistedAgentBootstrapLimit,
+ Source: "client",
+ Since: since,
+ Limit: persistedAgentBootstrapLimit,
})
if err != nil {
return since, err
@@ -251,9 +249,6 @@ func (d *Dashboard) IngestPersistedAgentActivity(rec activity.Recorder, since ti
if evt.Timestamp.After(latest) {
latest = evt.Timestamp
}
- if strings.TrimSpace(evt.AgentID) == "" {
- continue
- }
if !shouldTrackPersistedAgentActivity(evt) {
continue
}
@@ -546,7 +541,7 @@ func matchesMode(mode, channel string) bool {
}
func shouldTrackPersistedAgentActivity(evt activity.Event) bool {
- return strings.TrimSpace(evt.AgentID) != ""
+ return evt.Source == "client"
}
func (d *Dashboard) rememberEventIDLocked(id string) {
diff --git a/internal/dashboard/dashboard_test.go b/internal/dashboard/dashboard_test.go
index d8da4609..bac10733 100644
--- a/internal/dashboard/dashboard_test.go
+++ b/internal/dashboard/dashboard_test.go
@@ -305,7 +305,7 @@ func TestDashboardLoadPersistedAgentActivityRestoresAgentsAndEvents(t *testing.T
events: []activity.Event{
{
Timestamp: now.Add(-2 * time.Minute),
- Source: "bridge",
+ Source: "client",
RequestID: "req-1",
AgentID: "agent-1",
Method: http.MethodPost,
@@ -317,7 +317,7 @@ func TestDashboardLoadPersistedAgentActivityRestoresAgentsAndEvents(t *testing.T
},
{
Timestamp: now.Add(-1 * time.Minute),
- Source: "bridge",
+ Source: "client",
RequestID: "req-2",
Method: http.MethodGet,
Path: "/health",
@@ -326,7 +326,7 @@ func TestDashboardLoadPersistedAgentActivityRestoresAgentsAndEvents(t *testing.T
},
{
Timestamp: now,
- Source: "server",
+ Source: "client",
RequestID: "req-3",
AgentID: "agent-2",
Method: http.MethodGet,
@@ -342,16 +342,16 @@ func TestDashboardLoadPersistedAgentActivityRestoresAgentsAndEvents(t *testing.T
}
agents := d.Agents()
- if len(agents) != 2 {
- t.Fatalf("Agents() len = %d, want 2", len(agents))
+ if len(agents) != 3 {
+ t.Fatalf("Agents() len = %d, want 3", len(agents))
}
events := d.RecentEvents()
- if len(events) != 2 {
- t.Fatalf("RecentEvents() len = %d, want 2", len(events))
+ if len(events) != 3 {
+ t.Fatalf("RecentEvents() len = %d, want 3", 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)
+ if events[0].ID != "req-1" || events[1].ID != "req-2" || events[2].ID != "req-3" {
+ t.Fatalf("RecentEvents() IDs = [%s, %s, %s], want [req-1, req-2, req-3]", events[0].ID, events[1].ID, events[2].ID)
}
}
@@ -361,7 +361,7 @@ func TestDashboardIngestPersistedAgentActivityAddsNewEventsWithoutDuplicatingLiv
d.RecordActivityEvent(activity.Event{
Timestamp: now.Add(-2 * time.Second),
- Source: "bridge",
+ Source: "client",
RequestID: "req-live",
AgentID: "agent-1",
Method: http.MethodPost,
@@ -376,7 +376,7 @@ func TestDashboardIngestPersistedAgentActivityAddsNewEventsWithoutDuplicatingLiv
events: []activity.Event{
{
Timestamp: now.Add(-2 * time.Second),
- Source: "bridge",
+ Source: "client",
RequestID: "req-live",
AgentID: "agent-1",
Method: http.MethodPost,
@@ -388,7 +388,7 @@ func TestDashboardIngestPersistedAgentActivityAddsNewEventsWithoutDuplicatingLiv
},
{
Timestamp: now,
- Source: "bridge",
+ Source: "client",
RequestID: "req-new",
AgentID: "agent-2",
Method: http.MethodGet,
@@ -420,6 +420,48 @@ func TestDashboardIngestPersistedAgentActivityAddsNewEventsWithoutDuplicatingLiv
}
}
+func TestDashboardLoadPersistedAgentActivityNormalizesBlankAgentIDToAnonymous(t *testing.T) {
+ d := NewDashboard(nil)
+ now := time.Now().UTC()
+
+ err := d.LoadPersistedAgentActivity(stubActivityRecorder{
+ events: []activity.Event{
+ {
+ Timestamp: now,
+ Source: "client",
+ RequestID: "req-anon",
+ Method: http.MethodGet,
+ Path: "/text",
+ Status: http.StatusOK,
+ DurationMs: 6,
+ SessionID: "ses_publicid123",
+ },
+ },
+ })
+ if err != nil {
+ t.Fatalf("LoadPersistedAgentActivity() error = %v", err)
+ }
+
+ agents := d.Agents()
+ if len(agents) != 1 {
+ t.Fatalf("Agents() len = %d, want 1", len(agents))
+ }
+ if agents[0].ID != "anonymous" {
+ t.Fatalf("Agents()[0].ID = %q, want anonymous", agents[0].ID)
+ }
+
+ events := d.RecentEvents()
+ if len(events) != 1 {
+ t.Fatalf("RecentEvents() len = %d, want 1", len(events))
+ }
+ if events[0].AgentID != "anonymous" {
+ t.Fatalf("RecentEvents()[0].AgentID = %q, want anonymous", events[0].AgentID)
+ }
+ if got := events[0].Details["sessionId"]; got != "ses_publicid123" {
+ t.Fatalf("RecentEvents()[0].Details[sessionId] = %#v, want ses_publicid123", got)
+ }
+}
+
func TestMatchesMode(t *testing.T) {
tests := []struct {
mode string
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.go
index 70ff9ece..f564a341 100644
--- a/internal/handlers/actions.go
+++ b/internal/handlers/actions.go
@@ -12,6 +12,7 @@ import (
"strings"
"time"
+ "github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/engine"
"github.com/pinchtab/pinchtab/internal/httpx"
@@ -138,6 +139,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
}
}
h.recordResolvedTab(r, resolvedTabID)
+ w.Header().Set(activity.HeaderPTTabID, resolvedTabID)
// Allow custom timeout via query param (1-60 seconds)
actionTimeout := h.Config.ActionTimeout
diff --git a/internal/handlers/activity_helpers.go b/internal/handlers/activity_helpers.go
index 9b86a23a..f30b3f02 100644
--- a/internal/handlers/activity_helpers.go
+++ b/internal/handlers/activity_helpers.go
@@ -16,6 +16,17 @@ func (h *Handlers) tabContext(r *http.Request, tabID string) (context.Context, s
return ctx, resolvedID, err
}
+// tabContextWithHeader resolves the tab and sets the resolved tab ID as a
+// response header so the orchestrator proxy can enrich activity events
+// even for large responses (e.g. snapshots) that exceed the body-inspection threshold.
+func (h *Handlers) tabContextWithHeader(w http.ResponseWriter, r *http.Request, tabID string) (context.Context, string, error) {
+ ctx, resolvedID, err := h.tabContext(r, tabID)
+ if err == nil {
+ w.Header().Set(activity.HeaderPTTabID, resolvedID)
+ }
+ return ctx, resolvedID, err
+}
+
func (h *Handlers) recordActivity(r *http.Request, update activity.Update) {
activity.EnrichRequest(r, update)
}
diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.go
index 0bd54451..bc361167 100644
--- a/internal/handlers/middleware.go
+++ b/internal/handlers/middleware.go
@@ -124,6 +124,12 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.Sessi
AgentID: sess.AgentID,
SessionID: sess.ID,
})
+ if !sessionRequestAllowed(r, sess) {
+ httpx.ErrorCode(w, http.StatusForbidden, "session_scope_forbidden", "agent session is not allowed to access this endpoint", false, map[string]any{
+ "safeControlledEnvironmentOnly": true,
+ })
+ return
+ }
case authn.MethodHeader:
if subtle.ConstantTimeCompare([]byte(creds.Value), []byte(token)) != 1 {
authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders, cookieSecureSetting(cfg))
@@ -165,6 +171,313 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.Sessi
})
}
+func sessionRequestAllowed(r *http.Request, sess *agentsession.Session) bool {
+ method := strings.ToUpper(strings.TrimSpace(r.Method))
+ path := strings.TrimSpace(r.URL.Path)
+ if method == http.MethodPost && sessionRevokePath(path) {
+ return true
+ }
+ if sessionAdminRoute(method, path) {
+ return false
+ }
+ if sess == nil {
+ return false
+ }
+
+ grants := normalizedSessionGrants(sess.Grants)
+ if len(grants) == 0 || grants["*"] {
+ return true
+ }
+
+ for grant := range grants {
+ if sessionGrantAllows(grant, method, path) {
+ return true
+ }
+ }
+ return false
+}
+
+func normalizedSessionGrants(grants []string) map[string]bool {
+ out := make(map[string]bool, len(grants))
+ for _, grant := range grants {
+ normalized := strings.ToLower(strings.TrimSpace(grant))
+ if normalized == "" {
+ continue
+ }
+ out[normalized] = true
+ }
+ return out
+}
+
+func sessionAdminRoute(method, path string) bool {
+ switch {
+ case method == http.MethodGet && path == "/api/config":
+ return true
+ case method == http.MethodPut && path == "/api/config":
+ return true
+ case method == http.MethodPost && path == "/shutdown":
+ return true
+ case method == http.MethodPost && (path == "/browser/restart" || path == "/ensure-chrome"):
+ return true
+ case method == http.MethodPost && path == "/fingerprint/rotate":
+ return true
+ case method == http.MethodGet && path == "/api/events":
+ return true
+ case method == http.MethodGet && path == "/api/metrics":
+ return true
+ case method == http.MethodGet && path == "/api/agents":
+ return true
+ case method == http.MethodGet && strings.HasPrefix(path, "/api/agents/") && !strings.HasSuffix(path, "/events"):
+ return true
+ case path == "/sessions" || strings.HasPrefix(path, "/sessions/"):
+ return path != "/sessions/me"
+ case path == "/instances" || strings.HasPrefix(path, "/instances/"):
+ return true
+ case path == "/profiles" || strings.HasPrefix(path, "/profiles/"):
+ return true
+ case method == http.MethodGet && path == "/cache/status":
+ return true
+ case method == http.MethodPost && path == "/cache/clear":
+ return true
+ default:
+ return false
+ }
+}
+
+func sessionRevokePath(path string) bool {
+ if !strings.HasPrefix(path, "/sessions/") || !strings.HasSuffix(path, "/revoke") {
+ return false
+ }
+ sessionID := strings.TrimSuffix(strings.TrimPrefix(path, "/sessions/"), "/revoke")
+ return strings.Trim(sessionID, "/") != ""
+}
+
+func sessionGrantAllows(grant, method, path string) bool {
+ switch grant {
+ case "browse":
+ return sessionBrowseGrantAllows(method, path)
+ case "network":
+ return sessionNetworkGrantAllows(method, path)
+ case "media":
+ return sessionMediaGrantAllows(method, path)
+ case "cookies":
+ return sessionCookiesGrantAllows(method, path)
+ case "clipboard":
+ return sessionClipboardGrantAllows(method, path)
+ case "evaluate":
+ return sessionEvaluateGrantAllows(method, path)
+ case "storage":
+ return sessionStorageGrantAllows(method, path)
+ case "console":
+ return sessionConsoleGrantAllows(method, path)
+ case "solve":
+ return sessionSolveGrantAllows(method, path)
+ case "tasks":
+ return sessionTasksGrantAllows(method, path)
+ case "activity":
+ return sessionActivityGrantAllows(method, path)
+ default:
+ return false
+ }
+}
+
+func sessionBrowseGrantAllows(method, path string) bool {
+ switch method {
+ case http.MethodGet:
+ switch {
+ case path == "/tabs",
+ path == "/navigate",
+ path == "/action",
+ path == "/snapshot",
+ path == "/screenshot",
+ path == "/text",
+ path == "/openapi.json",
+ path == "/help",
+ path == "/health",
+ path == "/sessions/me":
+ return true
+ case tabRouteHasSuffix(path, "/snapshot"),
+ tabRouteHasSuffix(path, "/screenshot"),
+ tabRouteHasSuffix(path, "/text"),
+ tabRouteHasSuffix(path, "/metrics"):
+ return true
+ }
+ case http.MethodPost:
+ switch {
+ case path == "/tab",
+ path == "/navigate",
+ path == "/back",
+ path == "/forward",
+ path == "/reload",
+ path == "/action",
+ path == "/actions",
+ path == "/macro",
+ path == "/find",
+ path == "/wait",
+ path == "/dialog",
+ path == "/lock",
+ path == "/unlock":
+ return true
+ case tabRouteHasSuffix(path, "/navigate"),
+ tabRouteHasSuffix(path, "/back"),
+ tabRouteHasSuffix(path, "/forward"),
+ tabRouteHasSuffix(path, "/reload"),
+ tabRouteHasSuffix(path, "/action"),
+ tabRouteHasSuffix(path, "/actions"),
+ tabRouteHasSuffix(path, "/find"),
+ tabRouteHasSuffix(path, "/wait"),
+ tabRouteHasSuffix(path, "/dialog"),
+ tabRouteHasSuffix(path, "/lock"),
+ tabRouteHasSuffix(path, "/unlock"):
+ return true
+ }
+ }
+ return false
+}
+
+func sessionNetworkGrantAllows(method, path string) bool {
+ switch method {
+ case http.MethodGet:
+ switch {
+ case path == "/network",
+ path == "/network/stream",
+ path == "/network/export",
+ path == "/network/export/stream":
+ return true
+ case strings.HasPrefix(path, "/network/"):
+ return true
+ case tabRouteHasSuffix(path, "/network"),
+ tabRouteHasSuffix(path, "/network/stream"),
+ tabRouteHasSuffix(path, "/network/export"),
+ tabRouteHasSuffix(path, "/network/export/stream"):
+ return true
+ case strings.HasPrefix(path, "/tabs/") && strings.Contains(path, "/network/"):
+ return true
+ }
+ case http.MethodPost:
+ return path == "/network/clear"
+ }
+ return false
+}
+
+func sessionMediaGrantAllows(method, path string) bool {
+ switch method {
+ case http.MethodGet:
+ switch {
+ case path == "/pdf",
+ path == "/download",
+ path == "/screencast",
+ path == "/screencast/tabs":
+ return true
+ case tabRouteHasSuffix(path, "/pdf"),
+ tabRouteHasSuffix(path, "/download"):
+ return true
+ }
+ case http.MethodPost:
+ switch {
+ case path == "/pdf",
+ path == "/upload":
+ return true
+ case tabRouteHasSuffix(path, "/pdf"),
+ tabRouteHasSuffix(path, "/upload"):
+ return true
+ }
+ }
+ return false
+}
+
+func sessionCookiesGrantAllows(method, path string) bool {
+ switch method {
+ case http.MethodGet, http.MethodPost:
+ return path == "/cookies" || tabRouteHasSuffix(path, "/cookies")
+ default:
+ return false
+ }
+}
+
+func sessionClipboardGrantAllows(method, path string) bool {
+ switch method {
+ case http.MethodGet:
+ return path == "/clipboard/read" || path == "/clipboard/paste"
+ case http.MethodPost:
+ return path == "/clipboard/write" || path == "/clipboard/copy"
+ default:
+ return false
+ }
+}
+
+func sessionEvaluateGrantAllows(method, path string) bool {
+ if method != http.MethodPost {
+ return false
+ }
+ return path == "/evaluate" || tabRouteHasSuffix(path, "/evaluate")
+}
+
+func sessionStorageGrantAllows(method, path string) bool {
+ switch method {
+ case http.MethodGet:
+ return path == "/storage" || path == "/state/list" || path == "/state/show"
+ case http.MethodPost:
+ return path == "/storage" || path == "/state/save" || path == "/state/load" || path == "/state/clean"
+ case http.MethodDelete:
+ return path == "/storage" || path == "/state"
+ default:
+ return false
+ }
+}
+
+func sessionConsoleGrantAllows(method, path string) bool {
+ switch method {
+ case http.MethodGet:
+ return path == "/console" || path == "/errors"
+ case http.MethodPost:
+ return path == "/console/clear" || path == "/errors/clear"
+ default:
+ return false
+ }
+}
+
+func sessionSolveGrantAllows(method, path string) bool {
+ switch method {
+ case http.MethodGet:
+ return path == "/solvers"
+ case http.MethodPost:
+ switch {
+ case path == "/solve" || strings.HasPrefix(path, "/solve/"):
+ return true
+ case tabRouteHasSuffix(path, "/solve") || (strings.HasPrefix(path, "/tabs/") && strings.Contains(path, "/solve/")):
+ return true
+ }
+ }
+ return false
+}
+
+func sessionTasksGrantAllows(method, path string) bool {
+ switch method {
+ case http.MethodGet:
+ return path == "/tasks" || path == "/scheduler/stats" || strings.HasPrefix(path, "/tasks/")
+ case http.MethodPost:
+ return path == "/tasks" || path == "/tasks/batch" || (strings.HasPrefix(path, "/tasks/") && strings.HasSuffix(path, "/cancel"))
+ default:
+ return false
+ }
+}
+
+func sessionActivityGrantAllows(method, path string) bool {
+ switch method {
+ case http.MethodGet:
+ return path == "/api/activity" || (strings.HasPrefix(path, "/api/agents/") && strings.HasSuffix(path, "/events"))
+ case http.MethodPost:
+ return strings.HasPrefix(path, "/api/agents/") && strings.HasSuffix(path, "/events")
+ default:
+ return false
+ }
+}
+
+func tabRouteHasSuffix(path, suffix string) bool {
+ return strings.HasPrefix(path, "/tabs/") && strings.HasSuffix(path, suffix)
+}
+
func isPublicDashboardPath(path string) bool {
switch path {
case "/", "/login", "/dashboard", "/dashboard/":
@@ -194,8 +507,8 @@ func cookieAuthAllowed(r *http.Request) bool {
path == "/api/agents",
path == "/api/events",
path == "/api/config",
- path == "/api/sessions",
- strings.HasPrefix(path, "/api/sessions/"),
+ path == "/sessions",
+ strings.HasPrefix(path, "/sessions/"),
path == "/profiles",
path == "/instances",
path == "/instances/tabs",
diff --git a/internal/handlers/middleware_test.go b/internal/handlers/middleware_test.go
index 9b28ef7f..dfb8b66c 100644
--- a/internal/handlers/middleware_test.go
+++ b/internal/handlers/middleware_test.go
@@ -7,12 +7,28 @@ import (
"testing"
"time"
+ "github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/agentsession"
"github.com/pinchtab/pinchtab/internal/authn"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/httpx"
)
+type activityCaptureRecorder struct {
+ events []activity.Event
+}
+
+func (c *activityCaptureRecorder) Enabled() bool { return true }
+
+func (c *activityCaptureRecorder) Record(evt activity.Event) error {
+ c.events = append(c.events, evt)
+ return nil
+}
+
+func (c *activityCaptureRecorder) Query(activity.Filter) ([]activity.Event, error) {
+ return append([]activity.Event(nil), c.events...), nil
+}
+
func resetRateLimitStateForTests() {
rateMu.Lock()
rateBuckets = map[string][]time.Time{}
@@ -1015,6 +1031,165 @@ func TestAuthMiddleware_SessionAuth(t *testing.T) {
}
}
+func TestAuthMiddleware_SessionAuthRejectsDashboardAdminRoute(t *testing.T) {
+ store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})
+ _, token, _ := store.Create("test-agent", "test")
+
+ cfg := &config.RuntimeConfig{Token: "server-token"}
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(http.MethodGet, "/api/config", nil)
+ req.Header.Set("Authorization", "Session "+token)
+ rr := httptest.NewRecorder()
+ handler.ServeHTTP(rr, req)
+
+ if called {
+ t.Fatal("handler should not be called for dashboard/admin route via session auth")
+ }
+ if rr.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d", rr.Code)
+ }
+}
+
+func TestAuthMiddleware_SessionAuthWithoutGrantsAllowsNonAdminRoutes(t *testing.T) {
+ store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})
+ _, token, _ := store.Create("test-agent", "test")
+
+ cfg := &config.RuntimeConfig{Token: "server-token"}
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(http.MethodPost, "/evaluate", nil)
+ req.Header.Set("Authorization", "Session "+token)
+ rr := httptest.NewRecorder()
+ handler.ServeHTTP(rr, req)
+
+ if !called {
+ t.Fatal("handler should be called for non-admin route when grants are empty")
+ }
+ if rr.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", rr.Code)
+ }
+}
+
+func TestAuthMiddleware_SessionAuthAllowsRevokeRouteToReachHandler(t *testing.T) {
+ store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})
+ sessionID, token, _ := store.Create("test-agent", "test")
+
+ cfg := &config.RuntimeConfig{Token: "server-token"}
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(http.MethodPost, "/sessions/"+sessionID+"/revoke", nil)
+ req.Header.Set("Authorization", "Session "+token)
+ rr := httptest.NewRecorder()
+ handler.ServeHTTP(rr, req)
+
+ if !called {
+ t.Fatal("handler should be called for session revoke route")
+ }
+ if rr.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", rr.Code)
+ }
+}
+
+func TestAuthMiddleware_SessionAuthHonorsBrowseGrant(t *testing.T) {
+ store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})
+ sessionID, token, _ := store.Create("test-agent", "test")
+ sess, ok := store.Get(sessionID)
+ if !ok || sess == nil {
+ t.Fatal("expected session to exist")
+ }
+ sess.Grants = []string{"browse"}
+
+ cfg := &config.RuntimeConfig{Token: "server-token"}
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(http.MethodGet, "/text", nil)
+ req.Header.Set("Authorization", "Session "+token)
+ rr := httptest.NewRecorder()
+ handler.ServeHTTP(rr, req)
+
+ if !called {
+ t.Fatal("handler should be called for route covered by browse grant")
+ }
+ if rr.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", rr.Code)
+ }
+}
+
+func TestAuthMiddleware_SessionAuthRejectsRouteOutsideGrant(t *testing.T) {
+ store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})
+ sessionID, token, _ := store.Create("test-agent", "test")
+ sess, ok := store.Get(sessionID)
+ if !ok || sess == nil {
+ t.Fatal("expected session to exist")
+ }
+ sess.Grants = []string{"browse"}
+
+ cfg := &config.RuntimeConfig{Token: "server-token"}
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(http.MethodGet, "/clipboard/read", nil)
+ req.Header.Set("Authorization", "Session "+token)
+ rr := httptest.NewRecorder()
+ handler.ServeHTTP(rr, req)
+
+ if called {
+ t.Fatal("handler should not be called for route outside granted scope")
+ }
+ if rr.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d", rr.Code)
+ }
+}
+
+func TestAuthMiddleware_SessionAuthEnrichesActivity(t *testing.T) {
+ store := agentsession.NewStore(agentsession.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})
+ sessionID, token, _ := store.Create("test-agent", "test")
+ rec := &activityCaptureRecorder{}
+
+ cfg := &config.RuntimeConfig{Token: "server-token"}
+ handler := activity.Middleware(rec, "server", AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })))
+
+ req := httptest.NewRequest(http.MethodGet, "/text", nil)
+ req.Header.Set("Authorization", "Session "+token)
+ rr := httptest.NewRecorder()
+ handler.ServeHTTP(rr, req)
+
+ if rr.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", rr.Code)
+ }
+ if len(rec.events) != 1 {
+ t.Fatalf("len(events) = %d, want 1", len(rec.events))
+ }
+ if rec.events[0].SessionID != sessionID {
+ t.Fatalf("event.SessionID = %q, want %q", rec.events[0].SessionID, sessionID)
+ }
+ if rec.events[0].AgentID != "test-agent" {
+ t.Fatalf("event.AgentID = %q, want test-agent", rec.events[0].AgentID)
+ }
+}
+
func TestAuthMiddleware_SessionAuthInvalid(t *testing.T) {
store := agentsession.NewStore(agentsession.Config{Enabled: true})
diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.go
index e417ac0d..83b0b318 100644
--- a/internal/handlers/snapshot.go
+++ b/internal/handlers/snapshot.go
@@ -119,7 +119,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
}
}
- ctx, resolvedTabID, err := h.tabContext(r, tabID)
+ ctx, resolvedTabID, err := h.tabContextWithHeader(w, r, tabID)
if err != nil {
httpx.Error(w, 404, err)
return
diff --git a/internal/handlers/text.go b/internal/handlers/text.go
index b17337df..baeb2c5e 100644
--- a/internal/handlers/text.go
+++ b/internal/handlers/text.go
@@ -58,7 +58,7 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
}
}
- ctx, resolvedTabID, err := h.tabContext(r, tabID)
+ ctx, resolvedTabID, err := h.tabContextWithHeader(w, r, tabID)
if err != nil {
httpx.Error(w, 404, err)
return
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index 7438bb08..95f6fdbf 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -378,6 +378,8 @@ func (o *Orchestrator) writeChildConfig(port string, cdpPort int, profilePath, i
fc := config.FileConfigFromRuntime(o.runtimeCfg)
fc.Server.Port = port
fc.Server.StateDir = instanceStateDir
+ activityEnabled := false
+ fc.Observability.Activity.Enabled = &activityEnabled
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.go
index 6bb9bf15..0afd6f85 100644
--- a/internal/orchestrator/orchestrator_test.go
+++ b/internal/orchestrator/orchestrator_test.go
@@ -352,6 +352,9 @@ func TestOrchestrator_Launch_DoesNotInjectSharedActivityStateDir(t *testing.T) {
if fc.Observability.Activity.StateDir != "" {
t.Fatalf("child Observability.Activity.StateDir = %q, want empty", fc.Observability.Activity.StateDir)
}
+ if fc.Observability.Activity.Enabled == nil || *fc.Observability.Activity.Enabled {
+ t.Fatalf("child Observability.Activity.Enabled = %v, want explicit false", fc.Observability.Activity.Enabled)
+ }
if got := envMap(runner.env)["PINCHTAB_INTERNAL_ACTIVITY_STATE_DIR"]; got != "" {
t.Fatalf("PINCHTAB_INTERNAL_ACTIVITY_STATE_DIR = %q, want empty", got)
}
diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go
index 5fb4d431..d63bf3db 100644
--- a/internal/proxy/proxy.go
+++ b/internal/proxy/proxy.go
@@ -99,6 +99,9 @@ func Forward(w http.ResponseWriter, r *http.Request, targetURL *url.URL, opts Op
copyHeaders(w.Header(), resp.Header)
+ // Enrich activity from response headers (always available, regardless of body size).
+ enrichActivityFromHeaders(r, resp.Header)
+
// For small JSON responses, buffer to allow OnResponse to inspect the body.
if opts.OnResponse != nil && isSmallJSON(resp) {
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
@@ -150,6 +153,16 @@ func HTTP(w http.ResponseWriter, r *http.Request, targetURL string) {
Forward(w, r, parsed, Options{})
}
+// enrichActivityFromHeaders extracts tab ID from upstream response headers
+// and enriches the activity event. This works for all response sizes,
+// unlike body-based enrichment which is limited to small JSON responses.
+func enrichActivityFromHeaders(origReq *http.Request, respHeaders http.Header) {
+ tabID := strings.TrimSpace(respHeaders.Get(activity.HeaderPTTabID))
+ if tabID != "" {
+ activity.EnrichRequest(origReq, activity.Update{TabID: tabID})
+ }
+}
+
func isWebSocketUpgrade(r *http.Request) bool {
for _, v := range r.Header["Upgrade"] {
if strings.EqualFold(v, "websocket") {
diff --git a/internal/server/activity_recorder.go b/internal/server/activity_recorder.go
index 369b092d..207d111f 100644
--- a/internal/server/activity_recorder.go
+++ b/internal/server/activity_recorder.go
@@ -1,9 +1,6 @@
package server
import (
- "net/http"
- "strings"
-
"github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/dashboard"
)
@@ -44,16 +41,5 @@ func (r dashboardActivityRecorder) Query(filter activity.Filter) ([]activity.Eve
}
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", "/api/metrics":
- return false
- default:
- return true
- }
+ return evt.Source == "client"
}
diff --git a/internal/server/activity_recorder_test.go b/internal/server/activity_recorder_test.go
index 1185eccc..46b955de 100644
--- a/internal/server/activity_recorder_test.go
+++ b/internal/server/activity_recorder_test.go
@@ -26,29 +26,32 @@ func (s *stubRecorder) Query(activity.Filter) ([]activity.Event, error) {
return nil, nil
}
-func TestDashboardActivityRecorderSkipsInternalOrchestratorMonitoringEvents(t *testing.T) {
+func TestDashboardActivityRecorderSkipsNonClientEvents(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)
+ for _, source := range []string{"orchestrator", "server", "bridge", "dashboard"} {
+ err := rec.Record(activity.Event{
+ Timestamp: time.Now().UTC(),
+ Source: source,
+ Method: http.MethodPost,
+ Path: "/tabs/tab_1/navigate",
+ AgentID: "agent-1",
+ })
+ if err != nil {
+ t.Fatalf("Record(source=%q) error = %v", source, err)
+ }
}
- if len(base.events) != 1 {
- t.Fatalf("base recorder events = %d, want 1", len(base.events))
+ if len(base.events) != 4 {
+ t.Fatalf("base recorder events = %d, want 4", len(base.events))
}
if len(dash.RecentEvents()) != 0 {
t.Fatalf("dashboard recent events = %d, want 0", len(dash.RecentEvents()))
}
}
-func TestDashboardActivityRecorderBroadcastsNonMonitoringEvents(t *testing.T) {
+func TestDashboardActivityRecorderBroadcastsClientEvents(t *testing.T) {
base := &stubRecorder{}
dash := dashboard.NewDashboard(nil)
rec := newDashboardActivityRecorder(base, dash)
@@ -56,7 +59,7 @@ func TestDashboardActivityRecorderBroadcastsNonMonitoringEvents(t *testing.T) {
err := rec.Record(activity.Event{
RequestID: "req-1",
Timestamp: time.Now().UTC(),
- Source: "orchestrator",
+ Source: "client",
Method: http.MethodPost,
Path: "/tabs/tab_1/navigate",
AgentID: "agent-1",
diff --git a/internal/server/bridge.go b/internal/server/bridge.go
index aebae6cf..4b8dd180 100644
--- a/internal/server/bridge.go
+++ b/internal/server/bridge.go
@@ -34,6 +34,15 @@ func RunBridgeServer(cfg *config.RuntimeConfig, version string) {
actStore, err := activity.NewRecorder(activity.Config{
Enabled: cfg.Observability.Activity.Enabled,
RetentionDays: cfg.Observability.Activity.RetentionDays,
+ Events: activity.EventSourceConfig{
+ Dashboard: cfg.Observability.Activity.Events.Dashboard,
+ Server: cfg.Observability.Activity.Events.Server,
+ Bridge: cfg.Observability.Activity.Events.Bridge,
+ Orchestrator: cfg.Observability.Activity.Events.Orchestrator,
+ Scheduler: cfg.Observability.Activity.Events.Scheduler,
+ MCP: cfg.Observability.Activity.Events.MCP,
+ Other: cfg.Observability.Activity.Events.Other,
+ },
}, cfg.ActivityStateDir())
if err != nil {
slog.Error("activity store", "err", err)
diff --git a/internal/server/server.go b/internal/server/server.go
index e375e597..a15b3829 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -87,6 +87,15 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
actStore, err := activity.NewRecorder(activity.Config{
Enabled: cfg.Observability.Activity.Enabled,
RetentionDays: cfg.Observability.Activity.RetentionDays,
+ Events: activity.EventSourceConfig{
+ Dashboard: cfg.Observability.Activity.Events.Dashboard,
+ Server: cfg.Observability.Activity.Events.Server,
+ Bridge: cfg.Observability.Activity.Events.Bridge,
+ Orchestrator: cfg.Observability.Activity.Events.Orchestrator,
+ Scheduler: cfg.Observability.Activity.Events.Scheduler,
+ MCP: cfg.Observability.Activity.Events.MCP,
+ Other: cfg.Observability.Activity.Events.Other,
+ },
}, cfg.ActivityStateDir())
if err != nil {
slog.Error("activity store", "err", err)
diff --git a/skills/pinchtab/SKILL.md b/skills/pinchtab/SKILL.md
index cf04ff16..534ff93f 100644
--- a/skills/pinchtab/SKILL.md
+++ b/skills/pinchtab/SKILL.md
@@ -41,8 +41,6 @@ When multiple agents share one PinchTab server, always give each agent a stable
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.
@@ -258,7 +256,16 @@ curl -X POST http://localhost:9868/action \
If the server is exposed beyond localhost, require a token and use a dedicated automation profile. See [TRUST.md](./TRUST.md).
-**Agent sessions**: Instead of sharing the server bearer token, each agent can get its own revocable session token. Set `PINCHTAB_SESSION=ses_...` or send `Authorization: Session ses_...`. Create via `POST /api/sessions` with `{"agentId":"...", "label":"..."}`. Sessions have idle timeout (default 12h) and max lifetime (default 24h). Manage with rotate (`POST /api/sessions/{id}/rotate`) and revoke (`POST /api/sessions/{id}/revoke`).
+**Agent sessions**: Instead of sharing the server bearer token, each agent can get its own revocable session token. Set `PINCHTAB_SESSION=ses_...` or send `Authorization: Session ses_...`. Sessions have idle timeout (default 30m) and max lifetime (default 24h). Use them only in trusted, controlled environments. They are not a multi-tenant isolation boundary, and session-authenticated callers are still intended for operator-controlled automation only.
+
+```bash
+pinchtab session create --agent-id <agent-id> [--label <label>] # Create; prints sessionToken
+pinchtab session list # List all sessions
+pinchtab session info # Show session for current token
+pinchtab session revoke <session-id> # Revoke session
+```
+
+HTTP equivalents: `POST /sessions`, `GET /sessions`, `GET /sessions/me`, `POST /sessions/{id}/revoke`.
## Essential Commands
diff --git a/skills/pinchtab/references/agent-optimization.md b/skills/pinchtab/references/agent-optimization.md
index 1ebda434..3d4d6be3 100644
--- a/skills/pinchtab/references/agent-optimization.md
+++ b/skills/pinchtab/references/agent-optimization.md
@@ -166,7 +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.
+- **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 work stays attributable to the same agent.
- **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.md
index dc03911a..1217a7b3 100644
--- a/skills/pinchtab/references/api.md
+++ b/skills/pinchtab/references/api.md
@@ -6,7 +6,7 @@ Base URL for all examples: `http://localhost:9867`
## 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.
+If an agent is calling the HTTP API directly, include `X-Agent-Id: <agent-id>` on the requests that should stay attributable to that agent.
Example:
@@ -15,15 +15,12 @@ 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
@@ -446,21 +443,10 @@ curl -X POST /fingerprint/rotate -H 'Content-Type: application/json' \
curl /health
```
-## Agent Sessions
-
-```bash
-# Create agent session (requires bearer/cookie auth)
-curl -X POST /api/sessions -d '{"agentId":"my-agent","label":"dev"}'
-
-# List sessions
-curl /api/sessions
-
-# Get current session (requires Session auth)
-curl -H "Authorization: Session ses_..." /api/sessions/me
+## Session Auth
-# Rotate token
-curl -X POST /api/sessions/{id}/rotate
+If the user already gives you an agent session token, send it as:
-# Revoke session
-curl -X POST /api/sessions/{id}/revoke
+```bash
+curl -H "Authorization: Session ses_..." /health
```
diff --git a/skills/pinchtab/references/profiles.md b/skills/pinchtab/references/profiles.md
index 33bd9f0c..15961c3a 100644
--- a/skills/pinchtab/references/profiles.md
+++ b/skills/pinchtab/references/profiles.md
@@ -1,6 +1,6 @@
# Profile Management
-When running `pinchtab`, profiles are managed via the dashboard API on port 9867.
+When running `pinchtab`, profiles are managed via the HTTP API on port 9867.
## List profiles
@@ -102,7 +102,7 @@ Headed mode = real visible Chrome window managed by Pinchtab.
Recommended human + agent flow:
```bash
-# Human starts dashboard and sets up profile
+# Human starts PinchTab and sets up profile
pinchtab
# Agent resolves the profile endpoint
diff --git a/tests/e2e/fixtures/text-fields.html b/tests/e2e/fixtures/text-fields.html
new file mode 100644
index 00000000..9a41cc63
--- /dev/null
+++ b/tests/e2e/fixtures/text-fields.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>E2E Test - Text Fields</title>
+</head>
+<body>
+ <h1>Text Fields</h1>
+ <form>
+ <div>
+ <label for="title">Title</label>
+ <input type="text" id="title" name="title" placeholder="Enter a title">
+ </div>
+ <div>
+ <label for="notes">Notes</label>
+ <textarea id="notes" name="notes" rows="4" cols="40" placeholder="Enter notes"></textarea>
+ </div>
+ </form>
+</body>
+</html>
diff --git a/tests/e2e/scenarios-api/actions-full.sh b/tests/e2e/scenarios-api/actions-full.sh
index 3dece74e..d51922d9 100644
--- a/tests/e2e/scenarios-api/actions-full.sh
+++ b/tests/e2e/scenarios-api/actions-full.sh
@@ -139,6 +139,39 @@ action_human_type_selector "#name" " Jr."
end_test
+# ─────────────────────────────────────────────────────────────────
+start_test "fill: textarea by ref"
+
+navigate_fixture "text-fields.html"
+fresh_snapshot
+
+require_ref "textbox" "Notes" NOTES_REF && {
+ pt_post /action -d "{\"kind\":\"fill\",\"ref\":\"${NOTES_REF}\",\"text\":\"textarea fill test\"}"
+ assert_ok "fill textarea by ref"
+
+ pt_post /evaluate -d '{"expression":"document.querySelector(\"#notes\").value"}'
+ assert_ok "evaluate textarea after fill"
+ assert_json_eq "$RESULT" '.result' 'textarea fill test' "textarea value persisted after fill"
+}
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "type: textarea by ref"
+
+navigate_fixture "text-fields.html"
+fresh_snapshot
+
+require_ref "textbox" "Notes" NOTES_REF && {
+ action_type "$NOTES_REF" "textarea type test"
+
+ pt_post /evaluate -d '{"expression":"document.querySelector(\"#notes\").value"}'
+ assert_ok "evaluate textarea after type"
+ assert_json_eq "$RESULT" '.result' 'textarea type test' "textarea value persisted after type"
+}
+
+end_test
+
# Regression test for GitHub issue #236: press action was typing key names
# as literal text instead of dispatching keyboard events.
diff --git a/tests/e2e/scenarios-api/sessions-full.sh b/tests/e2e/scenarios-api/sessions-full.sh
new file mode 100755
index 00000000..c8fa4cee
--- /dev/null
+++ b/tests/e2e/scenarios-api/sessions-full.sh
@@ -0,0 +1,217 @@
+#!/bin/bash
+# sessions-full.sh — Agent session CRUD and auth scenarios.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../helpers/api.sh"
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /sessions creates a session"
+
+pt_post /sessions '{"agentId":"e2e-agent","label":"e2e-run"}'
+assert_ok "session created"
+assert_result_exists ".id" "has id"
+assert_result_exists ".sessionToken" "has sessionToken"
+assert_result_eq ".agentId" "e2e-agent" "agentId matches"
+assert_result_eq ".label" "e2e-run" "label matches"
+assert_result_eq ".status" "active" "status is active"
+
+SESSION_ID=$(echo "$RESULT" | jq -r '.id')
+SESSION_TOKEN=$(echo "$RESULT" | jq -r '.sessionToken')
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /sessions rejects missing agentId"
+
+pt_post /sessions '{}'
+assert_http_status 400 "missing agentId rejected"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /sessions lists sessions"
+
+pt_get /sessions
+assert_ok "list ok"
+SESSION_COUNT=$(echo "$RESULT" | jq 'length')
+if [ "$SESSION_COUNT" -ge 1 ]; then
+ echo -e " ${GREEN}✓${NC} session list has $SESSION_COUNT entry(s)"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${RED}✗${NC} expected at least 1 session, got $SESSION_COUNT"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /sessions/:id retrieves session by ID"
+
+pt_get "/sessions/${SESSION_ID}"
+assert_ok "get by id ok"
+assert_result_eq ".id" "$SESSION_ID" "id matches"
+assert_result_eq ".agentId" "e2e-agent" "agentId matches"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /sessions/:id returns 404 for unknown id"
+
+pt_get "/sessions/ses_doesnotexist000000000000000"
+assert_http_status 404 "unknown id returns 404"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /sessions/me returns session for session token"
+
+RESULT=$(e2e_curl --token "" -s \
+ -H "Authorization: Session ${SESSION_TOKEN}" \
+ "${E2E_SERVER}/sessions/me")
+HTTP_STATUS=$(e2e_curl --token "" -s -o /dev/null -w "%{http_code}" \
+ -H "Authorization: Session ${SESSION_TOKEN}" \
+ "${E2E_SERVER}/sessions/me")
+
+assert_http_status 200 "/sessions/me with valid session token"
+assert_result_eq ".agentId" "e2e-agent" "agentId matches"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /sessions/me rejects bearer token"
+
+pt_get /sessions/me
+assert_http_status 401 "/sessions/me rejects bearer token"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /sessions/me rejects invalid session token"
+
+RESULT=$(e2e_curl --token "" -s \
+ -H "Authorization: Session ses_invalidtoken000000000000" \
+ "${E2E_SERVER}/sessions/me")
+HTTP_STATUS=$(e2e_curl --token "" -s -o /dev/null -w "%{http_code}" \
+ -H "Authorization: Session ses_invalidtoken000000000000" \
+ "${E2E_SERVER}/sessions/me")
+
+assert_http_status 401 "/sessions/me rejects invalid token"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "session token cannot list sessions"
+
+RESULT=$(e2e_curl --token "" -s \
+ -H "Authorization: Session ${SESSION_TOKEN}" \
+ "${E2E_SERVER}/sessions")
+HTTP_STATUS=$(e2e_curl --token "" -s -o /dev/null -w "%{http_code}" \
+ -H "Authorization: Session ${SESSION_TOKEN}" \
+ "${E2E_SERVER}/sessions")
+
+assert_http_status 403 "session token blocked from listing sessions"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "session token cannot access dashboard admin config"
+
+RESULT=$(e2e_curl --token "" -s \
+ -H "Authorization: Session ${SESSION_TOKEN}" \
+ "${E2E_SERVER}/api/config")
+HTTP_STATUS=$(e2e_curl --token "" -s -o /dev/null -w "%{http_code}" \
+ -H "Authorization: Session ${SESSION_TOKEN}" \
+ "${E2E_SERVER}/api/config")
+
+assert_http_status 403 "session token blocked from /api/config"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /sessions creates a second session for scope checks"
+
+pt_post /sessions '{"agentId":"e2e-agent-2","label":"scope-check"}'
+assert_ok "second session created"
+assert_result_exists ".id" "has second session id"
+assert_result_exists ".sessionToken" "has second session token"
+
+SESSION_ID_2=$(echo "$RESULT" | jq -r '.id')
+SESSION_TOKEN_2=$(echo "$RESULT" | jq -r '.sessionToken')
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "session token cannot revoke another session"
+
+RESULT=$(e2e_curl --token "" -s -X POST \
+ -H "Authorization: Session ${SESSION_TOKEN}" \
+ "${E2E_SERVER}/sessions/${SESSION_ID_2}/revoke")
+HTTP_STATUS=$(e2e_curl --token "" -s -o /dev/null -w "%{http_code}" -X POST \
+ -H "Authorization: Session ${SESSION_TOKEN}" \
+ "${E2E_SERVER}/sessions/${SESSION_ID_2}/revoke")
+
+assert_http_status 403 "session token blocked from revoking another session"
+
+OTHER_STATUS=$(e2e_curl --token "" -s -o /dev/null -w "%{http_code}" \
+ -H "Authorization: Session ${SESSION_TOKEN_2}" \
+ "${E2E_SERVER}/sessions/me")
+if [ "$OTHER_STATUS" = "200" ]; then
+ echo -e " ${GREEN}✓${NC} other session remains active after forbidden revoke"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${RED}✗${NC} other session should remain active (got $OTHER_STATUS)"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "session token can revoke its own session"
+
+response=$(e2e_curl --token "" -s -w "\n%{http_code}" -X POST \
+ -H "Authorization: Session ${SESSION_TOKEN}" \
+ "${E2E_SERVER}/sessions/${SESSION_ID}/revoke")
+split_pinchtab_response "$response"
+
+assert_http_status 200 "self-revoke ok"
+
+REVOKED_STATUS=$(e2e_curl --token "" -s -o /dev/null -w "%{http_code}" \
+ -H "Authorization: Session ${SESSION_TOKEN}" \
+ "${E2E_SERVER}/sessions/me")
+if [ "$REVOKED_STATUS" = "401" ]; then
+ echo -e " ${GREEN}✓${NC} token rejected after revoke (401)"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${RED}✗${NC} token should be invalid after revoke (got $REVOKED_STATUS)"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /sessions/:id/revoke returns 404 for unknown id"
+
+pt_post "/sessions/ses_doesnotexist000000000000000/revoke" '{}'
+assert_http_status 404 "revoke unknown id returns 404"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "session token authenticates browser actions"
+
+pt_post /sessions '{"agentId":"e2e-action-agent"}'
+assert_ok "session created for action test"
+ACTION_TOKEN=$(echo "$RESULT" | jq -r '.sessionToken')
+
+ACTION_STATUS=$(e2e_curl --token "" -s -o /dev/null -w "%{http_code}" \
+ -H "Authorization: Session ${ACTION_TOKEN}" \
+ "${E2E_SERVER}/health")
+if [ "$ACTION_STATUS" = "200" ]; then
+ echo -e " ${GREEN}✓${NC} session token authenticates /health"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${RED}✗${NC} session token should authenticate /health (got $ACTION_STATUS)"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+end_test
diff --git a/tests/e2e/scenarios-cli/sessions-basic.sh b/tests/e2e/scenarios-cli/sessions-basic.sh
new file mode 100755
index 00000000..ad49fce7
--- /dev/null
+++ b/tests/e2e/scenarios-cli/sessions-basic.sh
@@ -0,0 +1,60 @@
+#!/bin/bash
+# sessions-basic.sh — CLI agent session happy-path scenarios.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../helpers/cli.sh"
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab session create"
+
+pt_ok session create --agent-id "e2e-agent" --label "e2e-test"
+assert_output_contains "sessionToken" "output contains sessionToken"
+assert_output_contains "e2e-agent" "output contains agentId"
+assert_output_contains "active" "output contains status active"
+
+SESSION_ID=$(echo "$PT_OUT" | jq -r '.id')
+SESSION_TOKEN=$(echo "$PT_OUT" | jq -r '.sessionToken')
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab session create without --agent-id fails"
+
+pt_fail session create
+if echo "$PT_ERR" | grep -q "agent-id"; then
+ echo -e " ${GREEN}✓${NC} error mentions --agent-id"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${RED}✗${NC} error mentions --agent-id (stderr: $PT_ERR)"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab session list"
+
+pt_ok session list
+assert_output_contains "$SESSION_ID" "list includes created session"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab session info with session token"
+
+PINCHTAB_SESSION="$SESSION_TOKEN" pt_ok session info
+assert_output_contains "e2e-agent" "info shows agentId"
+assert_output_contains "active" "info shows active status"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab session revoke"
+
+pt_ok session revoke "$SESSION_ID"
+assert_output_contains "ok" "revoke returns ok status"
+
+# Subsequent info with revoked token should fail
+PINCHTAB_SESSION="$SESSION_TOKEN" pt_fail session info
+
+end_test