File size: 5,270 Bytes
c453128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/**
 * SingleTabGate โ€” allow only ONE live AgentGUI tab/window per browser.
 *
 * Two open copies of the app are actively harmful, not just wasteful: each
 * desk's live activity stream is a single server-side queue, so two activity
 * WebSockets steal alternating tokens from each other (fragmented chat), and
 * two FloorManagers patrol/audit/nudge the same desks concurrently.
 *
 * Mechanism: the Web Locks API. The first tab acquires an exclusive lock and
 * holds it for its lifetime (auto-released by the browser on close/crash).
 * Any later tab fails the `ifAvailable` probe, renders a blocking overlay
 * instead of the app, and queues a waiting lock request โ€” so it activates
 * automatically the moment the holder goes away. "Use here instead" broadcasts
 * a takeover: the holder releases its lock (unmounting the app and closing all
 * its WebSockets) and shows a "moved to another tab" screen.
 *
 * Browsers without `navigator.locks` (non-secure contexts, very old engines)
 * skip gating entirely โ€” same behavior as before this component existed.
 */
import { useEffect, useRef, useState, type ReactNode } from "react";

const LOCK_NAME = "agent-gui-single-tab";
const TAKEOVER_CHANNEL = "agent-gui-tab-takeover";

type GateStatus = "pending" | "active" | "blocked" | "deactivated";

const hasLocks = typeof navigator !== "undefined" && "locks" in navigator;

export default function SingleTabGate({ children }: { children: ReactNode }) {
  const [status, setStatus] = useState<GateStatus>(hasLocks ? "pending" : "active");
  // Resolving this promise releases the held lock (lets another tab take over).
  const releaseRef = useRef<(() => void) | null>(null);

  useEffect(() => {
    if (!hasLocks) return;
    const abort = new AbortController();
    const bc = new BroadcastChannel(TAKEOVER_CHANNEL);
    let dead = false;

    // Queue for the lock. Granted immediately if free; otherwise this waits
    // until the current holder closes or releases, then activates this tab.
    navigator.locks
      .request(LOCK_NAME, { signal: abort.signal }, async () => {
        if (dead) return;
        setStatus("active");
        await new Promise<void>((resolve) => { releaseRef.current = resolve; });
      })
      .catch(() => { /* request aborted on unmount */ });

    // If someone else already holds the lock, our request above is parked in
    // the queue โ€” flip to the blocked overlay (never downgrade an active tab).
    navigator.locks.query().then((state) => {
      if (dead) return;
      if (state.held?.some((l) => l.name === LOCK_NAME)) {
        setStatus((s) => (s === "pending" ? "blocked" : s));
      }
    }).catch(() => {});

    bc.onmessage = (e) => {
      // Another tab requested takeover. Only the holder reacts: release the
      // lock (the waiter is granted next) and go passive. BroadcastChannel
      // never echoes to the sender, so the taker can't deactivate itself.
      if (e.data === "takeover" && releaseRef.current) {
        releaseRef.current();
        releaseRef.current = null;
        setStatus("deactivated");
      }
    };

    return () => {
      dead = true;
      abort.abort();
      releaseRef.current?.();   // StrictMode remount / real unmount: free the lock
      releaseRef.current = null;
      bc.close();
    };
  }, []);

  if (status === "active") return <>{children}</>;
  if (status === "pending") return null; // lock grant resolves in microseconds

  const blocked = status === "blocked";
  return (
    <div style={{
      height: "100vh", display: "flex", flexDirection: "column",
      alignItems: "center", justifyContent: "center", gap: 14,
      background: "var(--bg)", color: "var(--text)", textAlign: "center", padding: 24,
    }}>
      <div style={{ fontSize: 42 }}>{blocked ? "๐Ÿ”’" : "๐Ÿ‘‹"}</div>
      <div style={{ fontSize: 18, fontWeight: 600 }}>
        {blocked
          ? "AgentGUI is already open in another tab or window"
          : "This session moved to another tab"}
      </div>
      <div style={{ color: "var(--text-dim)", maxWidth: 440, fontSize: 13, lineHeight: 1.5 }}>
        {blocked
          ? "Running two copies splits the live agent streams between them and " +
            "doubles manager patrols, so only one tab can be active at a time. " +
            "Close the other tab to continue here, or take over now."
          : "Another tab took over this AgentGUI session. Reload to claim it back."}
      </div>
      {blocked ? (
        <button
          onClick={() => {
            // The waiting lock request from the effect is already queued; the
            // holder releases on this message and we activate automatically.
            const c = new BroadcastChannel(TAKEOVER_CHANNEL);
            c.postMessage("takeover");
            c.close();
          }}
          style={btnStyle}
        >
          Use here instead
        </button>
      ) : (
        <button onClick={() => location.reload()} style={btnStyle}>
          Reload &amp; claim this tab
        </button>
      )}
    </div>
  );
}

const btnStyle: React.CSSProperties = {
  background: "var(--accent2)", color: "#fff", border: "none",
  borderRadius: "var(--radius)", padding: "10px 18px", fontSize: 14,
  fontWeight: 600, cursor: "pointer",
};