/ src / bridge / replBridgeHandle.ts
replBridgeHandle.ts
 1  import { updateSessionBridgeId } from '../utils/concurrentSessions.js'
 2  import type { ReplBridgeHandle } from './replBridge.js'
 3  import { toCompatSessionId } from './sessionIdCompat.js'
 4  
 5  /**
 6   * Global pointer to the active REPL bridge handle, so callers outside
 7   * useReplBridge's React tree (tools, slash commands) can invoke handle methods
 8   * like subscribePR. Same one-bridge-per-process justification as bridgeDebug.ts
 9   * — the handle's closure captures the sessionId and getAccessToken that created
10   * the session, and re-deriving those independently (BriefTool/upload.ts pattern)
11   * risks staging/prod token divergence.
12   *
13   * Set from useReplBridge.tsx when init completes; cleared on teardown.
14   */
15  
16  let handle: ReplBridgeHandle | null = null
17  
18  export function setReplBridgeHandle(h: ReplBridgeHandle | null): void {
19    handle = h
20    // Publish (or clear) our bridge session ID in the session record so other
21    // local peers can dedup us out of their bridge list — local is preferred.
22    void updateSessionBridgeId(getSelfBridgeCompatId() ?? null).catch(() => {})
23  }
24  
25  export function getReplBridgeHandle(): ReplBridgeHandle | null {
26    return handle
27  }
28  
29  /**
30   * Our own bridge session ID in the session_* compat format the API returns
31   * in /v1/sessions responses — or undefined if bridge isn't connected.
32   */
33  export function getSelfBridgeCompatId(): string | undefined {
34    const h = getReplBridgeHandle()
35    return h ? toCompatSessionId(h.bridgeSessionId) : undefined
36  }