Skip to content

Connect tunnel stops retrying after an HTTP 500 WebSocket upgrade response #1782

Closed

Description

@hemaaanth

Workflow

Run bb 0.38.0 with the local server exposed through bb connect, then use remote browser/mobile/desktop clients through the assigned getbb.app handle.

What happened

An established Connect tunnel closed abnormally. The first reconnect reached the Connect gate but received HTTP 500:

[05:10:06] tunnel closed (code 1006); reconnecting in 1000ms
[05:10:07] tunnel connecting to wss://<handle>.getbb.app/__tunnel?v=1
[05:10:08] tunnel rejected: HTTP 500

There were no subsequent reconnect attempts. bb connect status --json remained paired but stuck in reconnecting, with lastError: "tunnel rejected: HTTP 500" and an elapsed nextRetryAt.

Remote clients could still render the app shell, but opening any thread failed with “Failed to load thread.” The local server and thread APIs remained healthy, and there was no process crash, coredump, OOM event, or data loss.

Reloading the Connect plugin initiated another dial, but that handshake could remain pending indefinitely. A full bb service restart restored the tunnel.

Expected behavior

A transient non-auth HTTP rejection should close the failed attempt and schedule another capped-backoff reconnect. A WebSocket handshake that never opens or closes should have a deadline and retry.

Likely mechanism

ConnectTunnel.openTunnel() handles non-401/403 unexpected-response events by recording lastError, but it schedules retries only from the WebSocket close handler. In the observed HTTP 500 path, no later close event arrived, so the tunnel stayed alive enough to prevent process supervision from helping but never retried.

The dial also has no handshake timeout, which permits a replacement attempt to remain pending indefinitely.

Suggested fix

  • Route unexpected-response failures through an idempotent cleanup/reconnect path instead of relying on a later close event.
  • Add a bounded WebSocket handshake timeout.
  • Add regression coverage for:
    • HTTP 500 with no subsequent close event;
    • a handshake that never completes;
    • avoiding duplicate retries when both unexpected-response and close fire.

Environment

  • bb-app 0.38.0
  • Linux x64
  • Node.js 26.7.0
  • Built-in Connect plugin

Related but distinct: #1494 and #1524 cover desktop recovery when a configured server target is unreachable. This report concerns the server-side Connect tunnel no longer retrying, which affects every remote client.

A deterministic reproduction script will follow separately and be linked back to this issue.

AGENT GENERATED: by GPT-5.6 Sol

Activity

  1. hemaaanth commented on Aug 18, 2026

    @hemaaanth
    ContributorAuthor

    Here is a deterministic reproducer that uses loopback networking, fake plugin state, and the real ConnectTunnel. It does not touch a running bb service or any stored credentials.

    With workspace dependencies installed, save it as plugins/connect/scripts/repro-http-500-no-retry.mts and run:

    node --conditions=source --import tsx plugins/connect/scripts/repro-http-500-no-retry.mts
    import assert from "node:assert/strict";
    import { createServer } from "node:http";
    import type { AddressInfo } from "node:net";
    import type { Socket } from "node:net";
    import { createFakePluginHost } from "@get-bb/plugin-sdk/testing";
    import { ShareHostResolver } from "../src/hosts.js";
    import { DEFAULT_CONNECT_BASE_URL } from "../src/redeem.js";
    import { ShareRegistry } from "../src/shares.js";
    import { ConnectTunnel } from "../src/tunnel.js";
    
    const OBSERVATION_WINDOW_MS = 3_000;
    const POLL_INTERVAL_MS = 10;
    const CONDITION_TIMEOUT_MS = 2_000;
    
    const sleep = (durationMs: number) =>
      new Promise<void>((resolve) => setTimeout(resolve, durationMs));
    
    async function waitFor(
      description: string,
      condition: () => boolean,
    ): Promise<void> {
      const deadline = Date.now() + CONDITION_TIMEOUT_MS;
      while (!condition()) {
        if (Date.now() >= deadline) {
          throw new Error(`Timed out waiting for ${description}`);
        }
        await sleep(POLL_INTERVAL_MS);
      }
    }
    
    const heldSockets = new Set<Socket>();
    let upgradeAttempts = 0;
    const gate = createServer((_request, response) => {
      response.writeHead(404).end();
    });
    
    gate.on("upgrade", (_request, socket) => {
      upgradeAttempts += 1;
      heldSockets.add(socket);
      socket.once("close", () => heldSockets.delete(socket));
      socket.write(
        "HTTP/1.1 500 Internal Server Error\r\n" +
          "Content-Length: 0\r\n" +
          "Connection: keep-alive\r\n" +
          "\r\n",
      );
      // Keep the rejected upgrade socket open. Node's `ws` emits
      // `unexpected-response`, but no later `close` event for ConnectTunnel to
      // schedule its retry from.
    });
    
    await new Promise<void>((resolve, reject) => {
      gate.once("error", reject);
      gate.listen(0, "127.0.0.1", () => resolve());
    });
    
    const address = gate.address() as AddressInfo;
    const fakeHost = createFakePluginHost({
      pluginId: "connect-http-500-repro",
      sdk: {
        system: {
          config: async () => ({ primaryHostId: "host-repro" }) as never,
        },
      },
    });
    const credential = {
      serverUrl: `http://127.0.0.1:${address.port}`,
      handle: "repro",
      credential: "bbcred_repro",
    };
    const shares = new ShareRegistry({
      kv: {
        get: async () => undefined,
        set: async () => {},
        delete: async () => {},
      },
      hosts: fakeHost.bb.hosts,
      hostResolver: new ShareHostResolver(() => fakeHost.bb.sdk),
      getLoopbackBaseUrl: () => "http://127.0.0.1:38886",
      getCredential: () => credential,
      log: fakeHost.bb.log,
    });
    const tunnel = new ConnectTunnel({
      store: {
        read: async () => credential,
        write: async () => {},
        clear: async () => {},
      },
      shares,
      defaultBaseUrl: DEFAULT_CONNECT_BASE_URL,
      getLoopbackBaseUrl: () => "http://127.0.0.1:38886",
      log: fakeHost.bb.log,
    });
    
    try {
      await tunnel.start();
      await waitFor("the rejected WebSocket upgrade", () => upgradeAttempts === 1);
      await waitFor(
        "ConnectTunnel to record the HTTP 500",
        () => tunnel.status().lastError === "tunnel rejected: HTTP 500",
      );
    
      await sleep(OBSERVATION_WINDOW_MS);
    
      const status = tunnel.status();
      assert.equal(status.state, "reconnecting");
      assert.equal(status.lastError, "tunnel rejected: HTTP 500");
      assert.equal(status.nextRetryAt, null);
      assert.equal(
        upgradeAttempts,
        1,
        "Bug no longer reproduced: ConnectTunnel made another upgrade attempt",
      );
    
      console.log("BUG REPRODUCED: ConnectTunnel did not retry after HTTP 500");
      console.log(
        JSON.stringify(
          {
            observationWindowMs: OBSERVATION_WINDOW_MS,
            upgradeAttempts,
            state: status.state,
            lastError: status.lastError,
            nextRetryAt: status.nextRetryAt,
          },
          null,
          2,
        ),
      );
    } finally {
      tunnel.stop();
      for (const socket of heldSockets) socket.destroy();
      await new Promise<void>((resolve) => gate.close(() => resolve()));
      await fakeHost.harness.dispose();
    }

    Current output:

    BUG REPRODUCED: ConnectTunnel did not retry after HTTP 500
    {
      "observationWindowMs": 3000,
      "upgradeAttempts": 1,
      "state": "reconnecting",
      "lastError": "tunnel rejected: HTTP 500",
      "nextRetryAt": null
    }
    
  2. added theissue type on Aug 18, 2026
  3. added
    remote
    connect
    on Aug 18, 2026
  4. added a commit that references this issue on Aug 19, 2026
    c1a8980
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    connectremote

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions