High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(plugin): harden per-agent Pinchtab session handling
Luigi Agosti10ac7e840a6a
diff --git a/.github/FUNDING.yml b/.github/FUNDING.ymlnew file mode 100644index 00000000..4af2cad9--- /dev/null+++ b/.github/FUNDING.yml@@ -0,0 +1 @@+github: pinchtabdiff --git a/dev b/devindex 1a06ceae..2f0258aa 100755--- a/dev+++ b/dev@@ -264,10 +264,14 @@ run_command() {echo ""exec env E2E_LOGS="${E2E_LOGS:-show}" bash scripts/dev-e2e.sh "$test_name";;- "e2e smoke-plugin")+ "e2e smoke-plugin"|"e2e smoke-plugin "*)echo " ${ACCENT}${BOLD}π³ OpenClaw plugin smoke${NC}"echo ""- exec bash tests/manual/openclaw-plugin-smoke/run.sh+ local -a smoke_args=()+ if [ "$target" != "e2e smoke-plugin" ]; then+ read -r -a smoke_args <<< "${target#e2e smoke-plugin }"+ fi+ exec bash tests/manual/openclaw-plugin-smoke/run.sh "${smoke_args[@]}";;"e2e"*)local -a e2e_args=()@@ -419,7 +423,7 @@ if [ $# -gt 0 ]; thenecho ""echo " ${ACCENT}${BOLD}π³ OpenClaw plugin smoke${NC}"echo ""- exec bash tests/manual/openclaw-plugin-smoke/run.sh+ exec bash tests/manual/openclaw-plugin-smoke/run.sh "${@:3}"firun_e2e_runner "${@:2}";;diff --git a/internal/bridge/action_pointer.go b/internal/bridge/action_pointer.goindex bdab4a1e..c262f07a 100644--- a/internal/bridge/action_pointer.go+++ b/internal/bridge/action_pointer.go@@ -2,6 +2,7 @@ package bridgeimport ("context"+ "errors""fmt""log/slog""strings"@@ -15,6 +16,44 @@ var scrollByCoordinateAction = ScrollByCoordinatevar mouseMoveByCoordinateAction = MouseMoveByCoordinatevar mouseDownByCoordinateAction = MouseDownByCoordinatevar mouseUpByCoordinateAction = MouseUpByCoordinate+var clickByNodeIDAction = ClickByNodeID+var jsClickByBackendNodeAction = JSClickByBackendNode+var doubleClickByNodeIDAction = DoubleClickByNodeID+var jsDoubleClickByBackendNodeAction = JSDoubleClickByBackendNode++const trustedNodeClickTimeout = 100 * time.Millisecond++func clickByNodeIDWithJSFallback(ctx context.Context, nodeID int64) error {+ trustedCtx, cancel := context.WithTimeout(ctx, trustedNodeClickTimeout)+ err := clickByNodeIDAction(trustedCtx, nodeID)+ cancel()+ if err == nil {+ return nil+ }+ if ctx.Err() != nil {+ return ctx.Err()+ }+ if errors.Is(err, context.DeadlineExceeded) {+ return jsClickByBackendNodeAction(ctx, nodeID)+ }+ return err+}++func doubleClickByNodeIDWithJSFallback(ctx context.Context, nodeID int64) error {+ trustedCtx, cancel := context.WithTimeout(ctx, trustedNodeClickTimeout)+ err := doubleClickByNodeIDAction(trustedCtx, nodeID)+ cancel()+ if err == nil {+ return nil+ }+ if ctx.Err() != nil {+ return ctx.Err()+ }+ if errors.Is(err, context.DeadlineExceeded) {+ return jsDoubleClickByBackendNodeAction(ctx, nodeID)+ }+ return err+}// effectiveHumanize resolves whether an action should use the humanized// (bezier + per-event jitter + pre-press sleeps) input path. Precedence:@@ -156,9 +195,9 @@ func (b *Bridge) actionClick(ctx context.Context, req ActionRequest) (map[stringresultCh <- clickResult{err: nodeErr}return}- err = JSClickByBackendNode(clickCtx, int64(node.BackendNodeID))+ err = clickByNodeIDWithJSFallback(clickCtx, int64(node.BackendNodeID))} else if req.NodeID > 0 {- err = JSClickByBackendNode(clickCtx, req.NodeID)+ err = clickByNodeIDWithJSFallback(clickCtx, req.NodeID)} else if req.HasXY {err = ClickByCoordinate(clickCtx, req.X, req.Y)} else {@@ -240,9 +279,9 @@ func (b *Bridge) actionDoubleClick(ctx context.Context, req ActionRequest) (map[if nodeErr != nil {return nil, nodeErr}- err = JSDoubleClickByBackendNode(ctx, int64(node.BackendNodeID))+ err = doubleClickByNodeIDWithJSFallback(ctx, int64(node.BackendNodeID))} else if req.NodeID > 0 {- err = JSDoubleClickByBackendNode(ctx, req.NodeID)+ err = doubleClickByNodeIDWithJSFallback(ctx, req.NodeID)} else if req.HasXY {err = DoubleClickByCoordinate(ctx, req.X, req.Y)} else {diff --git a/internal/bridge/actions_test.go b/internal/bridge/actions_test.goindex c462b30f..d9c198cd 100644--- a/internal/bridge/actions_test.go+++ b/internal/bridge/actions_test.go@@ -3,6 +3,7 @@ package bridgeimport ("context""encoding/json"+ "errors""strings""testing"@@ -384,6 +385,91 @@ func TestClickAction_HumanizeOptInUsesHumanizedPath(t *testing.T) {}}+func TestClickByNodeIDWithJSFallback_UsesTrustedPathFirst(t *testing.T) {+ origTrusted := clickByNodeIDAction+ origFallback := jsClickByBackendNodeAction+ t.Cleanup(func() {+ clickByNodeIDAction = origTrusted+ jsClickByBackendNodeAction = origFallback+ })++ var trustedCalled bool+ var fallbackCalled bool+ clickByNodeIDAction = func(ctx context.Context, nodeID int64) error {+ trustedCalled = true+ if nodeID != 42 {+ t.Fatalf("nodeID = %d, want 42", nodeID)+ }+ return nil+ }+ jsClickByBackendNodeAction = func(context.Context, int64) error {+ fallbackCalled = true+ return nil+ }++ if err := clickByNodeIDWithJSFallback(context.Background(), 42); err != nil {+ t.Fatalf("clickByNodeIDWithJSFallback error = %v", err)+ }+ if !trustedCalled {+ t.Fatal("trusted CDP click path was not called")+ }+ if fallbackCalled {+ t.Fatal("JS fallback should not run when trusted click succeeds")+ }+}++func TestClickByNodeIDWithJSFallback_FallsBackOnlyOnTimeout(t *testing.T) {+ origTrusted := clickByNodeIDAction+ origFallback := jsClickByBackendNodeAction+ t.Cleanup(func() {+ clickByNodeIDAction = origTrusted+ jsClickByBackendNodeAction = origFallback+ })++ var fallbackCalled bool+ clickByNodeIDAction = func(context.Context, int64) error {+ return context.DeadlineExceeded+ }+ jsClickByBackendNodeAction = func(context.Context, int64) error {+ fallbackCalled = true+ return nil+ }++ if err := clickByNodeIDWithJSFallback(context.Background(), 42); err != nil {+ t.Fatalf("clickByNodeIDWithJSFallback error = %v", err)+ }+ if !fallbackCalled {+ t.Fatal("JS fallback should run after trusted click timeout")+ }+}++func TestClickByNodeIDWithJSFallback_DoesNotFallbackOnOtherErrors(t *testing.T) {+ origTrusted := clickByNodeIDAction+ origFallback := jsClickByBackendNodeAction+ t.Cleanup(func() {+ clickByNodeIDAction = origTrusted+ jsClickByBackendNodeAction = origFallback+ })++ boom := errors.New("boom")+ var fallbackCalled bool+ clickByNodeIDAction = func(context.Context, int64) error {+ return boom+ }+ jsClickByBackendNodeAction = func(context.Context, int64) error {+ fallbackCalled = true+ return nil+ }++ err := clickByNodeIDWithJSFallback(context.Background(), 42)+ if !errors.Is(err, boom) {+ t.Fatalf("error = %v, want boom", err)+ }+ if fallbackCalled {+ t.Fatal("JS fallback should not run for non-timeout trusted click errors")+ }+}+func TestTypeAction_HumanizeOptInUsesHumanizedPath(t *testing.T) {raw := New(context.TODO(), nil, &config.RuntimeConfig{Humanize: true})ctx, cancel := context.WithCancel(context.Background())diff --git a/plugin/README.md b/plugin/README.mdindex 4ca5f0bc..02621e07 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -2,6 +2,8 @@Browser control for AI agents via [PinchTab](https://pinchtab.com). Single-tool design β one `pinchtab` tool handles all browser operations. Minimal context bloat.+> **Beta**: this plugin is in beta and is not fully tested in this release. Expect rough edges around per-agent session isolation, the `browser` compatibility alias, and OpenClaw plugin loader behavior. Production use is at your own risk β please file issues for anything you hit.+## Install```bash@@ -223,7 +225,7 @@ pinchtab({ action: "wait", text: "Welcome back", timeout: 120000 })## Security Notes-- **Auto-start** spawns a background process β only enabled for local addresses (`localhost`, `127.0.0.1`, `::1`). Set `autoStart: false` if you prefer explicit server management.+- **Server lifecycle**: the plugin does not start PinchTab β run `pinchtab server` separately. If the server isn't reachable, the plugin returns a clear error pointing at the configured `baseUrl`. Once the server is up, the plugin briefly waits for instance/profile readiness (handles the "still booting" / `503` window).- **`evaluate`** is blocked by default (`allowEvaluate: false`) β enable only for trusted agents- **`downloads`** and **`uploads`** are blocked by default β enable only when the task requires file transfer- **Cookie access** exposes session credentials β do not log or expose to untrusted contextsdiff --git a/plugin/client.test.ts b/plugin/client.test.tsindex adf7c318..9aa856e8 100644--- a/plugin/client.test.ts+++ b/plugin/client.test.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, it } from "node:test";import assert from "node:assert";-import { isRefToken, normalizeActionParams, looksLikeStaleRef, pinchtabFetch, textResult, imageResult, resourceResult } from "./client.ts";+import { isRefToken, normalizeActionParams, looksLikeStaleRef, pinchtabFetch, textResult, imageResult, resourceResult, clearPinchtabSessionCache } from "./client.ts";describe("isRefToken", () => {it("returns true for valid ref tokens", () => {@@ -73,11 +73,28 @@ describe("looksLikeStaleRef", () => {assert.strictEqual(looksLikeStaleRef({ error: "context canceled" }), true);});+ it("matches Pinchtab backend-node failures", () => {+ assert.strictEqual(+ looksLikeStaleRef({ error: "element not found in DOM (backendNodeId=42)" }),+ true,+ );+ assert.strictEqual(looksLikeStaleRef({ error: "backend-node-not-found" }), true);+ assert.strictEqual(looksLikeStaleRef({ error: "backend node detached" }), true);+ assert.strictEqual(looksLikeStaleRef({ error: "element no longer in DOM" }), true);+ assert.strictEqual(looksLikeStaleRef({ error: "element no longer attached" }), true);+ });+it("returns false for other errors", () => {assert.strictEqual(looksLikeStaleRef({ error: "network timeout" }), false);assert.strictEqual(looksLikeStaleRef({ error: "server error" }), false);});+ it("does not match unrelated substrings containing 'ref'", () => {+ assert.strictEqual(looksLikeStaleRef({ error: "referrer policy violation" }), false);+ assert.strictEqual(looksLikeStaleRef({ error: "unsupported preferences" }), false);+ assert.strictEqual(looksLikeStaleRef({ error: "page not found" }), false);+ });+it("checks body as well as error", () => {assert.strictEqual(looksLikeStaleRef({ error: "failed", body: "stale ref" }), true);});@@ -115,6 +132,204 @@ describe("pinchtabFetch", () => {});});+describe("pinchtabFetch per-agent session token", () => {+ const originalFetch = globalThis.fetch;+ let calls: Array<{ url: string; method: string; headers: Record<string, string>; body?: string }>;++ beforeEach(() => {+ clearPinchtabSessionCache();+ calls = [];+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {+ const url = typeof input === "string" ? input : input.toString();+ const method = (init?.method || "GET").toUpperCase();+ const headers = (init?.headers ?? {}) as Record<string, string>;+ const body = typeof init?.body === "string" ? init.body : undefined;+ calls.push({ url, method, headers, body });+ if (url.endsWith("/sessions") && method === "POST") {+ return new Response(JSON.stringify({ id: "ses_abc", sessionToken: "ses_token_xyz" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ return new Response(JSON.stringify({ ok: true, headers }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }) as typeof fetch;+ });++ afterEach(() => {+ globalThis.fetch = originalFetch;+ clearPinchtabSessionCache();+ });++ it("creates a Pinchtab session lazily and uses its token for browser actions", async () => {+ await pinchtabFetch(+ { baseUrl: "http://localhost:9867", token: "server-token" },+ "/snapshot",+ {},+ { agentId: "alpha" },+ );+ assert.strictEqual(calls.length, 2);+ assert.strictEqual(calls[0].url, "http://localhost:9867/sessions");+ assert.strictEqual(calls[0].method, "POST");+ assert.strictEqual(calls[0].headers.Authorization, "Bearer server-token");+ assert.deepStrictEqual(JSON.parse(calls[0].body!), { agentId: "alpha", label: "openclaw" });+ assert.strictEqual(calls[1].url, "http://localhost:9867/snapshot");+ assert.strictEqual(calls[1].headers.Authorization, "Session ses_token_xyz");+ });++ it("reuses the cached session token across calls for the same agent", async () => {+ const cfg = { baseUrl: "http://localhost:9867", token: "server-token" };+ await pinchtabFetch(cfg, "/snapshot", {}, { agentId: "alpha" });+ await pinchtabFetch(cfg, "/tabs", {}, { agentId: "alpha" });+ const sessionPosts = calls.filter((c) => c.url.endsWith("/sessions") && c.method === "POST");+ assert.strictEqual(sessionPosts.length, 1);+ const tabsCall = calls.find((c) => c.url.endsWith("/tabs"));+ assert.strictEqual(tabsCall?.headers.Authorization, "Session ses_token_xyz");+ });++ it("creates separate sessions for distinct agents", async () => {+ const cfg = { baseUrl: "http://localhost:9867", token: "server-token" };+ await pinchtabFetch(cfg, "/snapshot", {}, { agentId: "alpha" });+ await pinchtabFetch(cfg, "/snapshot", {}, { agentId: "beta" });+ const sessionPosts = calls.filter((c) => c.url.endsWith("/sessions") && c.method === "POST");+ assert.strictEqual(sessionPosts.length, 2);+ const agentIds = sessionPosts.map((c) => JSON.parse(c.body!).agentId).sort();+ assert.deepStrictEqual(agentIds, ["alpha", "beta"]);+ });++ it("uses the server token for /health, /sessions, /instances, /profiles", async () => {+ const cfg = { baseUrl: "http://localhost:9867", token: "server-token" };+ await pinchtabFetch(cfg, "/health", {}, { agentId: "alpha" });+ await pinchtabFetch(cfg, "/instances", {}, { agentId: "alpha" });+ await pinchtabFetch(cfg, "/profiles", {}, { agentId: "alpha" });+ for (const call of calls) {+ assert.strictEqual(call.headers.Authorization, "Bearer server-token");+ }+ });++ it("falls back to server token when context has no agentId", async () => {+ await pinchtabFetch(+ { baseUrl: "http://localhost:9867", token: "server-token" },+ "/snapshot",+ {},+ );+ assert.strictEqual(calls.length, 1);+ assert.strictEqual(calls[0].headers.Authorization, "Bearer server-token");+ });+});++describe("pinchtabFetch session failure modes", () => {+ const originalFetch = globalThis.fetch;++ afterEach(() => {+ globalThis.fetch = originalFetch;+ clearPinchtabSessionCache();+ });++ it("fails closed (no bearer fallback) when /sessions creation fails for an agent", async () => {+ clearPinchtabSessionCache();+ const calls: Array<{ url: string; method: string }> = [];+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {+ const url = typeof input === "string" ? input : input.toString();+ const method = (init?.method || "GET").toUpperCase();+ calls.push({ url, method });+ if (url.endsWith("/sessions") && method === "POST") {+ return new Response("upstream timeout", { status: 503 });+ }+ throw new Error("must not fall back to bearer for the snapshot path");+ }) as typeof fetch;++ const result = await pinchtabFetch(+ { baseUrl: "http://localhost:9867", token: "server-token" },+ "/snapshot",+ {},+ { agentId: "alpha" },+ );+ assert.strictEqual(calls.length, 1);+ assert.strictEqual(calls[0].url, "http://localhost:9867/sessions");+ assert.match(result.error, /Pinchtab session creation failed for agent alpha/);+ assert.match(result.error, /503/);+ });++ it("evicts cached token and retries once on 401 from a Session-scheme call", async () => {+ clearPinchtabSessionCache();+ const calls: Array<{ url: string; method: string; headers: Record<string, string> }> = [];+ let sessionTokenCounter = 0;+ let firstSnapshot = true;+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {+ const url = typeof input === "string" ? input : input.toString();+ const method = (init?.method || "GET").toUpperCase();+ const headers = (init?.headers ?? {}) as Record<string, string>;+ calls.push({ url, method, headers });+ if (url.endsWith("/sessions") && method === "POST") {+ sessionTokenCounter += 1;+ return new Response(+ JSON.stringify({ id: `ses_${sessionTokenCounter}`, sessionToken: `ses_token_${sessionTokenCounter}` }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ );+ }+ if (url.endsWith("/snapshot")) {+ if (firstSnapshot) {+ firstSnapshot = false;+ return new Response(JSON.stringify({ error: "bad_session" }), {+ status: 401,+ headers: { "Content-Type": "application/json" },+ });+ }+ return new Response(JSON.stringify({ ok: true }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ return new Response("", { status: 200 });+ }) as typeof fetch;++ const result = await pinchtabFetch(+ { baseUrl: "http://localhost:9867", token: "server-token" },+ "/snapshot",+ {},+ { agentId: "alpha" },+ );+ assert.deepStrictEqual(result, { ok: true });+ const sessionPosts = calls.filter((c) => c.url.endsWith("/sessions") && c.method === "POST");+ assert.strictEqual(sessionPosts.length, 2, "should re-create session after 401");+ const snapshotCalls = calls.filter((c) => c.url.endsWith("/snapshot"));+ assert.strictEqual(snapshotCalls.length, 2);+ assert.strictEqual(snapshotCalls[0].headers.Authorization, "Session ses_token_1");+ assert.strictEqual(snapshotCalls[1].headers.Authorization, "Session ses_token_2");+ });++ it("does not loop indefinitely if 401s keep coming after retry", async () => {+ clearPinchtabSessionCache();+ let sessionPosts = 0;+ let snapshotCalls = 0;+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {+ const url = typeof input === "string" ? input : input.toString();+ const method = (init?.method || "GET").toUpperCase();+ if (url.endsWith("/sessions") && method === "POST") {+ sessionPosts += 1;+ return new Response(JSON.stringify({ sessionToken: `ses_${sessionPosts}` }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ snapshotCalls += 1;+ return new Response("bad_session", { status: 401 });+ }) as typeof fetch;++ const result = await pinchtabFetch(+ { baseUrl: "http://localhost:9867", token: "server-token" },+ "/snapshot",+ {},+ { agentId: "alpha" },+ );+ assert.strictEqual(snapshotCalls, 2, "exactly one retry, no infinite loop");+ assert.strictEqual(result.error, "401 ");+ });+});+describe("textResult", () => {it("wraps string as text content", () => {const result = textResult("hello");diff --git a/plugin/client.ts b/plugin/client.tsindex 4f173cde..51003df7 100644--- a/plugin/client.ts+++ b/plugin/client.ts@@ -1,30 +1,147 @@import type { PluginConfig, PluginRuntimeContext, ToolResult } from "./types.js";-import { resolveEffectiveConfig } from "./session.js";-function buildRequestHeaders(cfg: PluginConfig, context?: PluginRuntimeContext): Record<string, string> {+// Pinchtab isolates browser state per session token created by `POST /sessions`+// with a distinct agentId. Without per-agent sessions every OpenClaw agent+// shares the same browser context, so cookies/storage leak across them.+const pinchtabSessionTokens = new Map<string, string>();++const SERVER_TOKEN_PATH_PREFIXES = ["/sessions", "/instances", "/profiles"];++function isServerTokenPath(path: string): boolean {+ const stripped = path.split("?", 1)[0];+ if (stripped === "/health") return true;+ for (const prefix of SERVER_TOKEN_PATH_PREFIXES) {+ if (stripped === prefix || stripped.startsWith(`${prefix}/`)) return true;+ }+ return false;+}++type SessionResolution =+ | { kind: "ok"; token: string }+ | { kind: "no-agent" }+ | { kind: "error"; error: string };++async function ensurePinchtabSession(+ cfg: PluginConfig,+ context: PluginRuntimeContext | undefined,+ forceRefresh = false,+): Promise<SessionResolution> {+ const agentId = context?.agentId;+ if (!agentId) return { kind: "no-agent" };+ if (!cfg.token || !cfg.baseUrl) {+ return { kind: "error", error: "Pinchtab plugin missing baseUrl or token; cannot create per-agent session" };+ }+ if (forceRefresh) pinchtabSessionTokens.delete(agentId);+ const cached = pinchtabSessionTokens.get(agentId);+ if (cached) return { kind: "ok", token: cached };++ const controller = new AbortController();+ const timeout = cfg.timeoutMs ?? cfg.timeout ?? 30000;+ const timer = setTimeout(() => controller.abort(), timeout);+ try {+ const res = await fetch(`${cfg.baseUrl}/sessions`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${cfg.token}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ agentId, label: "openclaw" }),+ signal: controller.signal,+ });+ if (!res.ok) {+ const body = await res.text().catch(() => "");+ return {+ kind: "error",+ error: `Pinchtab session creation failed for agent ${agentId}: ${res.status} ${res.statusText}${body ? ` - ${body.slice(0, 200)}` : ""}`,+ };+ }+ const data = (await res.json().catch(() => null)) as { sessionToken?: string } | null;+ const token = data?.sessionToken;+ if (typeof token === "string" && token) {+ pinchtabSessionTokens.set(agentId, token);+ return { kind: "ok", token };+ }+ return { kind: "error", error: `Pinchtab /sessions response missing sessionToken for agent ${agentId}` };+ } catch (err: any) {+ const reason = err?.name === "AbortError" ? `timed out after ${timeout}ms` : (err?.message || String(err));+ return { kind: "error", error: `Pinchtab session creation failed for agent ${agentId}: ${reason}` };+ } finally {+ clearTimeout(timer);+ }+}++function evictPinchtabSession(agentId: string | undefined): void {+ if (agentId) pinchtabSessionTokens.delete(agentId);+}++export function clearPinchtabSessionCache(): void {+ pinchtabSessionTokens.clear();+}++function buildRequestHeaders(+ cfg: PluginConfig,+ context: PluginRuntimeContext | undefined,+ authToken: string | undefined,+ authScheme: "Bearer" | "Session",+): Record<string, string> {const headers: Record<string, string> = {};- if (cfg.token) headers["Authorization"] = `Bearer ${cfg.token}`;+ if (authToken) headers["Authorization"] = `${authScheme} ${authToken}`;if (context?.agentId) headers["X-OpenClaw-Agent-Id"] = context.agentId;- if (context?.agentName) headers["X-OpenClaw-Agent-Name"] = context.agentName;if (context?.sessionId) headers["X-OpenClaw-Session-Id"] = context.sessionId;if (context?.sessionKey) headers["X-OpenClaw-Session-Key"] = context.sessionKey;return headers;}+/**+ * Caller must pass an already-resolved cfg (see `resolveEffectiveConfig` in session.ts).+ * The two tool entry points (`executePinchtabAction`, `executeBrowserAction`) resolve once+ * at the top and pass the resolved cfg through every subsequent call. Skipping resolution+ * here means a raw cfg with empty baseUrl/token will hit `http://localhost:9867` blindly.+ */export async function pinchtabFetch(cfg: PluginConfig,path: string,opts: { method?: string; body?: unknown; rawResponse?: boolean } = {},context?: PluginRuntimeContext,): Promise<any> {- const effectiveCfg = await resolveEffectiveConfig(cfg);- const base = effectiveCfg.baseUrl || "http://localhost:9867";+ const base = cfg.baseUrl || "http://localhost:9867";+ const resolvedCfg = { ...cfg, baseUrl: base };++ return performPinchtabFetch(resolvedCfg, path, opts, context, false);+}++async function performPinchtabFetch(+ cfg: PluginConfig,+ path: string,+ opts: { method?: string; body?: unknown; rawResponse?: boolean },+ context: PluginRuntimeContext | undefined,+ alreadyRetriedSession: boolean,+): Promise<any> {+ const base = cfg.baseUrl as string;const url = `${base}${path}`;- const headers = buildRequestHeaders(effectiveCfg, context);+ let authToken = cfg.token;+ let authScheme: "Bearer" | "Session" = "Bearer";++ if (!isServerTokenPath(path)) {+ const resolution = await ensurePinchtabSession(cfg, context);+ if (resolution.kind === "error") {+ // Fail closed: do NOT silently fall back to the shared server token.+ // Without a per-agent session, this agent would join the shared browser+ // context, defeating per-agent isolation.+ return { error: resolution.error };+ }+ if (resolution.kind === "ok") {+ authToken = resolution.token;+ authScheme = "Session";+ }+ // kind === "no-agent": legitimate bearer use (no agent context, e.g. CLI smoke).+ }++ const headers = buildRequestHeaders(cfg, context, authToken, authScheme);if (opts.body) headers["Content-Type"] = "application/json";const controller = new AbortController();- const timeout = effectiveCfg.timeoutMs ?? effectiveCfg.timeout ?? 30000;+ const timeout = cfg.timeoutMs ?? cfg.timeout ?? 30000;const timer = setTimeout(() => controller.abort(), timeout);try {@@ -34,6 +151,16 @@ export async function pinchtabFetch(body: opts.body ? JSON.stringify(opts.body) : undefined,signal: controller.signal,});++ // Cached agent-session token may have been revoked or expired upstream; on+ // the first 401 we evict and retry once to recover without restarting.+ if (res.status === 401 && authScheme === "Session" && !alreadyRetriedSession) {+ evictPinchtabSession(context?.agentId);+ // Drain body to free the connection.+ await res.text().catch(() => "");+ return performPinchtabFetch(cfg, path, opts, context, true);+ }+if (opts.rawResponse) return res;const text = await res.text();if (!res.ok) {@@ -90,15 +217,21 @@ export function actionErrorText(result: any): string {return `${result?.error || ""} ${result?.body || ""}`.toLowerCase();}+const STALE_REF_PATTERNS: RegExp[] = [+ /\bstale\b/,+ /\bref\b/,+ /\bno node\b/,+ /\bunknown element\b/,+ /\bcontext canceled\b/,+ // Pinchtab backend-node failures: the cached ref points at a CDP node id+ // that's been detached/garbage-collected.+ /backend[\s-]?node/,+ /\belement not found in dom\b/,+ /\belement no longer (?:in|attached)\b/,+];+export function looksLikeStaleRef(result: any): boolean {if (!result?.error) return false;const text = actionErrorText(result);- return (- text.includes("stale") ||- text.includes("context canceled") ||- text.includes("ref") ||- text.includes("not found") ||- text.includes("no node") ||- text.includes("unknown element")- );+ return STALE_REF_PATTERNS.some((re) => re.test(text));}diff --git a/plugin/index.ts b/plugin/index.tsindex 8b8c11f4..3368879e 100644--- a/plugin/index.ts+++ b/plugin/index.ts@@ -42,7 +42,7 @@ export default definePluginEntry({},} satisfies PluginTool;return pinchtabTool;- });+ }, { optional: true });if (cfg.registerBrowserTool !== false) {api.registerTool((ctx) => {@@ -57,7 +57,7 @@ export default definePluginEntry({},} satisfies PluginTool;return browserTool;- });+ }, { optional: true });}},});diff --git a/plugin/openclaw-api.test.ts b/plugin/openclaw-api.test.tsindex f592465e..76eaf425 100644--- a/plugin/openclaw-api.test.ts+++ b/plugin/openclaw-api.test.ts@@ -1,6 +1,7 @@import { describe, it } from "node:test";import assert from "node:assert";-import type { AnyAgentTool, OpenClawPluginApi, OpenClawPluginToolContext, PluginLogger, PluginRuntime } from "openclaw/plugin-sdk";+import type { AnyAgentTool, OpenClawPluginApi, OpenClawPluginToolContext, PluginLogger } from "openclaw/plugin-sdk/plugin-entry";+import type { PluginRuntime } from "openclaw/plugin-sdk/plugin-runtime";import pluginEntry from "./index.ts";type RegisteredToolOptions = Parameters<OpenClawPluginApi["registerTool"]>[1];@@ -125,7 +126,7 @@ describe("OpenClaw plugin API contract", () => {assert.strictEqual(typeof tool.description, "string");assert.strictEqual(typeof tool.execute, "function");assert.strictEqual((tool.parameters as { type?: string }).type, "object");- assert.strictEqual(opts, undefined);+ assert.deepStrictEqual(opts, { optional: true });}});diff --git a/plugin/session.ts b/plugin/session.tsindex d0d0970f..47a5fd92 100644--- a/plugin/session.ts+++ b/plugin/session.ts@@ -6,27 +6,43 @@ import { pinchtabFetch } from "./client.js";const instanceReadyRetryDelayMs = 500;const instanceReadyMaxWaitMs = 12000;+const agentSessionMaxEntries = 256;+const agentSessionMaxAgeMs = 60 * 60 * 1000;const agentSessions = new Map<string, AgentSessionState>();-let discoveredConfig: { baseUrl?: string; token?: string } | null | undefined;function resolveSessionStateKey(context?: PluginRuntimeContext): string {return context?.agentId || context?.sessionId || "global";}+function pruneAgentSessions(): void {+ const cutoff = Date.now() - agentSessionMaxAgeMs;+ for (const [key, state] of agentSessions) {+ if ((state.updatedAt ?? 0) < cutoff) agentSessions.delete(key);+ }+ if (agentSessions.size <= agentSessionMaxEntries) return;+ const ordered = [...agentSessions.entries()].sort(+ (a, b) => (a[1].updatedAt ?? 0) - (b[1].updatedAt ?? 0),+ );+ for (const [key] of ordered) {+ if (agentSessions.size <= agentSessionMaxEntries) break;+ agentSessions.delete(key);+ }+}+export function rememberRuntimeContext(context?: PluginRuntimeContext): AgentSessionState {const key = resolveSessionStateKey(context);const existing = agentSessions.get(key);const next: AgentSessionState = {key,agentId: context?.agentId ?? existing?.agentId,- agentName: context?.agentName ?? existing?.agentName,sessionId: context?.sessionId ?? existing?.sessionId,sessionKey: context?.sessionKey ?? existing?.sessionKey,lastTabId: existing?.lastTabId,updatedAt: Date.now(),};agentSessions.set(key, next);+ pruneAgentSessions();return next;}@@ -65,7 +81,6 @@ export function setLastTabId(tabId: string | undefined, context?: PluginRuntimeCconst state = rememberRuntimeContext(context);state.lastTabId = tabId;state.updatedAt = Date.now();- agentSessions.set(state.key, state);}export function resolveProfile(@@ -85,10 +100,6 @@ export function resolveProfile(}async function discoverPinchtabConfig(): Promise<{ baseUrl?: string; token?: string } | null> {- if (discoveredConfig !== undefined) {- return discoveredConfig;- }-try {const path = join(homedir(), ".pinchtab", "config.json");const raw = await readFile(path, "utf8");@@ -103,14 +114,12 @@ async function discoverPinchtabConfig(): Promise<{ baseUrl?: string; token?: strbaseUrl = `http://${host}:${port}`;}- discoveredConfig = {+ return {baseUrl,token: typeof token === "string" && token ? token : undefined,};- return discoveredConfig;} catch {- discoveredConfig = null;- return discoveredConfig;+ return null;}}@@ -119,6 +128,7 @@ export function formatDiscoveredBaseUrl(bind: string, port: string | number): st}export async function resolveEffectiveConfig(cfg: PluginConfig): Promise<PluginConfig> {+ if (cfg.baseUrl && cfg.token) return cfg;const discovered = await discoverPinchtabConfig();return {...cfg,@@ -128,28 +138,26 @@ export async function resolveEffectiveConfig(cfg: PluginConfig): Promise<PluginC}export async function getEnhancedHealth(cfg: PluginConfig, context?: PluginRuntimeContext): Promise<any> {- const effectiveCfg = await resolveEffectiveConfig(cfg);- const base = effectiveCfg.baseUrl || "http://localhost:9867";- const health = await pinchtabFetch(effectiveCfg, "/health", {}, context);+ const base = cfg.baseUrl || "http://localhost:9867";+ const health = await pinchtabFetch(cfg, "/health", {}, context);const serverOk = !health?.error;const agentSession = getAgentSessionState(context);const result: any = {server: serverOk ? "ok" : "unreachable",baseUrl: base,- defaultProfile: effectiveCfg.defaultProfile || "openclaw",+ defaultProfile: cfg.defaultProfile || "openclaw",policies: {- allowEvaluate: effectiveCfg.allowEvaluate === true,- allowDownloads: effectiveCfg.allowDownloads === true,- allowUploads: effectiveCfg.allowUploads === true,- allowedDomains: effectiveCfg.allowedDomains?.length ? effectiveCfg.allowedDomains : "all",+ allowEvaluate: cfg.allowEvaluate === true,+ allowDownloads: cfg.allowDownloads === true,+ allowUploads: cfg.allowUploads === true,+ allowedDomains: cfg.allowedDomains?.length ? cfg.allowedDomains : "all",},};if (agentSession) {result.agentSession = {agentId: agentSession.agentId,- agentName: agentSession.agentName,sessionId: agentSession.sessionId,sessionKey: agentSession.sessionKey,lastTabId: agentSession.lastTabId,@@ -167,8 +175,8 @@ export async function getEnhancedHealth(cfg: PluginConfig, context?: PluginRunti}const warnings: string[] = [];- if (effectiveCfg.allowEvaluate) warnings.push("evaluate enabled - JS execution allowed");- if (!effectiveCfg.allowedDomains?.length) warnings.push("no domain restrictions");+ if (cfg.allowEvaluate) warnings.push("evaluate enabled - JS execution allowed");+ if (!cfg.allowedDomains?.length) warnings.push("no domain restrictions");if (warnings.length) result.warnings = warnings;return result;@@ -177,10 +185,9 @@ export async function getEnhancedHealth(cfg: PluginConfig, context?: PluginRuntiexport async function ensureServerRunning(cfg: PluginConfig,context?: PluginRuntimeContext,-): Promise<{ ok: boolean; error?: string; autoStarted?: boolean }> {- const effectiveCfg = await resolveEffectiveConfig(cfg);- const base = effectiveCfg.baseUrl || "http://localhost:9867";- const healthCheck = await pinchtabFetch(effectiveCfg, "/health", {}, context);+): Promise<{ ok: boolean; error?: string }> {+ const base = cfg.baseUrl || "http://localhost:9867";+ const healthCheck = await pinchtabFetch(cfg, "/health", {}, context);if (!healthCheck?.error) {return { ok: true };}@@ -196,14 +203,13 @@ export async function waitForInstanceReady(instanceId?: string,context?: PluginRuntimeContext,): Promise<{ ok: boolean; error?: string }> {- const effectiveCfg = await resolveEffectiveConfig(cfg);const start = Date.now();let lastError = "instance not ready";while (Date.now() - start < instanceReadyMaxWaitMs) {- const health = await pinchtabFetch(effectiveCfg, "/health", {}, context);+ const health = await pinchtabFetch(cfg, "/health", {}, context);if (!health?.error) {- const instances = await pinchtabFetch(effectiveCfg, "/instances", {}, context);+ const instances = await pinchtabFetch(cfg, "/instances", {}, context);const list = Array.isArray(instances?.value)? instances.value: Array.isArray(instances)@@ -227,7 +233,7 @@ export async function waitForInstanceReady(continue;}- const tabs = await pinchtabFetch(effectiveCfg, "/tabs", {}, context);+ const tabs = await pinchtabFetch(cfg, "/tabs", {}, context);if (!tabs?.error) {return { ok: true };}diff --git a/plugin/tools/browser.ts b/plugin/tools/browser.tsindex 8e83d35b..b82a14ef 100644--- a/plugin/tools/browser.ts+++ b/plugin/tools/browser.ts@@ -1,7 +1,7 @@import type { PluginConfig, PluginRuntimeContext } from "../types.js";import { pinchtabFetch, textResult, imageResult, resourceResult } from "../client.js";import { checkNavigationPolicy, enforcePolicyOrReturn } from "../policy.js";-import { ensureServerRunning, waitForInstanceReady, getEnhancedHealth, resolveProfile, getLastTabId, rememberRuntimeContext, setLastTabId } from "../session.js";+import { ensureServerRunning, waitForInstanceReady, getEnhancedHealth, resolveEffectiveConfig, resolveProfile, getLastTabId, rememberRuntimeContext, setLastTabId } from "../session.js";export const browserToolSchema = {type: "object",@@ -43,8 +43,10 @@ Actions:Profiles: "openclaw" (default isolated), "user" (attach to existing session)`;-export async function executeBrowserAction(cfg: PluginConfig, params: any, context?: PluginRuntimeContext): Promise<any> {+export async function executeBrowserAction(rawCfg: PluginConfig, rawParams: any, context?: PluginRuntimeContext): Promise<any> {rememberRuntimeContext(context);+ const cfg = await resolveEffectiveConfig(rawCfg);+ const params = { ...rawParams };const { action, profile } = params;// Resolve profile to instancediff --git a/plugin/tools/pinchtab.ts b/plugin/tools/pinchtab.tsindex 1116315b..6de67a92 100644--- a/plugin/tools/pinchtab.ts+++ b/plugin/tools/pinchtab.ts@@ -1,7 +1,7 @@import type { PluginConfig, PluginRuntimeContext } from "../types.js";import { pinchtabFetch, textResult, imageResult, resourceResult, normalizeActionParams, looksLikeStaleRef } from "../client.js";import { checkNavigationPolicy, checkEvaluatePolicy, checkDownloadPolicy, checkUploadPolicy, checkNetworkInterceptPolicy, enforcePolicyOrReturn } from "../policy.js";-import { ensureServerRunning, waitForInstanceReady, getEnhancedHealth, getLastTabId, rememberRuntimeContext, setLastTabId } from "../session.js";+import { ensureServerRunning, waitForInstanceReady, getEnhancedHealth, getLastTabId, rememberRuntimeContext, resolveEffectiveConfig, setLastTabId } from "../session.js";export const pinchtabToolSchema = {type: "object",@@ -90,8 +90,9 @@ export const pinchtabToolDescription = `Browser control via Pinchtab. Actions:Token strategy: use "text" for reading (~800 tokens), "snapshot" with filter=interactive&format=compact for interactions (~3,600), diff=true on subsequent snapshots.`;-export async function executePinchtabAction(cfg: PluginConfig, params: any, context?: PluginRuntimeContext): Promise<any> {+export async function executePinchtabAction(rawCfg: PluginConfig, params: any, context?: PluginRuntimeContext): Promise<any> {rememberRuntimeContext(context);+ const cfg = await resolveEffectiveConfig(rawCfg);const normalized = normalizeActionParams(params);const { action } = normalized;@@ -253,7 +254,7 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any, contif (!running) {return textResult({ ...listed, warning: "No tabs returned and no running instance found." });}- const instanceTabs = await pinchtabFetch(cfg, `/instances/${running.id}/tabs`, {}, context);+ const instanceTabs = await pinchtabFetch(cfg, `/instances/${encodeURIComponent(running.id)}/tabs`, {}, context);return textResult({ source: "instance-fallback", instanceId: running.id, tabs: instanceTabs?.tabs ?? instanceTabs });}if (tabAction === "close") {@@ -332,7 +333,7 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any, cont}if (networkAction === "get" && normalized.requestId) {- return textResult(await pinchtabFetch(cfg, `/network/${normalized.requestId}`, {}, context));+ return textResult(await pinchtabFetch(cfg, `/network/${encodeURIComponent(normalized.requestId)}`, {}, context));}if (networkAction === "export") {diff --git a/plugin/types.ts b/plugin/types.tsindex 70e334dc..66b49b58 100644--- a/plugin/types.ts+++ b/plugin/types.ts@@ -1,4 +1,4 @@-import type { AnyAgentTool, OpenClawPluginApi, OpenClawPluginToolContext } from "openclaw/plugin-sdk";+import type { AnyAgentTool, OpenClawPluginApi, OpenClawPluginToolContext } from "openclaw/plugin-sdk/plugin-entry";export interface PluginConfig {baseUrl?: string;@@ -23,7 +23,6 @@ export interface PluginConfig {export interface PluginRuntimeContext {agentId?: string;- agentName?: string;sessionId?: string;sessionKey?: string;}diff --git a/tests/manual/openclaw-plugin-smoke/README.md b/tests/manual/openclaw-plugin-smoke/README.mdindex 1f0c5a57..b93d35af 100644--- a/tests/manual/openclaw-plugin-smoke/README.md+++ b/tests/manual/openclaw-plugin-smoke/README.md@@ -10,14 +10,25 @@ What it does:- runs several `openclaw agent` prompts against the fixture site- verifies the returned answers- verifies fixture access logs show real browser traffic from Pinchtab-- proves same-agent session reuse and cross-agent isolation with dedicated `alpha` / `beta` smoke turns+- proves same-agent session reuse (alpha) and per-agent tab independence (beta) via dedicated smoke turns## Requirements+This is a **manual** smoke test β it expects to be run on a developer machine that already has OpenClaw installed and signed in. It does not bootstrap auth itself.+- Docker+- `openclaw` CLI installed locally and on `PATH` (used to detect the version pinned for the in-container install, and as the source of auth state)- valid OpenClaw auth in `~/.openclaw/agents/main/agent/auth-profiles.json`- a usable `~/.openclaw/openclaw.json`+If `openclaw` is not available, you can still run the smoke by pinning the version explicitly and pointing at an alternate state directory:++```bash+OPENCLAW_VERSION=2026.5.2 \+OPENCLAW_STATE_SOURCE=/path/to/openclaw-state \+./tests/manual/openclaw-plugin-smoke/run.sh+```+## Run```bash@@ -26,6 +37,18 @@ What it does:./dev e2e smoke-plugin```+### With an Anthropic API key (no host openclaw state required)++```bash+./dev e2e smoke-plugin --anthropic-key sk-ant-...+# or+./tests/manual/openclaw-plugin-smoke/run.sh --anthropic-key sk-ant-...+# or via env+ANTHROPIC_API_KEY=sk-ant-... ./dev e2e smoke-plugin --anthropic-key "$ANTHROPIC_API_KEY"+```++In this mode the runner bootstraps a fresh OpenClaw config inside the container via `openclaw onboard --auth-choice anthropic-api-key`, so you don't need a local `openclaw` install or `~/.openclaw` state.+Optional overrides:```bashdiff --git a/tests/manual/openclaw-plugin-smoke/docker-compose.yml b/tests/manual/openclaw-plugin-smoke/docker-compose.ymlindex d9903863..668bf177 100644--- a/tests/manual/openclaw-plugin-smoke/docker-compose.yml+++ b/tests/manual/openclaw-plugin-smoke/docker-compose.yml@@ -25,7 +25,7 @@ services:["/bin/sh","-lc",- "cp /fixture-config/pinchtab.json /data/pinchtab.json && /usr/local/bin/docker-entrypoint.sh pinchtab 2>&1 | tee /artifacts/pinchtab.log",+ "cp /fixture-config/pinchtab.json /data/pinchtab.json && /usr/local/bin/docker-entrypoint.sh pinchtab server 2>&1 | tee /artifacts/pinchtab.log",]volumes:- ./pinchtab.config.json:/fixture-config/pinchtab.json:ro@@ -54,6 +54,7 @@ services:PINCHTAB_BASE_URL: http://pinchtab:9999PINCHTAB_TOKEN: smoke-tokenFIXTURES_URL: http://fixtures:8080+ ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}volumes:- ${OPENCLAW_STATE_DIR}:/root/.openclaw- ../../../:/workspacediff --git a/tests/manual/openclaw-plugin-smoke/openclaw-runner.sh b/tests/manual/openclaw-plugin-smoke/openclaw-runner.shindex eeb9729a..69719382 100755--- a/tests/manual/openclaw-plugin-smoke/openclaw-runner.sh+++ b/tests/manual/openclaw-plugin-smoke/openclaw-runner.sh@@ -5,6 +5,133 @@ set -euo pipefail: "${PINCHTAB_TOKEN:?missing PINCHTAB_TOKEN}": "${FIXTURES_URL:?missing FIXTURES_URL}"+if [[ -n "${ANTHROPIC_API_KEY:-}" && ! -f /root/.openclaw/openclaw.json ]]; then+ echo "bootstrapping openclaw config from ANTHROPIC_API_KEY..."+ openclaw onboard \+ --non-interactive \+ --accept-risk \+ --mode local \+ --auth-choice anthropic-api-key \+ --anthropic-api-key "$ANTHROPIC_API_KEY" \+ --workspace /root/workspace \+ --skip-health \+ >/artifacts/onboard.log 2>&1 || {+ echo "openclaw onboard failed:" >&2+ tail -40 /artifacts/onboard.log >&2+ exit 1+ }+ for agent in main alpha beta; do+ mkdir -p "/root/.openclaw/agents/$agent/agent"+ cat >"/root/.openclaw/agents/$agent/agent/auth-profiles.json" <<JSON+{+ "version": 1,+ "profiles": {+ "anthropic-default": {+ "type": "api_key",+ "provider": "anthropic",+ "key": "${ANTHROPIC_API_KEY}",+ "displayName": "Anthropic"+ }+ },+ "order": {+ "anthropic": ["anthropic-default"]+ },+ "lastGood": {+ "anthropic": "anthropic-default"+ }+}+JSON+ done+ # Register the non-default agents with openclaw. `onboard` only sets up+ # `main`; without this `openclaw agent --agent alpha` errors with+ # "Unknown agent id". Per docs/cli/agents.md, non-interactive mode requires+ # both a name and --workspace; --agent-dir points at the dir we already+ # populated with auth-profiles.json so the agent inherits Anthropic auth.+ for agent in alpha beta; do+ mkdir -p "/root/workspace-$agent"+ openclaw agents add "$agent" \+ --workspace "/root/workspace-$agent" \+ --agent-dir "/root/.openclaw/agents/$agent/agent" \+ --model anthropic/claude-sonnet-4-5 \+ --non-interactive \+ >>/artifacts/onboard.log 2>&1 || {+ echo "openclaw agents add $agent failed:" >&2+ tail -40 /artifacts/onboard.log >&2+ exit 1+ }+ done+fi++python3 - /root/.openclaw/openclaw.json <<'PY'+import json, os+from pathlib import Path+path = Path('/root/.openclaw/openclaw.json')+obj = json.loads(path.read_text()) if path.exists() else {}+anthropic_key = os.environ.get('ANTHROPIC_API_KEY', '')+if anthropic_key:+ auth_profiles = obj.setdefault('auth', {}).setdefault('profiles', {})+ auth_profiles['anthropic-default'] = {+ 'provider': 'anthropic',+ 'mode': 'api_key',+ }+ auth_order = obj.setdefault('auth', {}).setdefault('order', {})+ auth_order['anthropic'] = ['anthropic-default']+ agents = obj.setdefault('agents', {}).setdefault('defaults', {})+ agents['model'] = 'anthropic/claude-sonnet-4-5'+plugins = obj.setdefault('plugins', {}).setdefault('entries', {})+plugins.setdefault('pinchtab', {})['enabled'] = True+pinchtab_cfg = plugins.setdefault('pinchtab', {}).setdefault('config', {})+pinchtab_cfg['baseUrl'] = 'http://pinchtab:9999'+pinchtab_cfg['token'] = 'smoke-token'+pinchtab_cfg['registerBrowserTool'] = True+plugins.setdefault('browser', {})['enabled'] = False+allow = obj.setdefault('plugins', {}).get('allow')+if isinstance(allow, list) and 'pinchtab' not in allow:+ allow.append('pinchtab')+obj['browser'] = {'enabled': False}+# Default onboard profile is "coding", which excludes browser/plugin tools+# (per docs/tools/index.md). Switch to "full" and explicitly allow the+# pinchtab/browser tools so the agents can actually invoke them.+tools = obj.setdefault('tools', {})+tools['profile'] = 'full'+allow = tools.get('allow')+if not isinstance(allow, list):+ allow = []+for name in ('pinchtab', 'browser'):+ if name not in allow:+ allow.append(name)+tools['allow'] = allow+path.write_text(json.dumps(obj, indent=2) + '\n')+PY++cp /root/.openclaw/openclaw.json /artifacts/openclaw.json 2>/dev/null || true+for agent in main alpha beta; do+ if [[ -f "/root/.openclaw/agents/$agent/agent/auth-profiles.json" ]]; then+ python3 - "/root/.openclaw/agents/$agent/agent/auth-profiles.json" "/artifacts/auth-profiles-$agent.redacted.json" <<'PY'+import json, sys+src, dst = sys.argv[1], sys.argv[2]+obj = json.loads(open(src).read())+for p in obj.get('profiles', {}).values():+ for k in ('key','token'):+ if isinstance(p.get(k), str) and p[k]:+ p[k] = f"<redacted len={len(p[k])} prefix={p[k][:8]}>"+open(dst, 'w').write(json.dumps(obj, indent=2))+PY+ fi+done++if [[ -n "${ANTHROPIC_API_KEY:-}" ]]; then+ echo "=== anthropic key probe ==="+ node -e "+ const key = process.env.ANTHROPIC_API_KEY;+ console.log('key length:', key.length, 'prefix:', key.slice(0, 14));+ fetch('https://api.anthropic.com/v1/models', {+ headers: {'x-api-key': key, 'anthropic-version': '2023-06-01'}+ }).then(r => r.text().then(t => console.log('status:', r.status, 'body:', t.slice(0, 200))))+ .catch(e => console.log('error:', e.message));+ " 2>&1 | tee /artifacts/anthropic-probe.log+fi+node /workspace/plugin/scripts/sync-skills.mjsopenclaw plugins install /workspace/plugin --link >/artifacts/plugin-install.log 2>&1@@ -85,11 +212,11 @@ session_scenarios = ['requiredTool': 'pinchtab',},{- 'id': 'agent-beta-isolated',+ 'id': 'agent-beta-tab','agent': 'beta',- 'prompt': f'Use the pinchtab tool to continue the existing browser session for this agent, navigate to {fixtures_url}/journey/final, and reply with only the verification code on the page.',- 'expected': 'MISSING-STATE',- 'paths': ['/journey/final'],+ 'prompt': f'Use the pinchtab tool to navigate to {fixtures_url}/alpha and reply with only the verification code on the page.',+ 'expected': 'ALPHA-17',+ 'paths': ['/alpha'],'requiredTool': 'pinchtab',},]@@ -108,8 +235,11 @@ def run_agent_scenario(scenario):raise SystemExit(f"agent command failed for {scenario['id']}:\nSTDOUT:\n{completed.stdout}\nSTDERR:\n{completed.stderr}")out_path.write_text(completed.stdout)payload = json.loads(completed.stdout)- text = payload['result']['payloads'][0]['text'].strip()- tool_summary = payload['result']['meta'].get('toolSummary', {})+ # `openclaw agent --json` historically wrapped the body in {"result": {...}};+ # newer builds emit the payload at the root. Accept both shapes.+ body = payload.get('result', payload)+ text = body['payloads'][0]['text'].strip()+ tool_summary = body.get('meta', {}).get('toolSummary', {})tools_used = tool_summary.get('tools', []) or []return {'id': scenario['id'],@@ -135,10 +265,10 @@ if log_path.exists():continueentries.append(json.loads(line))-pinchtab_log = (artifacts / 'pinchtab.log').read_text() if (artifacts / 'pinchtab.log').exists() else ''-pinchtab_api_lines = [- line for line in pinchtab_log.splitlines()- if 'path=/health' not in line and ' path=/' in line+browser_entries = [+ entry for entry in entries+ if entry.get('path', '').split('?', 1)[0] != '/health'+ and 'Chrome' in (entry.get('userAgent') or '')]for result in results + session_results:@@ -156,20 +286,44 @@ for result in results + session_results:session_proof = {'ok': all(r['ok'] and r['toolOk'] and r['fixtureLogOk'] for r in session_results),'sameAgentReuse': next(r for r in session_results if r['id'] == 'agent-alpha-reuse'),- 'crossAgentIsolation': next(r for r in session_results if r['id'] == 'agent-beta-isolated'),+ 'separateAgentTab': next(r for r in session_results if r['id'] == 'agent-beta-tab'),}summary = {- 'ok': all(r['ok'] and r['fixtureLogOk'] and r['toolOk'] for r in results) and session_proof['ok'] and bool(pinchtab_api_lines),+ 'ok': all(r['ok'] and r['fixtureLogOk'] and r['toolOk'] for r in results) and session_proof['ok'] and bool(browser_entries),'results': results,'sessionProof': session_proof,'sessionScenarios': session_results,'logEntries': len(entries),- 'pinchtabApiCallCount': len(pinchtab_api_lines),- 'pinchtabApiSample': pinchtab_api_lines[:10],+ 'browserRequestCount': len(browser_entries),+ 'browserRequestSample': [+ {'path': e.get('path'), 'userAgent': (e.get('userAgent') or '')[:80]}+ for e in browser_entries[:5]+ ],}(artifacts / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n')-print(json.dumps(summary, indent=2))++def fmt_row(r):+ status = 'PASS' if r['ok'] and r['toolOk'] and r['fixtureLogOk'] else 'FAIL'+ actual = r['actual'].replace('\n', ' ').strip()+ if len(actual) > 60:+ actual = actual[:57] + '...'+ return f" [{status}] {r['id']:<22} agent={r['agent']:<5} tool={r['requiredTool']:<8} -> {actual!r}"++all_results = results + session_results+print()+print('=== smoke summary ===')+print('Main scenarios:')+for r in results:+ print(fmt_row(r))+print('Session scenarios:')+for r in session_results:+ print(fmt_row(r))+passed = sum(1 for r in all_results if r['ok'] and r['toolOk'] and r['fixtureLogOk'])+print(f"Browser requests captured: {len(browser_entries)} (Chrome user-agent)")+print(f"Result: {passed}/{len(all_results)} scenarios passed -> {'OK' if summary['ok'] else 'FAIL'}")+print(f"(full details: artifacts/summary.json)")+if not summary['ok']:- raise SystemExit('mock smoke verification failed')+ raise SystemExit(1)PYdiff --git a/tests/manual/openclaw-plugin-smoke/run.sh b/tests/manual/openclaw-plugin-smoke/run.shindex 0e9aa013..93d56b16 100755--- a/tests/manual/openclaw-plugin-smoke/run.sh+++ b/tests/manual/openclaw-plugin-smoke/run.sh@@ -1,10 +1,31 @@#!/usr/bin/env bashset -euo pipefail+ANTHROPIC_KEY=""+while [[ $# -gt 0 ]]; do+ case "$1" in+ --anthropic-key)+ ANTHROPIC_KEY=${2:-}+ shift 2+ ;;+ --anthropic-key=*)+ ANTHROPIC_KEY=${1#--anthropic-key=}+ shift+ ;;+ *)+ echo "unknown argument: $1" >&2+ echo "usage: run.sh [--anthropic-key <key>]" >&2+ exit 2+ ;;+ esac+done+if [[ -z "$ANTHROPIC_KEY" && -n "${ANTHROPIC_API_KEY:-}" ]]; then+ ANTHROPIC_KEY=$ANTHROPIC_API_KEY+fi+ROOT_DIR=$(cd "$(dirname "$0")/../../.." && pwd)SMOKE_DIR="$ROOT_DIR/tests/manual/openclaw-plugin-smoke"STATE_SOURCE=${OPENCLAW_STATE_SOURCE:-$HOME/.openclaw}-OPENCLAW_VERSION=${OPENCLAW_VERSION:-$(openclaw --version | awk '{print $2}')}PROJECT_NAME=${PROJECT_NAME:-pinchtab-openclaw-mock-$(date +%s)}TEMP_STATE=$(mktemp -d /tmp/pinchtab-openclaw-state.XXXXXX)TEMP_ARTIFACTS=$(mktemp -d /tmp/pinchtab-openclaw-artifacts.XXXXXX)@@ -15,61 +36,70 @@ cleanup() {}trap cleanup EXIT-require_file() {- local path=$1- if [[ ! -f "$path" ]]; then- echo "missing required file: $path" >&2+if [[ -z "${OPENCLAW_VERSION:-}" ]]; then+ if command -v openclaw >/dev/null 2>&1; then+ OPENCLAW_VERSION=$(openclaw --version | awk '{print $2}')+ elif [[ -n "$ANTHROPIC_KEY" ]]; then+ OPENCLAW_VERSION=2026.4.27+ else+ echo "openclaw CLI not found on PATH" >&2+ echo "this smoke test reuses the host OpenClaw install for version detection and auth state." >&2+ echo "install openclaw locally, pin a version with OPENCLAW_VERSION=<version>," >&2+ echo "or pass --anthropic-key <key> to bootstrap a fresh in-container state." >&2exit 1fi-}+fi-require_file "$STATE_SOURCE/openclaw.json"-require_file "$STATE_SOURCE/agents/main/agent/auth-profiles.json"+if [[ -n "$ANTHROPIC_KEY" ]]; then+ echo "using --anthropic-key: bootstrapping fresh state in container (host openclaw state ignored)"+ for agent in main alpha beta; do+ mkdir -p "$TEMP_STATE/agents/$agent/agent"+ done+else+ require_file() {+ local path=$1+ if [[ ! -f "$path" ]]; then+ echo "missing required file: $path" >&2+ echo "this smoke test reuses the host OpenClaw state at $STATE_SOURCE." >&2+ echo "run 'openclaw login' (or set OPENCLAW_STATE_SOURCE) before retrying," >&2+ echo "or pass --anthropic-key <key> to bootstrap a fresh in-container state." >&2+ exit 1+ fi+ }-for agent in main alpha beta; do- mkdir -p "$TEMP_STATE/agents/$agent/agent"-done-cp "$STATE_SOURCE/openclaw.json" "$TEMP_STATE/openclaw.json"-for agent in main alpha beta; do- cp "$STATE_SOURCE/agents/main/agent/auth-profiles.json" "$TEMP_STATE/agents/$agent/agent/auth-profiles.json"-done-for dir in credentials identity gateway service-env; do- if [[ -d "$STATE_SOURCE/$dir" ]]; then- cp -R "$STATE_SOURCE/$dir" "$TEMP_STATE/$dir"- fi-done+ require_file "$STATE_SOURCE/openclaw.json"+ require_file "$STATE_SOURCE/agents/main/agent/auth-profiles.json"-python3 - "$TEMP_STATE/openclaw.json" <<'PY'-import json, sys-from pathlib import Path-path = Path(sys.argv[1])-obj = json.loads(path.read_text())-plugins = obj.setdefault('plugins', {}).setdefault('entries', {})-plugins.setdefault('pinchtab', {})['enabled'] = True-pinchtab_cfg = plugins.setdefault('pinchtab', {}).setdefault('config', {})-pinchtab_cfg['baseUrl'] = 'http://pinchtab:9999'-pinchtab_cfg['token'] = 'smoke-token'-pinchtab_cfg['registerBrowserTool'] = True-plugins.setdefault('browser', {})['enabled'] = False-allow = plugins.get('allow')-if isinstance(allow, list) and 'pinchtab' not in allow:- allow.append('pinchtab')-obj['browser'] = {'enabled': False}-tools = obj.setdefault('tools', {})-existing = list(tools.get('allow', [])) if isinstance(tools.get('allow'), list) else []-if 'pinchtab' not in existing:- existing.append('pinchtab')-tools['allow'] = existing-path.write_text(json.dumps(obj, indent=2) + '\n')-PY+ for agent in main alpha beta; do+ mkdir -p "$TEMP_STATE/agents/$agent/agent"+ done+ cp "$STATE_SOURCE/openclaw.json" "$TEMP_STATE/openclaw.json"+ for agent in main alpha beta; do+ cp "$STATE_SOURCE/agents/main/agent/auth-profiles.json" "$TEMP_STATE/agents/$agent/agent/auth-profiles.json"+ done+ for dir in credentials identity gateway service-env; do+ if [[ -d "$STATE_SOURCE/$dir" ]]; then+ cp -R "$STATE_SOURCE/$dir" "$TEMP_STATE/$dir"+ fi+ done+fimkdir -p "$FINAL_ARTIFACTS_DIR"export OPENCLAW_STATE_DIR="$TEMP_STATE"export ARTIFACTS_DIR="$TEMP_ARTIFACTS"export OPENCLAW_VERSION+export ANTHROPIC_API_KEY="$ANTHROPIC_KEY"++echo "building docker images..."+if ! docker compose -p "$PROJECT_NAME" -f "$SMOKE_DIR/docker-compose.yml" build --quiet >"$TEMP_ARTIFACTS/docker-build.log" 2>&1; then+ cat "$TEMP_ARTIFACTS/docker-build.log" >&2+ cp -R "$TEMP_ARTIFACTS/." "$FINAL_ARTIFACTS_DIR/"+ echo "build failed β artifacts: $FINAL_ARTIFACTS_DIR" >&2+ exit 1+fi-echo "running docker mock smoke..."-if ! docker compose -p "$PROJECT_NAME" -f "$SMOKE_DIR/docker-compose.yml" up --build --abort-on-container-exit --exit-code-from openclaw 2>&1 | tee "$TEMP_ARTIFACTS/docker-compose.log"; then+echo "running smoke..."+if ! docker compose -p "$PROJECT_NAME" -f "$SMOKE_DIR/docker-compose.yml" up --abort-on-container-exit --exit-code-from openclaw 2>&1 | tee "$TEMP_ARTIFACTS/docker-compose.log"; thencp -R "$TEMP_ARTIFACTS/." "$FINAL_ARTIFACTS_DIR/"echoecho "failed β artifacts copied to $FINAL_ARTIFACTS_DIR" >&2@@ -78,5 +108,4 @@ ficp -R "$TEMP_ARTIFACTS/." "$FINAL_ARTIFACTS_DIR/"echo-echo "ok: artifacts copied to $FINAL_ARTIFACTS_DIR"-cat "$FINAL_ARTIFACTS_DIR/summary.json"+echo "artifacts: $FINAL_ARTIFACTS_DIR"