High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: cap stream connections and remove activity state dir overrides
Luigi Agosti1687ac308e3d
diff --git a/.github/workflows/reusable-publish-skill.yml b/.github/workflows/reusable-publish-skill.ymlindex cc0dc5f9..bf26c87c 100644--- a/.github/workflows/reusable-publish-skill.yml+++ b/.github/workflows/reusable-publish-skill.yml@@ -32,11 +32,14 @@ jobs:- name: Resolve versionid: version+ env:+ INPUT_VERSION: ${{ inputs.version }}+ DISPATCH_VERSION: ${{ github.event.inputs.version }}run: |- if [ -n "${{ inputs.version }}" ]; then- VERSION="${{ inputs.version }}"- elif [ -n "${{ github.event.inputs.version }}" ]; then- VERSION="${{ github.event.inputs.version }}"+ if [ -n "$INPUT_VERSION" ]; then+ VERSION="$INPUT_VERSION"+ elif [ -n "$DISPATCH_VERSION" ]; then+ VERSION="$DISPATCH_VERSION"elseVERSION=${GITHUB_REF_NAME#v}fi@@ -52,8 +55,9 @@ jobs:CLAWHUB_TOKEN: ${{ secrets.CLAWHUB_TOKEN }}- name: Publish skill+ env:+ VERSION: ${{ steps.version.outputs.value }}run: |- VERSION="${{ steps.version.outputs.value }}"clawhub publish skills/pinchtab \--slug pinchtab \--name "Pinchtab" \diff --git a/dashboard/src/stores/useAppStore.test.ts b/dashboard/src/stores/useAppStore.test.tsindex f4ef90ca..03321be2 100644--- a/dashboard/src/stores/useAppStore.test.ts+++ b/dashboard/src/stores/useAppStore.test.ts@@ -223,6 +223,40 @@ describe("useAppStore", () => {expect.objectContaining({ id: "evt_live" }),]);});++ it("keeps only the 20 most recent agent caches", () => {+ for (let i = 0; i < 22; i++) {+ const agentId = `agent_${i}`;+ const timestamp = new Date(Date.UTC(2024, 0, 1, 0, i)).toISOString();+ useAppStore.getState().upsertAgentFromEvent({+ id: `evt_${i}`,+ agentId,+ channel: "tool_call",+ type: "navigate",+ method: "POST",+ path: "/navigate",+ timestamp,+ } as any);+ useAppStore.getState().appendAgentEvent({+ id: `evt_cache_${i}`,+ agentId,+ channel: "tool_call",+ type: "navigate",+ method: "POST",+ path: "/navigate",+ timestamp,+ } as any);+ }++ const { agents, agentEventsById } = useAppStore.getState();+ expect(agents).toHaveLength(20);+ expect(Object.keys(agentEventsById)).toHaveLength(20);+ expect(agents.map((agent) => agent.id)).not.toContain("agent_0");+ expect(agents.map((agent) => agent.id)).not.toContain("agent_1");+ expect(agentEventsById.agent_0).toBeUndefined();+ expect(agentEventsById.agent_1).toBeUndefined();+ expect(agentEventsById.agent_21).toBeDefined();+ });});describe("settings", () => {diff --git a/dashboard/src/stores/useAppStore.ts b/dashboard/src/stores/useAppStore.tsindex 1bb31673..d76434ef 100644--- a/dashboard/src/stores/useAppStore.ts+++ b/dashboard/src/stores/useAppStore.ts@@ -90,6 +90,8 @@ const defaultSettings: Settings = {};const SETTINGS_KEY = "pinchtab_settings";+const MAX_AGENT_CACHE_SIZE = 20;+const MAX_AGENT_EVENTS_PER_AGENT = 200;function loadSettings(): Settings {try {@@ -111,6 +113,62 @@ function saveSettings(settings: Settings) {}}+function agentActivityTime(agent: Agent): number {+ return new Date(agent.lastActivity || agent.connectedAt).getTime();+}++function normalizeAgents(agents: Agent[]): Agent[] {+ const deduped = new Map<string, Agent>();+ for (const agent of agents) {+ deduped.set(agent.id, agent);+ }+ return [...deduped.values()].sort(+ (a, b) => agentActivityTime(b) - agentActivityTime(a),+ );+}++function retainedAgentIds(+ agents: Agent[],+ selectedAgentId: string | null,+ extraAgentIds: string[] = [],+): string[] {+ const ids: string[] = [];+ const seen = new Set<string>();+ const push = (id: string | null | undefined) => {+ const normalized = id?.trim();+ if (+ !normalized ||+ seen.has(normalized) ||+ ids.length >= MAX_AGENT_CACHE_SIZE+ ) {+ return;+ }+ seen.add(normalized);+ ids.push(normalized);+ };++ push(selectedAgentId);+ for (const id of extraAgentIds) {+ push(id);+ }+ for (const agent of normalizeAgents(agents)) {+ push(agent.id);+ }+ return ids;+}++function pruneAgentEventsById(+ agentEventsById: Record<string, ActivityEvent[]>,+ retainedIds: string[],+): Record<string, ActivityEvent[]> {+ const retained = new Set(retainedIds);+ return Object.fromEntries(+ Object.entries(agentEventsById).filter(([agentId]) =>+ retained.has(agentId),+ ),+ );+}+export const useAppStore = create<AppState>((set) => ({// Profilesprofiles: [],@@ -200,7 +258,19 @@ export const useAppStore = create<AppState>((set) => ({agents: [],selectedAgentId: null,agentEventsById: {},- setAgents: (agents) => set({ agents }),+ setAgents: (agents) =>+ set((state) => {+ const normalized = normalizeAgents(agents);+ const retainedIds = retainedAgentIds(normalized, state.selectedAgentId);+ const retained = new Set(retainedIds);+ return {+ agents: normalized.filter((agent) => retained.has(agent.id)),+ agentEventsById: pruneAgentEventsById(+ state.agentEventsById,+ retainedIds,+ ),+ };+ }),upsertAgentFromEvent: (event) =>set((state) => {const agentId = event.agentId?.trim();@@ -210,58 +280,81 @@ export const useAppStore = create<AppState>((set) => ({const existing = state.agents.find((agent) => agent.id === agentId);if (!existing) {+ const nextAgents = normalizeAgents([+ {+ id: agentId,+ name: agentId,+ connectedAt: event.timestamp,+ lastActivity: event.timestamp,+ requestCount: 1,+ },+ ...state.agents,+ ]);+ const retainedIds = retainedAgentIds(+ nextAgents,+ state.selectedAgentId,+ [agentId],+ );+ const retained = new Set(retainedIds);return {- agents: [- {- id: agentId,- name: agentId,- connectedAt: event.timestamp,- lastActivity: event.timestamp,- requestCount: 1,- },- ...state.agents,- ],+ agents: nextAgents.filter((agent) => retained.has(agent.id)),+ agentEventsById: pruneAgentEventsById(+ state.agentEventsById,+ retainedIds,+ ),};}+ const nextAgents = normalizeAgents(+ state.agents.map((agent) =>+ agent.id === agentId+ ? {+ ...agent,+ lastActivity: event.timestamp,+ requestCount: agent.requestCount + 1,+ }+ : agent,+ ),+ );+ const retainedIds = retainedAgentIds(nextAgents, state.selectedAgentId, [+ agentId,+ ]);+ const retained = new Set(retainedIds);return {- agents: state.agents- .map((agent) =>- agent.id === agentId- ? {- ...agent,- lastActivity: event.timestamp,- requestCount: agent.requestCount + 1,- }- : agent,- )- .sort(- (a, b) =>- new Date(b.lastActivity || b.connectedAt).getTime() -- new Date(a.lastActivity || a.connectedAt).getTime(),- ),+ agents: nextAgents.filter((agent) => retained.has(agent.id)),+ agentEventsById: pruneAgentEventsById(+ state.agentEventsById,+ retainedIds,+ ),};}),hydrateAgentEvents: (agentId, events) =>- set((state) => ({- agentEventsById: {- ...state.agentEventsById,- [agentId]: [...(state.agentEventsById[agentId] ?? []), ...events]- .reduce<ActivityEvent[]>((merged, event) => {- if (merged.some((existing) => existing.id === event.id)) {+ set((state) => {+ const retainedIds = retainedAgentIds(+ state.agents,+ state.selectedAgentId,+ [agentId],+ );+ return {+ agentEventsById: {+ ...pruneAgentEventsById(state.agentEventsById, retainedIds),+ [agentId]: [...(state.agentEventsById[agentId] ?? []), ...events]+ .reduce<ActivityEvent[]>((merged, event) => {+ if (merged.some((existing) => existing.id === event.id)) {+ return merged;+ }+ merged.push(event);return merged;- }- merged.push(event);- return merged;- }, [])- .sort(- (left, right) =>- new Date(left.timestamp).getTime() -- new Date(right.timestamp).getTime(),- )- .slice(-500),- },- })),+ }, [])+ .sort(+ (left, right) =>+ new Date(left.timestamp).getTime() -+ new Date(right.timestamp).getTime(),+ )+ .slice(-MAX_AGENT_EVENTS_PER_AGENT),+ },+ };+ }),appendAgentEvent: (event) =>set((state) => {const agentId = event.agentId?.trim();@@ -278,10 +371,15 @@ export const useAppStore = create<AppState>((set) => ({new Date(left.timestamp).getTime() -new Date(right.timestamp).getTime(),)- .slice(-500);+ .slice(-MAX_AGENT_EVENTS_PER_AGENT);+ const retainedIds = retainedAgentIds(+ state.agents,+ state.selectedAgentId,+ [agentId],+ );return {agentEventsById: {- ...state.agentEventsById,+ ...pruneAgentEventsById(state.agentEventsById, retainedIds),[agentId]: next,},};diff --git a/internal/config/config_file.go b/internal/config/config_file.goindex a61722de..f5ff26c2 100644--- a/internal/config/config_file.go+++ b/internal/config/config_file.go@@ -401,7 +401,6 @@ func (fc FileConfig) MarshalJSON() ([]byte, error) {Enabled: fc.Observability.Activity.Enabled,SessionIdleSec: fc.Observability.Activity.SessionIdleSec,RetentionDays: fc.Observability.Activity.RetentionDays,- StateDir: fc.Observability.Activity.StateDir,},},Sessions: sessionsFileConfigJSON{@@ -465,7 +464,6 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {activityEnabled := cfg.Observability.Activity.EnabledactivitySessionIdleSec := cfg.Observability.Activity.SessionIdleSecactivityRetentionDays := cfg.Observability.Activity.RetentionDays- activityStateDir := cfg.Observability.Activity.StateDirdashboardSessionPersist := cfg.Sessions.Dashboard.PersistdashboardSessionIdleSec := int(cfg.Sessions.Dashboard.IdleTimeout / time.Second)dashboardSessionMaxLifetimeSec := int(cfg.Sessions.Dashboard.MaxLifetime / time.Second)@@ -565,7 +563,6 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {Enabled: &activityEnabled,SessionIdleSec: &activitySessionIdleSec,RetentionDays: &activityRetentionDays,- StateDir: activityStateDir,},},Sessions: SessionsFileConfig{diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex e924a1a6..5737a1a2 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -262,9 +262,6 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {if fc.Observability.Activity.RetentionDays != nil {cfg.Observability.Activity.RetentionDays = *fc.Observability.Activity.RetentionDays}- if fc.Observability.Activity.StateDir != "" {- cfg.Observability.Activity.StateDir = fc.Observability.Activity.StateDir- }if fc.Sessions.Dashboard.Persist != nil {cfg.Sessions.Dashboard.Persist = *fc.Sessions.Dashboard.Persist}diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.goindex 28d03f15..b44bbd45 100644--- a/internal/config/config_load_test.go+++ b/internal/config/config_load_test.go@@ -197,7 +197,7 @@ func TestConfigFileWithNestedValues(t *testing.T) {}}-func TestLoadConfigActivityStateDir(t *testing.T) {+func TestLoadConfigActivityStateDirIgnoresConfigOverride(t *testing.T) {clearConfigEnvVars(t)tmpDir := t.TempDir()@@ -220,11 +220,11 @@ func TestLoadConfigActivityStateDir(t *testing.T) {}cfg := Load()- if cfg.Observability.Activity.StateDir != sharedActivityDir {- t.Fatalf("Observability.Activity.StateDir = %q, want %q", cfg.Observability.Activity.StateDir, sharedActivityDir)+ if cfg.Observability.Activity.StateDir != "" {+ t.Fatalf("Observability.Activity.StateDir = %q, want empty", cfg.Observability.Activity.StateDir)}- if cfg.ActivityStateDir() != sharedActivityDir {- t.Fatalf("ActivityStateDir() = %q, want %q", cfg.ActivityStateDir(), sharedActivityDir)+ if cfg.ActivityStateDir() != "/tmp/profile-state" {+ t.Fatalf("ActivityStateDir() = %q, want %q", cfg.ActivityStateDir(), "/tmp/profile-state")}}diff --git a/internal/config/config_methods.go b/internal/config/config_methods.goindex f2838986..f3c6ad9b 100644--- a/internal/config/config_methods.go+++ b/internal/config/config_methods.go@@ -32,8 +32,5 @@ func (cfg *RuntimeConfig) ActivityStateDir() string {if cfg == nil {return ""}- if cfg.Observability.Activity.StateDir != "" {- return cfg.Observability.Activity.StateDir- }return cfg.StateDir}diff --git a/internal/dashboard/dashboard.go b/internal/dashboard/dashboard.goindex 14cc6c8d..c8f2d8a9 100644--- a/internal/dashboard/dashboard.go+++ b/internal/dashboard/dashboard.go@@ -95,6 +95,10 @@ func (d *Dashboard) SetInstanceLister(il InstanceLister) {// RecordActivityEvent converts a backend activity record into a live tool-call event.func (d *Dashboard) RecordActivityEvent(evt activity.Event) {+ d.recordEvents([]apiTypes.ActivityEvent{activityEventToLiveEvent(evt)})+}++func activityEventToLiveEvent(evt activity.Event) apiTypes.ActivityEvent {details := map[string]any{"status": evt.Status,"durationMs": evt.DurationMs,@@ -136,7 +140,7 @@ func (d *Dashboard) RecordActivityEvent(evt activity.Event) {details["action"] = evt.Action}- d.RecordEvent(apiTypes.ActivityEvent{+ return apiTypes.ActivityEvent{ID: evt.RequestID,AgentID: agentIDOrAnonymous(evt.AgentID),Channel: "tool_call",@@ -145,50 +149,12 @@ func (d *Dashboard) RecordActivityEvent(evt activity.Event) {Path: evt.Path,Timestamp: evt.Timestamp,Details: details,- })+ }}// RecordEvent records an activity event, updates the live agent summary, and broadcasts to SSE subscribers.func (d *Dashboard) RecordEvent(evt apiTypes.ActivityEvent) {- if evt.ID == "" {- evt.ID = generateID()- }- if evt.Timestamp.IsZero() {- evt.Timestamp = time.Now().UTC()- }- if evt.Channel == "" {- evt.Channel = "tool_call"- }- if evt.AgentID == "" {- evt.AgentID = "anonymous"- }-- d.mu.Lock()- if _, ok := d.seenEventIDs[evt.ID]; ok {- d.mu.Unlock()- return- }- d.rememberEventIDLocked(evt.ID)- d.upsertAgentLocked(evt)- if len(d.recentEvents) >= d.maxEvents {- copy(d.recentEvents, d.recentEvents[1:])- d.recentEvents[len(d.recentEvents)-1] = evt- } else {- d.recentEvents = append(d.recentEvents, evt)- }-- chans := make([]chan apiTypes.ActivityEvent, 0, len(d.activityConns))- for ch := range d.activityConns {- chans = append(chans, ch)- }- d.mu.Unlock()-- for _, ch := range chans {- select {- case ch <- evt:- default:- }- }+ d.recordEvents([]apiTypes.ActivityEvent{evt})}func (d *Dashboard) upsertAgentLocked(evt apiTypes.ActivityEvent) {@@ -280,6 +246,7 @@ func (d *Dashboard) IngestPersistedAgentActivity(rec activity.Recorder, since ti}latest := since+ batch := make([]apiTypes.ActivityEvent, 0, len(events))for _, evt := range events {if evt.Timestamp.After(latest) {latest = evt.Timestamp@@ -290,8 +257,9 @@ func (d *Dashboard) IngestPersistedAgentActivity(rec activity.Recorder, since tiif !shouldTrackPersistedAgentActivity(evt) {continue}- d.RecordActivityEvent(evt)+ batch = append(batch, activityEventToLiveEvent(evt))}+ d.recordEvents(batch)return latest, nil}@@ -595,6 +563,61 @@ func (d *Dashboard) rememberEventIDLocked(id string) {delete(d.seenEventIDs, evicted)}+func normalizeEvent(evt apiTypes.ActivityEvent) apiTypes.ActivityEvent {+ if evt.ID == "" {+ evt.ID = generateID()+ }+ if evt.Timestamp.IsZero() {+ evt.Timestamp = time.Now().UTC()+ }+ if evt.Channel == "" {+ evt.Channel = "tool_call"+ }+ if evt.AgentID == "" {+ evt.AgentID = "anonymous"+ }+ return evt+}++func (d *Dashboard) recordEvents(events []apiTypes.ActivityEvent) {+ if d == nil || len(events) == 0 {+ return+ }++ d.mu.Lock()+ broadcast := make([]apiTypes.ActivityEvent, 0, len(events))+ for _, raw := range events {+ evt := normalizeEvent(raw)+ if _, ok := d.seenEventIDs[evt.ID]; ok {+ continue+ }+ d.rememberEventIDLocked(evt.ID)+ d.upsertAgentLocked(evt)+ if len(d.recentEvents) >= d.maxEvents {+ copy(d.recentEvents, d.recentEvents[1:])+ d.recentEvents[len(d.recentEvents)-1] = evt+ } else {+ d.recentEvents = append(d.recentEvents, evt)+ }+ broadcast = append(broadcast, evt)+ }++ chans := make([]chan apiTypes.ActivityEvent, 0, len(d.activityConns))+ for ch := range d.activityConns {+ chans = append(chans, ch)+ }+ d.mu.Unlock()++ for _, evt := range broadcast {+ for _, ch := range chans {+ select {+ case ch <- evt:+ default:+ }+ }+ }+}+func classifyActivityType(evt activity.Event) string {if evt.Action != "" {switch evt.Action {diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.goindex 207f3ba3..e32ce9e0 100644--- a/internal/handlers/middleware.go+++ b/internal/handlers/middleware.go@@ -23,6 +23,13 @@ var (metricRequestLatencyN uint64metricRateLimited uint64metricStaleRefRetries uint64++ streamMu sync.Mutex+ streamConnections = map[string]int{}+)++const (+ maxConcurrentStreamRequestsPerHost = 8)const (@@ -376,6 +383,15 @@ func RateLimitMiddleware(next http.Handler) http.Handler {startRateLimiterJanitor(rateLimitWindow, evictionInterval)return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if isLongLivedStreamRequest(r) {+ host := authn.ClientIP(r)+ if !acquireStreamConnection(host) {+ atomic.AddUint64(&metricRateLimited, 1)+ httpx.ErrorCode(w, 429, "stream_limit_reached", "too many concurrent streaming connections", true, map[string]any{+ "maxConcurrent": maxConcurrentStreamRequestsPerHost,+ })+ return+ }+ defer releaseStreamConnection(host)next.ServeHTTP(w, r)return}@@ -422,6 +438,29 @@ func isLongLivedStreamRequest(r *http.Request) bool {}}+func acquireStreamConnection(host string) bool {+ streamMu.Lock()+ defer streamMu.Unlock()++ if streamConnections[host] >= maxConcurrentStreamRequestsPerHost {+ return false+ }+ streamConnections[host]+++ return true+}++func releaseStreamConnection(host string) {+ streamMu.Lock()+ defer streamMu.Unlock()++ current := streamConnections[host]+ if current <= 1 {+ delete(streamConnections, host)+ return+ }+ streamConnections[host] = current - 1+}+func startRateLimiterJanitor(window, interval time.Duration) {rateLimiterStarted.Do(func() {go func() {diff --git a/internal/handlers/middleware_test.go b/internal/handlers/middleware_test.goindex ef30e9fa..c1b4d978 100644--- a/internal/handlers/middleware_test.go+++ b/internal/handlers/middleware_test.go@@ -16,6 +16,10 @@ func resetRateLimitStateForTests() {rateMu.Lock()rateBuckets = map[string][]time.Time{}rateMu.Unlock()++ streamMu.Lock()+ streamConnections = map[string]int{}+ streamMu.Unlock()}func TestAuthMiddleware_NoToken(t *testing.T) {@@ -861,6 +865,60 @@ func TestRateLimitMiddleware_DoesNotRateLimitStreamingEndpoints(t *testing.T) {}}+func TestRateLimitMiddleware_LimitsConcurrentStreamingEndpointsPerHost(t *testing.T) {+ resetRateLimitStateForTests()+ t.Cleanup(resetRateLimitStateForTests)++ entered := make(chan struct{}, maxConcurrentStreamRequestsPerHost)+ release := make(chan struct{})+ results := make(chan int, maxConcurrentStreamRequestsPerHost)++ handler := RateLimitMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ entered <- struct{}{}+ <-release+ w.WriteHeader(http.StatusOK)+ }))++ for i := 0; i < maxConcurrentStreamRequestsPerHost; i++ {+ go func() {+ req := httptest.NewRequest(http.MethodGet, "/api/events", nil)+ req.RemoteAddr = "127.0.0.1:12345"+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)+ results <- w.Code+ }()+ }++ for i := 0; i < maxConcurrentStreamRequestsPerHost; i++ {+ select {+ case <-entered:+ case <-time.After(2 * time.Second):+ t.Fatalf("timed out waiting for stream %d to enter handler", i+1)+ }+ }++ req := httptest.NewRequest(http.MethodGet, "/api/events", nil)+ req.RemoteAddr = "127.0.0.1:12345"+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)+ if w.Code != http.StatusTooManyRequests {+ t.Fatalf("expected 429 once concurrent stream limit is reached, got %d", w.Code)+ }++ close(release)++ for i := 0; i < maxConcurrentStreamRequestsPerHost; i++ {+ select {+ case code := <-results:+ if code != http.StatusOK {+ t.Fatalf("stream %d completed with %d, want 200", i+1, code)+ }+ case <-time.After(2 * time.Second):+ t.Fatalf("timed out waiting for stream %d to complete", i+1)+ }+ }+}+func TestRateLimitMiddleware_IgnoresSpoofedForwardedHeaders(t *testing.T) {resetRateLimitStateForTests()t.Cleanup(resetRateLimitStateForTests)diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.goindex a1d90f59..396c5317 100644--- a/internal/orchestrator/orchestrator.go+++ b/internal/orchestrator/orchestrator.go@@ -374,9 +374,6 @@ func (o *Orchestrator) writeChildConfig(port string, cdpPort int, profilePath, ifc := config.FileConfigFromRuntime(o.runtimeCfg)fc.Server.Port = portfc.Server.StateDir = instanceStateDir- if o.runtimeCfg != nil {- fc.Observability.Activity.StateDir = o.runtimeCfg.ActivityStateDir()- }fc.Browser.ChromeDebugPort = intPtr(cdpPort)fc.Profiles.BaseDir = filepath.Dir(profilePath)fc.Profiles.DefaultProfile = filepath.Base(profilePath)diff --git a/internal/orchestrator/orchestrator_test.go b/internal/orchestrator/orchestrator_test.goindex a0e7e3a9..6bb9bf15 100644--- a/internal/orchestrator/orchestrator_test.go+++ b/internal/orchestrator/orchestrator_test.go@@ -313,7 +313,7 @@ func TestOrchestrator_Launch_ExplicitPortAlsoReservesDistinctChromeDebugPort(t *}}-func TestOrchestrator_Launch_ChildConfigKeepsSharedActivityStateDir(t *testing.T) {+func TestOrchestrator_Launch_DoesNotInjectSharedActivityStateDir(t *testing.T) {old := processAliveFuncprocessAliveFunc = func(pid int) bool { return pid > 0 }defer func() { processAliveFunc = old }()@@ -349,8 +349,11 @@ func TestOrchestrator_Launch_ChildConfigKeepsSharedActivityStateDir(t *testing.Tif fc.Server.StateDir != wantChildStateDir {t.Fatalf("child Server.StateDir = %q, want %q", fc.Server.StateDir, wantChildStateDir)}- if fc.Observability.Activity.StateDir != sharedActivityStateDir {- t.Fatalf("child Observability.Activity.StateDir = %q, want %q", fc.Observability.Activity.StateDir, sharedActivityStateDir)+ if fc.Observability.Activity.StateDir != "" {+ t.Fatalf("child Observability.Activity.StateDir = %q, want empty", fc.Observability.Activity.StateDir)+ }+ if got := envMap(runner.env)["PINCHTAB_INTERNAL_ACTIVITY_STATE_DIR"]; got != "" {+ t.Fatalf("PINCHTAB_INTERNAL_ACTIVITY_STATE_DIR = %q, want empty", got)}if inst.Port != "9930" {t.Fatalf("bridge port = %s, want 9930", inst.Port)diff --git a/internal/server/server.go b/internal/server/server.goindex ab81ead4..9249a1e7 100644--- a/internal/server/server.go+++ b/internal/server/server.go@@ -104,7 +104,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {ticker := time.NewTicker(1 * time.Second)defer ticker.Stop()- lastSync := time.Now().UTC().Add(-2 * time.Second)+ lastSync := time.Now().UTC()for {select {case <-syncCtx.Done():@@ -116,7 +116,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {continue}if !nextSync.IsZero() {- lastSync = nextSync.Add(-2 * time.Second)+ lastSync = nextSync}}}diff --git a/npm/src/index.ts b/npm/src/index.tsindex 3aedc715..bb50e763 100644--- a/npm/src/index.ts+++ b/npm/src/index.ts@@ -1,4 +1,5 @@import { spawn, ChildProcess } from 'child_process';+import { randomBytes } from 'crypto';import * as path from 'path';import * as fs from 'fs';import * as os from 'os';@@ -239,7 +240,7 @@ export class Pinchtab {const configDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pinchtab-npm-'));const configPath = path.join(configDir, 'config.json');const stateDir = path.join(configDir, 'state');- const token = this.configuredToken || `npm-${process.pid}-${Date.now()}`;+ const token = this.configuredToken || `npm-${randomBytes(16).toString('hex')}`;this.token = token;fs.writeFileSync(