findBridgePortForWorkspace function

Future<int> findBridgePortForWorkspace(
  1. String name, {
  2. String host = '127.0.0.1',
  3. int minPort = defaultVSCodeBridgePort,
  4. int maxPort = maxVSCodeBridgePort,
  5. BridgePortProbe probe = _defaultProbe,
  6. BridgeIdentityFetcher fetchIdentity = fetchBridgeWorkspaceName,
})

Scans the CLI bridge port range for the window whose workspace matches name and returns its port.

Ports are probed in ascending order from minPort to maxPort (inclusive, defaulting to the full defaultVSCodeBridgePort–maxVSCodeBridgePort range). For each responsive port the bridge's workspace identity is fetched and compared to name (normalised so the bare workspace name, a .code-workspace filename, and VS Code's " (Workspace)" multi-root suffix all match each other). The first matching port is returned, and the scan stops there.

Deliberately silent about a duplicate. Two VS Code windows with the same workspace open report the same identity; this function takes the lowest port and does not look further, because a helper that refused on ambiguity would break the common single-window case for a condition that is benign — every such window reaches the same extension. A caller that wants to know whether the name was ambiguous — because a user typed it as a pin and deserves to hear what it selected — uses findBridgePortsForWorkspace and reports the collision itself.

Throws a BridgeWorkspaceNotFoundException if no responsive bridge in the range reports a matching workspace.

Implementation

Future<int> findBridgePortForWorkspace(
  String name, {
  String host = '127.0.0.1',
  int minPort = defaultVSCodeBridgePort,
  int maxPort = maxVSCodeBridgePort,
  BridgePortProbe probe = _defaultProbe,
  BridgeIdentityFetcher fetchIdentity = fetchBridgeWorkspaceName,
}) async {
  final target = normalizeWorkspaceName(name);
  for (var port = minPort; port <= maxPort; port++) {
    if (!await probe(host, port)) continue;
    final identity = await fetchIdentity(host, port);
    if (identity == null) continue;
    if (normalizeWorkspaceName(identity) == target) return port;
  }
  throw BridgeWorkspaceNotFoundException(name, minPort, maxPort);
}