High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: auto-handoff on failure with dashboard signals
Luigi Agosti78c7a1b1175a
diff --git a/cmd/pinchtab/cmd_cli_browser_nav.go b/cmd/pinchtab/cmd_cli_browser_nav.goindex db8e8eef..cab2ff85 100644--- a/cmd/pinchtab/cmd_cli_browser_nav.go+++ b/cmd/pinchtab/cmd_cli_browser_nav.go@@ -105,38 +105,43 @@ var tabCloseCmd = &cobra.Command{}var tabHandoffCmd = &cobra.Command{- Use: "handoff <id>",+ Use: "handoff [id]",Short: "Pause tab automation for human handoff",- Long: "Mark a tab as paused_handoff so action routes block until resumed or timeout expires.",- Args: cobra.ExactArgs(1),+ Long: "Mark a tab as paused_handoff so action routes block until resumed or timeout expires. Defaults to the current tab (PINCHTAB_TAB or state file).",+ Args: cobra.MaximumNArgs(1),Run: func(cmd *cobra.Command, args []string) {reason, _ := cmd.Flags().GetString("reason")timeoutMS, _ := cmd.Flags().GetInt("timeout-ms")+ tabID := resolveTabArg(args)runCLI(func(rt cliRuntime) {- browseractions.TabHandoff(rt.client, rt.base, rt.token, args[0], reason, timeoutMS, cmd)+ browseractions.TabHandoff(rt.client, rt.base, rt.token, tabID, reason, timeoutMS, cmd)})},}var tabResumeCmd = &cobra.Command{- Use: "resume <id>",+ Use: "resume [id]",Short: "Resume a paused_handoff tab",- Args: cobra.ExactArgs(1),+ Long: "Resume automation on a paused tab. Defaults to the current tab (PINCHTAB_TAB or state file).",+ Args: cobra.MaximumNArgs(1),Run: func(cmd *cobra.Command, args []string) {status, _ := cmd.Flags().GetString("status")+ tabID := resolveTabArg(args)runCLI(func(rt cliRuntime) {- browseractions.TabResume(rt.client, rt.base, rt.token, args[0], status, cmd)+ browseractions.TabResume(rt.client, rt.base, rt.token, tabID, status, cmd)})},}var tabHandoffStatusCmd = &cobra.Command{- Use: "handoff-status <id>",+ Use: "handoff-status [id]",Short: "Show handoff status for a tab",- Args: cobra.ExactArgs(1),+ Long: "Show handoff status. Defaults to the current tab (PINCHTAB_TAB or state file).",+ Args: cobra.MaximumNArgs(1),Run: func(cmd *cobra.Command, args []string) {+ tabID := resolveTabArg(args)runCLI(func(rt cliRuntime) {- browseractions.TabHandoffStatus(rt.client, rt.base, rt.token, args[0], cmd)+ browseractions.TabHandoffStatus(rt.client, rt.base, rt.token, tabID, cmd)})},}diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.goindex f30fd57e..88e74ffa 100644--- a/cmd/pinchtab/cmd_cli_register.go+++ b/cmd/pinchtab/cmd_cli_register.go@@ -57,8 +57,17 @@ func registerBrowserCommands() {cacheCmd,storageCmd,stateCmd,+ tabHandoffCmd,+ tabResumeCmd,+ tabHandoffStatusCmd,)+ // Register handoff/resume/handoff-status as subcommands of `tab` too so+ // `pinchtab tab handoff <id>` keeps working alongside the top-level+ // `pinchtab handoff`. The commands carry GroupID="browser" (set by+ // setCommandGroup above) — add the same group to tabsCmd so cobra+ // accepts them without panicking.+ tabsCmd.AddGroup(&cobra.Group{ID: "browser", Title: "Browser"})tabsCmd.AddCommand(tabNewCmd, tabCloseCmd, tabHandoffCmd, tabResumeCmd, tabHandoffStatusCmd)clipboardCmd.AddCommand(clipboardReadCmd, clipboardWriteCmd, clipboardCopyCmd, clipboardPasteCmd)keyboardCmd.AddCommand(keyboardTypeCmd, keyboardInsertTextCmd)@@ -109,6 +118,9 @@ func registerBrowserCommands() {cacheCmd,storageCmd,stateCmd,+ tabHandoffCmd,+ tabResumeCmd,+ tabHandoffStatusCmd,)}@@ -379,6 +391,18 @@ func addRootCommands(cmds ...*cobra.Command) {//// Explicit --tab still wins (cobra flag precedence). If neither env var nor// state file is set, the server picks the active tab as before.+// resolveTabArg returns the tab ID from args[0] when present, otherwise falls+// back to $PINCHTAB_TAB then the persisted state file written by `nav`.+func resolveTabArg(args []string) string {+ if len(args) > 0 && args[0] != "" {+ return args[0]+ }+ if env := os.Getenv("PINCHTAB_TAB"); env != "" {+ return env+ }+ return readTabStateFile()+}+func addTabFlag(cmds ...*cobra.Command) {defaultTab := os.Getenv("PINCHTAB_TAB")if defaultTab == "" {diff --git a/cmd/pinchtab/cmd_cli_test.go b/cmd/pinchtab/cmd_cli_test.goindex f88b50f5..5c003b91 100644--- a/cmd/pinchtab/cmd_cli_test.go+++ b/cmd/pinchtab/cmd_cli_test.go@@ -66,11 +66,17 @@ func TestDragCommandRegistered(t *testing.T) {}func TestTabHandoffCommandsRegistered(t *testing.T) {+ for _, name := range []string{"handoff [id]", "resume [id]", "handoff-status [id]"} {+ if findCommand(rootCmd, name) == nil {+ t.Fatalf("expected top-level command %q to be registered", name)+ }+ }+tabCmd := findCommand(rootCmd, "tab [id]")if tabCmd == nil {t.Fatal("expected tab command to be registered")}- for _, name := range []string{"handoff", "resume", "handoff-status"} {+ for _, name := range []string{"handoff [id]", "resume [id]", "handoff-status [id]"} {if findCommand(tabCmd, name) == nil {t.Fatalf("expected tab subcommand %q to be registered", name)}diff --git a/cmd/pinchtab/cmd_server.go b/cmd/pinchtab/cmd_server.goindex 756578be..fff8b76b 100644--- a/cmd/pinchtab/cmd_server.go+++ b/cmd/pinchtab/cmd_server.go@@ -1,6 +1,11 @@package mainimport (+ "fmt"+ "os"++ "github.com/pinchtab/pinchtab/internal/cli"+ "github.com/pinchtab/pinchtab/internal/config/workflow""github.com/pinchtab/pinchtab/internal/server""github.com/spf13/cobra")@@ -10,7 +15,17 @@ var serverCmd = &cobra.Command{Short: "Start server",Run: func(cmd *cobra.Command, args []string) {maybeRunWizard()++ if yolo, _ := cmd.Flags().GetBool("yolo"); yolo {+ if _, _, _, err := workflow.ApplyGuardsDownPreset(); err != nil {+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("--yolo: %v", err)))+ os.Exit(1)+ }+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.WarningStyle, "YOLO mode: guards down"))+ }+cfg := loadConfig()+if headed, _ := cmd.Flags().GetBool("headed"); headed {cfg.Headless = falsecfg.HeadlessSet = true@@ -24,7 +39,8 @@ var serverCmd = &cobra.Command{func init() {serverCmd.GroupID = "primary"- serverCmd.Flags().StringArray("extension", nil, "Load browser extension (repeatable)")- serverCmd.Flags().Bool("headed", false, "Start default instance in headed mode")+ serverCmd.Flags().StringArrayP("extension", "e", nil, "Load browser extension (repeatable)")+ serverCmd.Flags().BoolP("headed", "H", false, "Start default instance in headed mode")+ serverCmd.Flags().BoolP("yolo", "y", false, "Apply guards down preset (enables evaluate, macro, download)")rootCmd.AddCommand(serverCmd)}diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsxindex df497bca..f44ee8c7 100644--- a/dashboard/src/App.tsx+++ b/dashboard/src/App.tsx@@ -8,7 +8,7 @@ import {useNavigate,} from "react-router-dom";import { ActivityPage, AgentsPage } from "./activities";-import { NavBar } from "./components/molecules";+import { HandoffNotifications, NavBar } from "./components/molecules";import { LoginPage, MonitoringPage, ProfilesPage, SettingsPage } from "./pages";import * as api from "./services/api";import {@@ -252,6 +252,7 @@ function AppContent() {{INSECURE_DASHBOARD_TRANSPORT_WARNING}</div>)}+ <HandoffNotifications /><main className="dashboard-grid flex-1 overflow-hidden"><Routes><Routediff --git a/dashboard/src/activities/ActivityItemLine.tsx b/dashboard/src/activities/ActivityItemLine.tsxindex 1f574085..dc7ba262 100644--- a/dashboard/src/activities/ActivityItemLine.tsx+++ b/dashboard/src/activities/ActivityItemLine.tsx@@ -8,6 +8,8 @@ import {IconPointer,IconScreenShare,} from "../components/atoms/Icon";+import { useState } from "react";+import { resumeTab } from "../services/api";import { activityStatusVariant } from "./helpers";import type { ActivityFilters, DashboardActivityEvent } from "./types";import CopyIdPill from "./CopyIdPill";@@ -106,6 +108,7 @@ interface Props {showTab?: boolean;copyTabId?: boolean;sessionLabel?: string;+ inHandoff?: boolean;onFilterChange?: (key: keyof ActivityFilters, value: string) => void;}@@ -114,9 +117,25 @@ export default function ActivityItemLine({showTab = true,copyTabId = false,sessionLabel,+ inHandoff = false,onFilterChange,}: Props) {const variant = activityStatusVariant(event.status);+ const [resuming, setResuming] = useState(false);+ const [resumeError, setResumeError] = useState("");++ const showResumeButton = inHandoff && Boolean(event.tabId);+ const handleResume = async () => {+ if (!event.tabId || resuming) return;+ setResuming(true);+ setResumeError("");+ try {+ await resumeTab(event.tabId);+ } catch (err) {+ setResumeError(err instanceof Error ? err.message : "Resume failed");+ setResuming(false);+ }+ };return (<div className="flex items-center gap-2.5 px-4 py-2 text-sm transition-colors hover:bg-white/2">@@ -128,10 +147,32 @@ export default function ActivityItemLine({{formatTime(event.timestamp)}</span>+ {inHandoff && (+ <span+ aria-label="tab paused for human handoff"+ title="Tab is paused for human handoff"+ className="inline-block h-2 w-2 shrink-0 rounded-full bg-red-500 ring-2 ring-bg-surface"+ />+ )}+<span className="min-w-0 flex-1 truncate text-text-primary">{eventDescription(event)}</span>+ {showResumeButton && (+ <button+ type="button"+ onClick={handleResume}+ disabled={resuming}+ title={+ resumeError || "Resume automation after manual challenge solve"+ }+ className="shrink-0 rounded-sm border border-warning/40 bg-warning/10 px-2 py-0.5 text-[0.68rem] text-warning transition-colors hover:bg-warning/20 disabled:opacity-50"+ >+ {resuming ? "Resuming…" : "Resolve challenge"}+ </button>+ )}+{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}diff --git a/dashboard/src/activities/AgentActivityWorkspace.tsx b/dashboard/src/activities/AgentActivityWorkspace.tsxindex 1b05effa..826bcd9f 100644--- a/dashboard/src/activities/AgentActivityWorkspace.tsx+++ b/dashboard/src/activities/AgentActivityWorkspace.tsx@@ -10,6 +10,7 @@ import {defaultActivityFilters,sameActivityFilters,} from "./helpers";+import { computeHandoffTabs, deriveHandoffIndex } from "./handoffState";import type { ActivityFilters, DashboardActivityEvent } from "./types";type WorkspaceTab = "agents" | "activities";@@ -185,8 +186,14 @@ export default function AgentActivityWorkspace({useAgentEventStore = false,clearToInitialFilters = false,}: Props) {- const { instances, profiles, agents, agentEventsById, hydrateAgentEvents } =- useAppStore();+ const {+ instances,+ profiles,+ agents,+ agentEventsById,+ hydrateAgentEvents,+ events: liveEvents,+ } = useAppStore();const normalizedHiddenSources = useMemo(() => [...hiddenSources],[hiddenSources],@@ -398,6 +405,26 @@ export default function AgentActivityWorkspace({return Array.from(ids).sort();}, [catalogEvents]);+ // Handoff detection runs against the union of polled catalog events and the+ // live SSE-driven store events so the sidebar dots update in real time, not+ // only when filters change and catalogEvents re-fetches.+ const handoffEventPool = useMemo(() => {+ const combined: DashboardActivityEvent[] = [...catalogEvents];+ for (const live of liveEvents) {+ combined.push(toDashboardActivityEvent(live));+ }+ return combined;+ }, [catalogEvents, liveEvents]);++ const handoffTabs = useMemo(+ () => computeHandoffTabs(handoffEventPool),+ [handoffEventPool],+ );+ const { sessionsWithHandoff, agentsWithHandoff } = useMemo(+ () => deriveHandoffIndex(handoffEventPool, handoffTabs),+ [handoffEventPool, handoffTabs],+ );+const visibleEvents = useMemo(() =>catalogEvents.filter((event) =>@@ -755,6 +782,8 @@ export default function AgentActivityWorkspace({activeAgentId={filters.agentId}filters={filters}sessions={derivedSessions}+ sessionsWithHandoff={sessionsWithHandoff}+ agentsWithHandoff={agentsWithHandoff}showAllAgentsOption={showAllAgentsOption}showAgentFilter={showAgentFilter}profiles={profiles}@@ -798,6 +827,8 @@ export default function AgentActivityWorkspace({error={error}loading={activityLoading || agentLoading}copyTabId={copyTabId}+ handoffTabs={handoffTabs}+ activeSessionId={filters.sessionId}onFilterChange={updateFilter}/></div>diff --git a/dashboard/src/activities/AgentStreamPanel.tsx b/dashboard/src/activities/AgentStreamPanel.tsxindex 4b7a18ab..826e3733 100644--- a/dashboard/src/activities/AgentStreamPanel.tsx+++ b/dashboard/src/activities/AgentStreamPanel.tsx@@ -2,6 +2,7 @@ import { useLayoutEffect, useRef } from "react";import { EmptyState } from "../components/atoms";import type { Session } from "../services/api";import ActivityItemLine from "./ActivityItemLine";+import { isHandoffEvent } from "./handoffState";import type { ActivityFilters, DashboardActivityEvent } from "./types";interface AgentStreamPanelProps {@@ -10,6 +11,8 @@ interface AgentStreamPanelProps {error: string;loading: boolean;copyTabId?: boolean;+ handoffTabs?: Set<string>;+ activeSessionId?: string;onFilterChange: (key: keyof ActivityFilters, value: string) => void;}@@ -19,6 +22,8 @@ export default function AgentStreamPanel({error,loading,copyTabId = false,+ handoffTabs,+ activeSessionId,onFilterChange,}: AgentStreamPanelProps) {const sessionLabels = new Map(@@ -76,20 +81,53 @@ export default function AgentStreamPanel({/>) : (<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"+ {(() => {+ // Find the most recent handoff event per tab (by timestamp desc)+ const mostRecentHandoffByTab = new Map<string, string>();+ for (let i = events.length - 1; i >= 0; i--) {+ const ev = events[i];+ if (+ isHandoffEvent(ev) &&+ ev.tabId &&+ handoffTabs?.has(ev.tabId) &&+ !mostRecentHandoffByTab.has(ev.tabId)+ ) {+ mostRecentHandoffByTab.set(+ ev.tabId,+ ev.requestId || ev.timestamp,+ );}- onFilterChange={onFilterChange}- />- ))}+ }++ return events.map((event, index) => {+ const suppressSessionLabel =+ Boolean(activeSessionId) &&+ event.sessionId === activeSessionId;+ // Only show badge on the MOST RECENT handoff event per tab+ const eventKey = event.requestId || event.timestamp;+ const inHandoff =+ isHandoffEvent(event) &&+ Boolean(event.tabId && handoffTabs?.has(event.tabId)) &&+ mostRecentHandoffByTab.get(event.tabId!) === eventKey;+ return (+ <ActivityItemLine+ key={`${eventKey}-${index}`}+ event={event}+ showTab+ copyTabId={copyTabId}+ sessionLabel={+ suppressSessionLabel+ ? undefined+ : event.sessionId+ ? sessionLabels.get(event.sessionId)+ : "anonymous"+ }+ inHandoff={inHandoff}+ onFilterChange={onFilterChange}+ />+ );+ });+ })()}</div>)}</div>diff --git a/dashboard/src/activities/AgentWorkspaceSidebar.tsx b/dashboard/src/activities/AgentWorkspaceSidebar.tsxindex c855140e..e0ec0e8b 100644--- a/dashboard/src/activities/AgentWorkspaceSidebar.tsx+++ b/dashboard/src/activities/AgentWorkspaceSidebar.tsx@@ -16,6 +16,8 @@ interface AgentWorkspaceSidebarProps {activeAgentId: string;filters: ActivityFilters;sessions: Session[];+ sessionsWithHandoff?: Set<string>;+ agentsWithHandoff?: Set<string>;showAllAgentsOption?: boolean;showAgentFilter?: boolean;profiles: Profile[];@@ -39,6 +41,8 @@ export default function AgentWorkspaceSidebar({activeAgentId,filters,sessions,+ sessionsWithHandoff,+ agentsWithHandoff,showAllAgentsOption = true,showAgentFilter = true,profiles,@@ -140,6 +144,8 @@ export default function AgentWorkspaceSidebar({selected={activeAgentId === agent.id}sessions={sessionsByAgent.get(agent.id) || []}activeSessionId={filters.sessionId}+ hasHandoff={agentsWithHandoff?.has(agent.id) ?? false}+ sessionsWithHandoff={sessionsWithHandoff}onClick={() => onSelectAgent(agent.id)}onSelectSession={onSelectSession}/>diff --git a/dashboard/src/activities/handoffState.ts b/dashboard/src/activities/handoffState.tsnew file mode 100644index 00000000..ed4901d6--- /dev/null+++ b/dashboard/src/activities/handoffState.ts@@ -0,0 +1,73 @@+import type { DashboardActivityEvent } from "./types";++// Returns true for POST {tab}/handoff events (the pause action).+export function isHandoffEvent(event: DashboardActivityEvent): boolean {+ return (+ event.method === "POST" &&+ event.path.endsWith("/handoff") &&+ Boolean(event.tabId)+ );+}++// Returns true for POST {tab}/resume events (the unpause action).+export function isResumeEvent(event: DashboardActivityEvent): boolean {+ return (+ event.method === "POST" &&+ event.path.endsWith("/resume") &&+ Boolean(event.tabId)+ );+}++// computeHandoffTabs walks events in chronological order and returns the set+// of tabIds whose most recent handoff/resume signal is a pause. A tab goes+// into the set on POST .../handoff and leaves it on POST .../resume.+export function computeHandoffTabs(+ events: DashboardActivityEvent[],+): Set<string> {+ const paused = new Set<string>();++ const sorted = [...events].sort(+ (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),+ );++ for (const event of sorted) {+ if (!event.tabId) continue;+ if (isHandoffEvent(event) && event.status >= 200 && event.status < 300) {+ paused.add(event.tabId);+ } else if (+ isResumeEvent(event) &&+ event.status >= 200 &&+ event.status < 300+ ) {+ paused.delete(event.tabId);+ }+ }++ return paused;+}++// deriveSessionAgentIndex builds two sets:+// - sessionsWithHandoff: sessions that touched any currently-paused tab+// - agentsWithHandoff: agents that touched any currently-paused tab+//+// We look across all events (not just handoff/resume) so a session is flagged+// as long as it produced traffic on a tab that is now in handoff.+export function deriveHandoffIndex(+ events: DashboardActivityEvent[],+ handoffTabs: Set<string>,+): { sessionsWithHandoff: Set<string>; agentsWithHandoff: Set<string> } {+ const sessionsWithHandoff = new Set<string>();+ const agentsWithHandoff = new Set<string>();++ if (handoffTabs.size === 0) {+ return { sessionsWithHandoff, agentsWithHandoff };+ }++ for (const event of events) {+ if (!event.tabId || !handoffTabs.has(event.tabId)) continue;+ if (event.sessionId) sessionsWithHandoff.add(event.sessionId);+ if (event.agentId) agentsWithHandoff.add(event.agentId);+ }++ return { sessionsWithHandoff, agentsWithHandoff };+}diff --git a/dashboard/src/components/molecules/AgentItem.tsx b/dashboard/src/components/molecules/AgentItem.tsxindex 36a7ba65..55c7a4be 100644--- a/dashboard/src/components/molecules/AgentItem.tsx+++ b/dashboard/src/components/molecules/AgentItem.tsx@@ -7,10 +7,21 @@ interface Props {selected: boolean;sessions: Session[];activeSessionId?: string;+ hasHandoff?: boolean;+ sessionsWithHandoff?: Set<string>;onClick: () => void;onSelectSession: (sessionId: string) => void;}+function HandoffDot() {+ return (+ <span+ aria-label="tab paused for human handoff"+ className="inline-block h-2 w-2 shrink-0 rounded-full bg-red-500 ring-2 ring-bg-surface"+ />+ );+}+function timeAgo(date: string): string {const diff = Date.now() - new Date(date).getTime();const secs = Math.floor(diff / 1000);@@ -40,6 +51,8 @@ export default function AgentItem({selected,sessions,activeSessionId,+ hasHandoff = false,+ sessionsWithHandoff,onClick,onSelectSession,}: Props) {@@ -56,10 +69,11 @@ export default function AgentItem({<div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-primary"><IconRobot /></div>- <div className="min-w-0 flex-1">+ <div className="min-w-0 flex-1 flex items-center gap-2"><span className="truncate text-sm font-medium">{agent.name || agent.id}</span>+ {hasHandoff && <HandoffDot />}</div><span className="dashboard-mono text-[0.65rem] text-text-muted">{timeAgo(agent.lastActivity || agent.connectedAt)}@@ -70,6 +84,8 @@ export default function AgentItem({<div className="ml-5 border-l border-border-subtle">{sessions.map((session) => {const isActive = activeSessionId === session.id;+ const sessionHasHandoff =+ sessionsWithHandoff?.has(session.id) ?? false;return (<buttonkey={session.id}@@ -84,6 +100,7 @@ export default function AgentItem({<span className="min-w-0 flex-1 truncate text-xs font-medium">{sessionDisplayName(session)}</span>+ {sessionHasHandoff && <HandoffDot />}</button>);})}diff --git a/dashboard/src/components/molecules/HandoffNotifications.tsx b/dashboard/src/components/molecules/HandoffNotifications.tsxnew file mode 100644index 00000000..fb91db2d--- /dev/null+++ b/dashboard/src/components/molecules/HandoffNotifications.tsx@@ -0,0 +1,68 @@+import { useAppStore } from "../../stores/useAppStore";+import { resumeTab } from "../../services/api";++export default function HandoffNotifications() {+ const notifications = useAppStore((state) => state.handoffNotifications);+ const dismiss = useAppStore((state) => state.dismissHandoffNotification);++ if (notifications.length === 0) {+ return null;+ }++ const handleResume = async (tabId: string) => {+ try {+ await resumeTab(tabId);+ dismiss(tabId);+ } catch (err) {+ console.error("Failed to resume tab", err);+ }+ };++ return (+ <div className="fixed bottom-4 right-4 z-50 flex w-96 max-w-full flex-col gap-2">+ {notifications.map((n) => (+ <div+ key={n.tabId}+ className="rounded-sm border border-warning/50 bg-warning/10 p-3 text-sm shadow-lg"+ >+ <div className="mb-1 flex items-start justify-between gap-2">+ <div className="font-semibold text-warning">+ Human intervention required+ </div>+ <button+ type="button"+ onClick={() => dismiss(n.tabId)}+ className="text-text-muted hover:text-text-primary"+ aria-label="Dismiss notification"+ >+ ×+ </button>+ </div>+ <div className="mb-1 text-text-primary">+ <code className="text-xs">{n.tabId}</code>+ {n.title && <span className="ml-2 text-text-muted">{n.title}</span>}+ </div>+ <div className="mb-2 text-text-secondary">+ <span className="text-text-muted">Reason:</span>{" "}+ <code className="text-xs">{n.reason}</code>+ {n.source && (+ <span className="ml-2 text-text-muted">via {n.source}</span>+ )}+ </div>+ {n.hint && (+ <div className="mb-2 text-xs text-text-muted">{n.hint}</div>+ )}+ <div className="flex justify-end gap-2">+ <button+ type="button"+ onClick={() => handleResume(n.tabId)}+ className="rounded-sm border border-border-subtle px-3 py-1 text-xs text-text-primary transition-all duration-150 hover:border-primary/30 hover:bg-bg-elevated"+ >+ Resume+ </button>+ </div>+ </div>+ ))}+ </div>+ );+}diff --git a/dashboard/src/components/molecules/index.ts b/dashboard/src/components/molecules/index.tsindex f5b64001..ff3d8fdb 100644--- a/dashboard/src/components/molecules/index.ts+++ b/dashboard/src/components/molecules/index.ts@@ -11,3 +11,4 @@ export { default as AgentItem } from "./AgentItem";export { default as ActivityLine } from "../../activities/ActivityLine";export { default as TabsChart } from "./TabsChart";export { default as ServerSummary } from "./ServerSummary";+export { default as HandoffNotifications } from "./HandoffNotifications";diff --git a/dashboard/src/pages/MonitoringPage.tsx b/dashboard/src/pages/MonitoringPage.tsxindex 3593d12c..aa99c796 100644--- a/dashboard/src/pages/MonitoringPage.tsx+++ b/dashboard/src/pages/MonitoringPage.tsx@@ -20,7 +20,13 @@ export default function MonitoringPage() {selectedMonitoringInstanceId,setSelectedMonitoringInstanceId,setInstances,+ handoffNotifications,} = useAppStore();++ const handoffTabs = useMemo(+ () => new Set(handoffNotifications.map((n) => n.tabId)),+ [handoffNotifications],+ );const navigate = useNavigate();const selectedId = selectedMonitoringInstanceId;const setSelectedId = setSelectedMonitoringInstanceId;@@ -308,6 +314,7 @@ export default function MonitoringPage() {<InstanceTabsPaneltabs={selectedTabs}instanceId={selectedId || undefined}+ handoffTabs={handoffTabs}/>) : (<div className="flex flex-1 items-center justify-center px-6">diff --git a/dashboard/src/profiles/ProfileDetailsPanel.tsx b/dashboard/src/profiles/ProfileDetailsPanel.tsxindex 1d3a7b0b..1b821dc3 100644--- a/dashboard/src/profiles/ProfileDetailsPanel.tsx+++ b/dashboard/src/profiles/ProfileDetailsPanel.tsx@@ -1,4 +1,4 @@-import { useState, useEffect, useCallback } from "react";+import { useState, useEffect, useCallback, useMemo } from "react";import InstanceLogsPanel from "./InstanceLogsPanel";import ProfileMetaInfoPanel from "./ProfileMetaInfoPanel";import ProfileBasicInfoPanel from "./ProfileBasicInfoPanel";@@ -8,6 +8,7 @@ import { InstanceTabsPanel } from "../tabs";import { TabsLayout, EmptyView } from "../components/molecules";import type { Profile, Instance, InstanceTab } from "../generated/types";import * as api from "../services/api";+import { useAppStore } from "../stores/useAppStore";interface Props {profile: Profile | null;@@ -31,6 +32,12 @@ export default function ProfileDetailsPanel({const [activeTab, setActiveTab] = useState<TabId>("profile");const [tabs, setTabs] = useState<InstanceTab[]>([]);const [formValues, setFormValues] = useState({ name: "", useWhen: "" });+ const { handoffNotifications } = useAppStore();++ const handoffTabs = useMemo(+ () => new Set(handoffNotifications.map((n) => n.tabId)),+ [handoffNotifications],+ );const isRunning = instance?.status === "running";@@ -137,6 +144,7 @@ export default function ProfileDetailsPanel({<InstanceTabsPaneltabs={tabs}instanceId={instance?.id}+ handoffTabs={handoffTabs}emptyMessage={isRunning ? "No tabs open." : "Instance not running."}diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 084ea451..9ab7f503 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -266,6 +266,17 @@ export async function closeTab(tabId: string): Promise<void> {await request(`/tabs/${encodeURIComponent(tabId)}/close`, { method: "POST" });}+export async function resumeTab(+ tabId: string,+ status = "human_completed",+): Promise<void> {+ await request(`/tabs/${encodeURIComponent(tabId)}/resume`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ status }),+ });+}+export interface ConsoleLogEntry {timestamp: string;level: string;@@ -507,9 +518,27 @@ export async function saveBackendConfig(}// SSE Events — endpoint is /api/events+export interface HandoffPayload {+ tabId?: string;+ status?: string;+ reason?: string;+ source?: string;+ hint?: string;+ requestedAt?: string;+ resumedAt?: string;+ timeoutMs?: number;+ url?: string;+ title?: string;+}+export interface SystemEvent {- type: "instance.started" | "instance.stopped" | "instance.error";- instance?: Instance;+ type:+ | "instance.started"+ | "instance.stopped"+ | "instance.error"+ | "tab.handoff"+ | "tab.resume";+ instance?: Instance | HandoffPayload;}export function activityEventSource(event: ActivityEvent): string {diff --git a/dashboard/src/services/dashboardRealtime.ts b/dashboard/src/services/dashboardRealtime.tsindex 42aa9d83..c2115759 100644--- a/dashboard/src/services/dashboardRealtime.ts+++ b/dashboard/src/services/dashboardRealtime.ts@@ -66,7 +66,37 @@ function startDashboardRealtime(includeMemory: boolean) {state.setAgents(mergeAgents(state.agents, agents));},onSystem: (event) => {- console.log("System event:", event);+ const state = useAppStore.getState();+ if (event.type === "tab.handoff") {+ const payload = (event.instance ?? {}) as Record<string, unknown>;+ const tabId =+ typeof payload.tabId === "string" ? payload.tabId : null;+ if (!tabId) {+ return;+ }+ state.addHandoffNotification({+ tabId,+ reason:+ typeof payload.reason === "string"+ ? payload.reason+ : "manual_handoff",+ hint: typeof payload.hint === "string" ? payload.hint : undefined,+ source:+ typeof payload.source === "string" ? payload.source : undefined,+ url: typeof payload.url === "string" ? payload.url : undefined,+ title:+ typeof payload.title === "string" ? payload.title : undefined,+ receivedAt: Date.now(),+ });+ return;+ }+ if (event.type === "tab.resume") {+ const payload = (event.instance ?? {}) as Record<string, unknown>;+ if (typeof payload.tabId === "string") {+ state.dismissHandoffNotification(payload.tabId);+ }+ return;+ }},onActivity: (event) => {if (!isClientActivityEvent(event)) {diff --git a/dashboard/src/stores/useAppStore.ts b/dashboard/src/stores/useAppStore.tsindex 4d4e71b0..84a11f57 100644--- a/dashboard/src/stores/useAppStore.ts+++ b/dashboard/src/stores/useAppStore.ts@@ -27,6 +27,16 @@ export interface ServerDataPoint {rateBucketHosts: number;}+export interface HandoffNotification {+ tabId: string;+ reason: string;+ hint?: string;+ source?: string;+ url?: string;+ title?: string;+ receivedAt: number;+}+interface AppState {// Profilesprofiles: Profile[];@@ -82,6 +92,12 @@ interface AppState {serverInfo: DashboardServerInfo | null;setServerInfo: (info: DashboardServerInfo | null) => void;+ // Handoff notifications (tabs paused for human-in-the-loop)+ handoffNotifications: HandoffNotification[];+ addHandoffNotification: (notification: HandoffNotification) => void;+ dismissHandoffNotification: (tabId: string) => void;+ clearHandoffNotifications: () => void;+// Monitoring UImonitoringSidebarCollapsed: boolean;setMonitoringSidebarCollapsed: (collapsed: boolean) => void;@@ -419,6 +435,23 @@ export const useAppStore = create<AppState>((set) => ({serverInfo: null,setServerInfo: (serverInfo) => set({ serverInfo }),+ // Handoff notifications+ handoffNotifications: [],+ addHandoffNotification: (notification) =>+ set((state) => {+ const filtered = state.handoffNotifications.filter(+ (n) => n.tabId !== notification.tabId,+ );+ return { handoffNotifications: [...filtered, notification] };+ }),+ dismissHandoffNotification: (tabId) =>+ set((state) => ({+ handoffNotifications: state.handoffNotifications.filter(+ (n) => n.tabId !== tabId,+ ),+ })),+ clearHandoffNotifications: () => set({ handoffNotifications: [] }),+// Monitoring UImonitoringSidebarCollapsed: true,setMonitoringSidebarCollapsed: (monitoringSidebarCollapsed) =>diff --git a/dashboard/src/tabs/InstanceTabsPanel.tsx b/dashboard/src/tabs/InstanceTabsPanel.tsxindex b9bb35b7..2dc9b0f2 100644--- a/dashboard/src/tabs/InstanceTabsPanel.tsx+++ b/dashboard/src/tabs/InstanceTabsPanel.tsx@@ -11,6 +11,7 @@ interface Props {tabs: InstanceTab[];emptyMessage?: string;instanceId?: string;+ handoffTabs?: Set<string>;}function sameIds(left: string[], right: string[]): boolean {@@ -24,6 +25,7 @@ export default function InstanceTabsPanel({tabs,emptyMessage = "No tabs open",instanceId,+ handoffTabs,}: Props) {const [selectedTabId, setSelectedTabId] = useState<string | null>(null);const [selectionPinned, setSelectionPinned] = useState(false);@@ -130,6 +132,7 @@ export default function InstanceTabsPanel({pinnedTabId={selectionPinned ? selectedTabId : null}telemetryActive={showTelemetry}newTabsCount={newTabsCount}+ handoffTabs={handoffTabs}onSelect={(id) => {setAcknowledgedTabIds(currentTabIds);setSelectedTabId(id);diff --git a/dashboard/src/tabs/TabBar.tsx b/dashboard/src/tabs/TabBar.tsxindex 6bc16148..670f3939 100644--- a/dashboard/src/tabs/TabBar.tsx+++ b/dashboard/src/tabs/TabBar.tsx@@ -7,6 +7,7 @@ interface Props {pinnedTabId?: string | null;telemetryActive?: boolean;newTabsCount?: number;+ handoffTabs?: Set<string>;onSelect: (id: string) => void;onTogglePinned?: (id: string) => void;onTabClosed?: () => void;@@ -14,6 +15,16 @@ interface Props {onSetTelemetry?: (active: boolean) => void;}+function HandoffDot() {+ return (+ <span+ aria-label="tab paused for human handoff"+ title="Tab is paused for human handoff"+ className="inline-block h-2 w-2 shrink-0 rounded-full bg-red-500 ring-2 ring-bg-surface"+ />+ );+}+function PinIcon({ pinned }: { pinned: boolean }) {return (<svg@@ -39,6 +50,7 @@ export default function TabBar({pinnedTabId,telemetryActive,newTabsCount = 0,+ handoffTabs,onSelect,onTogglePinned,onTabClosed,@@ -61,6 +73,7 @@ export default function TabBar({{tabs.map((tab) => {const isSelected = tab.id === selectedTabId && !telemetryActive;const isPinned = tab.id === pinnedTabId;+ const isInHandoff = handoffTabs?.has(tab.id) ?? false;const title = tab.title || "Untitled";return (@@ -76,9 +89,10 @@ export default function TabBar({type="button"onClick={() => onSelect(tab.id)}title={`${title}\n${tab.url}`}- className="min-w-0 flex-1 truncate text-left"+ className="min-w-0 flex-1 truncate text-left flex items-center gap-1.5"><span className="truncate text-xs font-medium">{title}</span>+ {isInHandoff && <HandoffDot />}</button>{onTogglePinned && (<buttondiff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex 57d18109..ddbe8a57 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -93,6 +93,29 @@ pinchtab network # GET 200 https://...| `pinchtab security` | Open the interactive security overview || `pinchtab completion <shell>` | Generate shell completion scripts |+### Server Flags++```bash+pinchtab server [flags]+```++| Flag | Short | Purpose |+| --- | --- | --- |+| `--yolo` | `-y` | Apply guards down preset (enables evaluate, macro, download) |+| `--headed` | `-H` | Start browser instances in headed (visible) mode |+| `--extension <path>` | `-e` | Load browser extension (repeatable) |++Examples:++```bash+pinchtab server -y # guards down for local dev+pinchtab server -H # visible browser for debugging+pinchtab server -yH # both combined+pinchtab server -e ./my-extension # load extension+```++**Note:** Use `--headed` only when you need visual feedback (debugging, manual testing). Headless mode is more resource-efficient for automation.+## Browser CommandsThe browser control surface is top-level. `tab` is only for list/focus/new/close.diff --git a/internal/autosolver/types.go b/internal/autosolver/types.goindex 99cd2492..92caeedf 100644--- a/internal/autosolver/types.go+++ b/internal/autosolver/types.go@@ -132,7 +132,7 @@ func DefaultConfig() Config {Enabled: true,MaxAttempts: 8,SolverTimeout: 30 * time.Second,- Solvers: []string{"cloudflare", "semantic", "capsolver", "twocaptcha"},+ Solvers: []string{"cloudflare", "semantic"},LLMFallback: false,RetryBaseDelay: 500 * time.Millisecond,RetryMaxDelay: 10 * time.Second,diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex cba0006c..50a5bf07 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -179,7 +179,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {return}if err := h.enforceTabNotPausedForHandoff(resolvedTabID); err != nil {- httpx.ErrorCode(w, 409, "tab_paused_handoff", err.Error(), false, nil)+ httpx.ErrorCode(w, 409, "tab_paused_handoff", err.Error(), false, h.handoffErrorDetails(resolvedTabID))return}}@@ -414,6 +414,9 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {if engineName == "" {engineName = "chrome"}+ if engineName != "lite" {+ h.maybeAutoSolve(tCtx, resolvedTabID, autoSolverTriggerAction)+ }w.Header().Set("X-Engine", engineName)h.recordEngine(r, engineName)resp := map[string]any{"success": true, "result": result}@@ -824,11 +827,16 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re}}+ successful := countSuccessful(results)+ if !allLite && successful > 0 {+ h.maybeAutoSolve(ctx, resolvedTabID, autoSolverTriggerAction)+ }+httpx.JSON(w, 200, map[string]any{"results": results,"total": len(req.Actions),- "successful": countSuccessful(results),- "failed": len(req.Actions) - countSuccessful(results),+ "successful": successful,+ "failed": len(req.Actions) - successful,})}@@ -1113,12 +1121,17 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {results = append(results, actionResult{Index: i, Success: true, Result: res})}+ successful := countSuccessful(results)+ if !allLiteMacro && successful > 0 {+ h.maybeAutoSolve(ctx, resolvedTabID, autoSolverTriggerAction)+ }+httpx.JSON(w, 200, map[string]any{"kind": "macro","results": results,"total": len(req.Steps),- "successful": countSuccessful(results),- "failed": len(req.Steps) - countSuccessful(results),+ "successful": successful,+ "failed": len(req.Steps) - successful,})}diff --git a/internal/handlers/autosolver.go b/internal/handlers/autosolver.goindex 760621e2..e21a2d4c 100644--- a/internal/handlers/autosolver.go+++ b/internal/handlers/autosolver.go@@ -17,24 +17,40 @@ import (const (autoSolverTriggerNavigate = "navigate"autoSolverTriggerAction = "action"++ // autoTriggerMaxAttempts caps retries on nav/action auto-triggers so a+ // missed challenge doesn't block the request path. Explicit POST /solve+ // still uses the fully configured MaxAttempts.+ autoTriggerMaxAttempts = 2++ // autoTriggerRunBudget caps the total time an auto-trigger run can take+ // end-to-end (detection + retries). Safety valve for slow pages or solvers.+ autoTriggerRunBudget = 45 * time.Second)-func (h *Handlers) maybeAutoSolve(ctx context.Context, tabID, trigger string) {+// maybeAutoSolve kicks off the autosolver pipeline for tabID in the background.+// It never blocks the caller: the HTTP request that triggered this returns+// immediately while the solver runs with its own bounded context. If the+// solver detects a challenge and fails, the tab is flipped to paused_handoff+// so subsequent action requests see the 409 handoff error.+func (h *Handlers) maybeAutoSolve(_ context.Context, tabID, trigger string) {if tabID == "" || h.autoSolverRunner == nil || !h.shouldAutoSolve(trigger) {return}- if ctx == nil {- ctx = context.Background()- }- if err := h.autoSolverRunner(ctx, tabID); err != nil &&- !errors.Is(err, context.Canceled) &&- !errors.Is(err, context.DeadlineExceeded) {- slog.Warn("autosolver auto-trigger failed",- "trigger", trigger,- "tab_id", tabID,- "error", err)- }+ go func() {+ runCtx, cancel := context.WithTimeout(context.Background(), autoTriggerRunBudget)+ defer cancel()++ if err := h.autoSolverRunner(runCtx, tabID); err != nil &&+ !errors.Is(err, context.Canceled) &&+ !errors.Is(err, context.DeadlineExceeded) {+ slog.Warn("autosolver auto-trigger failed",+ "trigger", trigger,+ "tab_id", tabID,+ "error", err)+ }+ }()}func (h *Handlers) shouldAutoSolve(trigger string) bool {@@ -67,17 +83,23 @@ func (h *Handlers) runAutoSolver(ctx context.Context, tabID string) error {return err}- html, err := page.HTML()+ // Detection is the cheap path that runs on every nav/action — keep it+ // short so normal pages return almost immediately.+ detectCtx, detectCancel := context.WithTimeout(ctx, 5*time.Second)+ html, err := fetchHTMLWithTimeout(detectCtx, page)+ detectCancel()if err != nil {return err}- // Auto-trigger focuses on challenge resolution and should be a no-op on normal pages.if coreautosolver.DetectChallengeIntent(page.Title(), page.URL(), html) == nil {return nil}cfg := h.normalizedAutoSolverConfig()+ if cfg.MaxAttempts > autoTriggerMaxAttempts {+ cfg.MaxAttempts = autoTriggerMaxAttempts+ }as := h.buildAutoSolver(cfg, true)solveCtx, cancel := context.WithTimeout(ctx, estimateAutoSolverRunTimeout(cfg))@@ -99,12 +121,61 @@ func (h *Handlers) runAutoSolver(ctx context.Context, tabID string) error {"tab_id", tabID,"attempts", result.Attempts,"error", result.Error)+ h.autoHandoffAfterFailure(tabID, deriveChallengeType(result, page))}}return nil}+// fetchHTMLWithTimeout runs page.HTML() but aborts if ctx fires first. Since+// Page.HTML has no context argument, we run it in a goroutine and select on+// ctx — a stuck CDP call will leak the goroutine until the call itself+// unblocks, but the caller returns promptly.+func fetchHTMLWithTimeout(ctx context.Context, page coreautosolver.Page) (string, error) {+ type result struct {+ html string+ err error+ }+ ch := make(chan result, 1)+ go func() {+ html, err := page.HTML()+ ch <- result{html: html, err: err}+ }()+ select {+ case <-ctx.Done():+ return "", ctx.Err()+ case r := <-ch:+ return r.html, r.err+ }+}++// autoHandoffAfterFailure flips the tab into paused_handoff so action routes+// block and the dashboard/agent can escalate to a human. No-op if the tab is+// already paused or the bridge does not support handoff state.+func (h *Handlers) autoHandoffAfterFailure(tabID, challengeType string) {+ if tabID == "" {+ return+ }+ ctrl, ok := h.handoffController()+ if !ok {+ return+ }+ if state, exists := ctrl.TabHandoffState(tabID); exists && state.Status == "paused_handoff" {+ return+ }+ reason := "autosolver_unsolved"+ if trimmed := strings.TrimSpace(challengeType); trimmed != "" {+ reason = "autosolver_unsolved:" + trimmed+ }+ if _, err := h.pauseTabForHandoff(tabID, reason, "autosolver", 0); err != nil {+ slog.Warn("autosolver: auto-handoff failed",+ "tab_id", tabID,+ "reason", reason,+ "error", err)+ }+}+func (h *Handlers) normalizedAutoSolverConfig() coreautosolver.Config {cfg := coreautosolver.DefaultConfig()if h == nil || h.Config == nil {diff --git a/internal/handlers/autosolver_test.go b/internal/handlers/autosolver_test.goindex 47ccc772..53e5ea78 100644--- a/internal/handlers/autosolver_test.go+++ b/internal/handlers/autosolver_test.go@@ -2,7 +2,9 @@ package handlersimport ("context"+ "sync/atomic""testing"+ "time""github.com/pinchtab/pinchtab/internal/config")@@ -86,28 +88,44 @@ func TestMaybeAutoSolve_InvokesRunnerWhenEnabled(t *testing.T) {}},}- calls := 0+ var calls atomic.Int64+ done := make(chan struct{}, 8)h.autoSolverRunner = func(_ context.Context, tabID string) error {- calls+++ calls.Add(1)if tabID != "tab1" {- t.Fatalf("runner tabID = %q, want tab1", tabID)+ t.Errorf("runner tabID = %q, want tab1", tabID)}+ done <- struct{}{}return nil}+ waitFor := func(expected int64) bool {+ deadline := time.Now().Add(2 * time.Second)+ for time.Now().Before(deadline) {+ if calls.Load() == expected {+ return true+ }+ time.Sleep(5 * time.Millisecond)+ }+ return false+ }+h.maybeAutoSolve(context.Background(), "tab1", autoSolverTriggerNavigate)- if calls != 1 {- t.Fatalf("autoSolverRunner calls = %d, want 1", calls)+ if !waitFor(1) {+ t.Fatalf("autoSolverRunner calls = %d, want 1", calls.Load())}+ <-doneh.maybeAutoSolve(context.Background(), "", autoSolverTriggerNavigate)- if calls != 1 {- t.Fatalf("autoSolverRunner calls with empty tab id = %d, want unchanged", calls)+ time.Sleep(20 * time.Millisecond) // ensure no goroutine was spawned+ if got := calls.Load(); got != 1 {+ t.Fatalf("autoSolverRunner calls with empty tab id = %d, want unchanged", got)}h.Config.AutoSolver.TriggerOnNavigate = falseh.maybeAutoSolve(context.Background(), "tab1", autoSolverTriggerNavigate)- if calls != 1 {- t.Fatalf("autoSolverRunner calls with navigate trigger disabled = %d, want unchanged", calls)+ time.Sleep(20 * time.Millisecond)+ if got := calls.Load(); got != 1 {+ t.Fatalf("autoSolverRunner calls with navigate trigger disabled = %d, want unchanged", got)}}diff --git a/internal/handlers/handoff.go b/internal/handlers/handoff.goindex 0033a9bf..7a29edc5 100644--- a/internal/handlers/handoff.go+++ b/internal/handlers/handoff.go@@ -26,6 +26,63 @@ func (h *Handlers) handoffController() (tabHandoffController, bool) {return ctrl, ok}+// handoffHintMessage is included in error responses and dashboard events when+// the agent must yield control to a human operator.+const handoffHintMessage = "return control to the user and ask them to manually solve the challenge in the browser window, then call POST /tabs/{id}/resume to continue"++// handoffErrorDetails builds the details payload attached to 409 responses+// when an action hits a tab that is paused for handoff. Always includes the+// agent hint; when known, also includes the current reason and pausedAt.+func (h *Handlers) handoffErrorDetails(tabID string) map[string]any {+ details := map[string]any{"hint": handoffHintMessage}+ if ctrl, ok := h.handoffController(); ok {+ if state, exists := ctrl.TabHandoffState(tabID); exists {+ if state.Reason != "" {+ details["reason"] = state.Reason+ }+ if !state.PausedAt.IsZero() {+ details["pausedAt"] = state.PausedAt.Format(time.RFC3339)+ }+ }+ }+ return details+}++// pauseTabForHandoff marks a tab as paused for human handoff and broadcasts+// a dashboard event. source identifies what triggered the handoff+// (e.g. "autosolver", "manual"). Returns the applied reason.+func (h *Handlers) pauseTabForHandoff(tabID, reason, source string, timeout time.Duration) (string, error) {+ ctrl, ok := h.handoffController()+ if !ok {+ return "", fmt.Errorf("bridge does not support handoff state")+ }+ reason = strings.TrimSpace(reason)+ if reason == "" {+ reason = "manual_handoff"+ }+ if err := ctrl.SetTabHandoff(tabID, reason, timeout); err != nil {+ return reason, err+ }+ if h.Dashboard != nil {+ payload := map[string]any{+ "tabId": tabID,+ "status": "paused_handoff",+ "reason": reason,+ "source": source,+ "hint": handoffHintMessage,+ "requestedAt": time.Now().UTC().Format(time.RFC3339),+ }+ if timeout > 0 {+ payload["timeoutMs"] = int(timeout / time.Millisecond)+ }+ h.Dashboard.BroadcastSystemEvent(dashboard.SystemEvent{+ Type: "tab.handoff",+ Instance: payload,+ })+ }+ return reason, nil+}+func (h *Handlers) HandleTabHandoff(w http.ResponseWriter, r *http.Request) {tabID := strings.TrimSpace(r.PathValue("id"))if tabID == "" {@@ -56,45 +113,29 @@ func (h *Handlers) HandleTabHandoff(w http.ResponseWriter, r *http.Request) {return}- ctrl, ok := h.handoffController()- if !ok {+ if _, ok := h.handoffController(); !ok {httpx.ErrorCode(w, 501, "handoff_not_supported", "bridge does not support handoff state", false, nil)return}-- reason := strings.TrimSpace(req.Reason)- if reason == "" {- reason = "manual_handoff"- }- timeout := time.Duration(req.TimeoutMs) * time.Millisecondif req.TimeoutMs < 0 {httpx.Error(w, 400, fmt.Errorf("timeoutMs must be >= 0"))return}- if err := ctrl.SetTabHandoff(resolvedTabID, reason, timeout); err != nil {+ timeout := time.Duration(req.TimeoutMs) * time.Millisecond+ reason, err := h.pauseTabForHandoff(resolvedTabID, req.Reason, "manual", timeout)+ if err != nil {httpx.ErrorCode(w, 500, "handoff_failed", err.Error(), false, nil)return}h.recordActivity(r, activity.Update{Action: "handoff", TabID: resolvedTabID})- if h.Dashboard != nil {- h.Dashboard.BroadcastSystemEvent(dashboard.SystemEvent{- Type: "tab.handoff",- Instance: map[string]any{- "tabId": resolvedTabID,- "status": "paused_handoff",- "reason": reason,- "timeoutMs": req.TimeoutMs,- "requestedAt": time.Now().UTC().Format(time.RFC3339),- },- })- }resp := map[string]any{"tabId": resolvedTabID,"status": "paused_handoff","reason": reason,"timeoutMs": req.TimeoutMs,+ "hint": handoffHintMessage,}if timeout > 0 {resp["expiresAt"] = time.Now().UTC().Add(timeout).Format(time.RFC3339)diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.goindex 31d67a8e..c34cae14 100644--- a/internal/handlers/middleware.go+++ b/internal/handlers/middleware.go@@ -447,7 +447,7 @@ func sessionConsoleGrantAllows(method, path string) bool {func sessionSolveGrantAllows(method, path string) bool {switch method {case http.MethodGet:- return path == "/solvers"+ return path == "/solvers" || path == "/config/autosolver"case http.MethodPost:switch {case path == "/solve" || strings.HasPrefix(path, "/solve/"):diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.goindex ff6491a2..0b860d6b 100644--- a/internal/handlers/navigation.go+++ b/internal/handlers/navigation.go@@ -244,6 +244,8 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {return}+ h.maybeAutoSolve(tCtx, newTabID, autoSolverTriggerNavigate)+var navURL string_ = chromedp.Run(tCtx, chromedp.Location(&navURL))title, _ := bridge.WaitForTitle(tCtx, titleWait)@@ -300,6 +302,8 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {return}+ h.maybeAutoSolve(tCtx, resolvedTabID, autoSolverTriggerNavigate)+var navURL string_ = chromedp.Run(tCtx, chromedp.Location(&navURL))title, _ := bridge.WaitForTitle(tCtx, titleWait)diff --git a/internal/handlers/solver.go b/internal/handlers/solver.goindex 98f9a9e4..004f991e 100644--- a/internal/handlers/solver.go+++ b/internal/handlers/solver.go@@ -156,14 +156,26 @@ func (h *Handlers) HandleSolve(w http.ResponseWriter, r *http.Request) {title = page.Title()}- httpx.JSON(w, 200, map[string]any{+ challengeType := deriveChallengeType(result, page)+ resp := map[string]any{"tabId": resolvedTabID,"solver": solverName,"solved": result.Solved,- "challengeType": deriveChallengeType(result, page),+ "challengeType": challengeType,"attempts": result.Attempts,"title": title,- })+ }++ // If a challenge was detected but the solver couldn't resolve it, flip the+ // tab into paused_handoff so subsequent actions block and the caller can+ // escalate to a human.+ if !result.Solved && result.Attempts > 0 && challengeType != "" {+ h.autoHandoffAfterFailure(resolvedTabID, challengeType)+ resp["handoff"] = "paused_handoff"+ resp["hint"] = handoffHintMessage+ }++ httpx.JSON(w, 200, resp)}// HandleTabSolve handles POST /tabs/{id}/solve and /tabs/{id}/solve/{name}.diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex 973c64c0..2edd1ed8 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -71,6 +71,11 @@ var coreEndpoints = []Endpoint{{"POST", "/lock", "Lock tab", CapNone, true},{"POST", "/unlock", "Unlock tab", CapNone, true},+ // Human handoff+ {"POST", "/handoff", "Pause tab for human handoff", CapNone, true},+ {"POST", "/resume", "Resume paused tab", CapNone, true},+ {"GET", "/handoff", "Get handoff status", CapNone, true},+// Cookies{"GET", "/cookies", "Get cookies", CapNone, true},{"POST", "/cookies", "Set cookies", CapNone, true},diff --git a/skills/pinchtab/references/commands.md b/skills/pinchtab/references/commands.mdindex 0dfffdbd..98de75dd 100644--- a/skills/pinchtab/references/commands.md+++ b/skills/pinchtab/references/commands.md@@ -6,15 +6,25 @@## Control Plane-### `pinchtab start`+### `pinchtab server`Start the PinchTab server (default port 9867).```bash-pinchtab start-pinchtab start --port 9868-pinchtab start --profile work --headless+pinchtab server+pinchtab server -y # guards down (enables evaluate, macro, download)+pinchtab server -H # visible browser for debugging+pinchtab server -yH # both combined+pinchtab server -e ./ext # load browser extension```+| Flag | Short | Description |+|------|-------|-------------|+| `--yolo` | `-y` | Apply guards down preset (enables evaluate, macro, download) |+| `--headed` | `-H` | Start browser in headed (visible) mode |+| `--extension <path>` | `-e` | Load browser extension (repeatable) |++> **Note:** Use `--headed` only when you need visual feedback (debugging, watching automation). Headless mode is more resource-efficient.+### `pinchtab stop`Stop the running server.diff --git a/tests/e2e/helpers/api-assertions.sh b/tests/e2e/helpers/api-assertions.shindex 096e26fa..893f7d76 100644--- a/tests/e2e/helpers/api-assertions.sh+++ b/tests/e2e/helpers/api-assertions.sh@@ -119,6 +119,20 @@ assert_contains() {fi}+assert_not_contains() {+ local haystack="$1"+ local needle="$2"+ local desc="${3:-does not contain '$needle'}"++ if echo "$haystack" | grep -q "$needle"; then+ echo -e " ${RED}✗${NC} $desc (found when should be absent)"+ ((ASSERTIONS_FAILED++)) || true+ else+ echo -e " ${GREEN}✓${NC} $desc"+ ((ASSERTIONS_PASSED++)) || true+ fi+}+assert_result_eq() {local path="$1"local expected="$2"