Skip to content

fix(relay): serve the relay endpoint from the API - #6226

Merged
saddlepaddle merged 2 commits into
mainfrom
relay-endpoint-api
Aug 10, 2026
Merged

saddlepaddle merged 2 commits into
mainfrom
relay-endpoint-api

Conversation

@saddlepaddle

@saddlepaddle saddlepaddle commented Aug 6, 2026 •

Copy link
Copy Markdown
Member

The client half of this shipped in canary while the server half never merged — host.relayEndpoint 404s in production, so every host and client falls back to the Fly relay. This is that missing server half (the commit was pushed to #6204's branch two hours after that PR merged, so it went nowhere).

Client-side flag evaluation was the root cause of tonight's rollout failures, reproduced under controlled conditions: with the same active flag and the same machine, old code resolved the fallback relay and new code resolved the flag's URL. The desktop resolves the relay when spawning host-service, and getRelayUrl() silently returns the default when PostHog hasn't identified the user yet — a cold start usually loses that race and never re-checks, so a host sits on the wrong relay through any number of restarts. Clients read the flag live while hosts read it at spawn, so the two also drift apart on any change.

host.relayEndpoint resolves the flag server-side, once, for host-service, the renderer, and the CLI. The host-service asks for itself after authenticating rather than trusting what spawned it, so there is no identification to race. env.RELAY_URL remains the fallback for an unreachable API, and the host-service now logs the relay it chose.

Verified locally end-to-end: a dev-project flag pointing at a distinct port, cold start of the whole stack, all three host-services resolved the flag's URL and connected — where the same setup on main used the fallback.


Summary by cubic

Serve host.relayEndpoint from the API and move desktop, CLI, and host-service to use it so hosts and clients land on the same relay. Removes client-side flag races; falls back to env.RELAY_URL if needed.

  • Bug Fixes
    • Added host.relayEndpoint on the API to resolve relay-url-override per user; defaults to env.RELAY_URL.
    • Host-service now resolves the relay after authenticating, logs the chosen URL, and uses it for protocol detection.
    • Desktop renderer fetches the endpoint via @tanstack/react-query (cached, retries); desktop main and CLI stop reading PostHog and only use env.RELAY_URL as fallback.
    • Fixed the production 404 so clients don’t fall back to the Fly relay and hosts/clients stay aligned.

Written for commit b6df04a. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • Improvements
    • Relay connections now retrieve the latest available endpoint when connecting.
    • Added reliable fallback to the configured relay URL when endpoint retrieval is unavailable.
    • Improved consistency of relay endpoint handling across desktop, CLI, and host-service connections.
    • Endpoint requests are cached briefly and retried automatically to improve responsiveness and reliability.

…ients use

Client-side flag evaluation raced PostHog identification: the desktop
resolved the relay when spawning host-service, and a spawn that lost the
race silently used the default, stranding a host on a different relay
than its clients with no signal on either side. Clients read the flag
live while hosts read it at spawn, so the two also drifted apart on any
change.

host.relayEndpoint answers once, server-side, for host-service, the
renderer, and the CLI. The host-service asks for itself after
authenticating rather than trusting what spawned it.

Claude-Session: https://claude.ai/code/session_01A2JifsfA63nWthegPwNt8G
@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 2a85a9b6-ed5e-41f6-bfd2-e46c97c4e029

📥 Commits

Reviewing files that changed from the base of the PR and between 6884f2c and b6df04a.

📒 Files selected for processing (6)
  • apps/desktop/src/main/lib/host-service-coordinator.ts
  • apps/desktop/src/main/lib/relay-url/relay-url.ts
  • apps/desktop/src/renderer/hooks/useRelayUrl/useRelayUrl.ts
  • packages/cli/src/lib/host/relay-url.ts
  • packages/host-service/src/tunnel/connect.ts
  • packages/trpc/src/router/host/host.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • apps/desktop/src/main/lib/relay-url/relay-url.ts
  • apps/desktop/src/renderer/hooks/useRelayUrl/useRelayUrl.ts
  • packages/cli/src/lib/host/relay-url.ts
  • packages/host-service/src/tunnel/connect.ts

📝 Walkthrough

Walkthrough

The host API now resolves user-specific relay overrides and falls back to env.RELAY_URL. Desktop, CLI, and host-service consumers query this endpoint. Tunnel connections use the resolved URL for protocol detection and construction.

Changes

Relay endpoint resolution

Layer / File(s) Summary
Host relay endpoint query
packages/trpc/src/router/host/host.ts
Adds the authenticated host.relayEndpoint query. It returns a valid PostHog override or env.RELAY_URL.
Relay URL consumers
apps/desktop/src/renderer/hooks/useRelayUrl/useRelayUrl.ts, packages/cli/src/lib/host/relay-url.ts, apps/desktop/src/main/lib/relay-url/relay-url.ts, apps/desktop/src/main/lib/host-service-coordinator.ts
Desktop and CLI consumers query the host endpoint. The desktop main-process helper now returns the environment URL synchronously.
Tunnel connection resolution
packages/host-service/src/tunnel/connect.ts
Resolves the endpoint during connection setup and uses it for protocol detection and tunnel construction.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant RelayConsumer
  participant host.relayEndpoint
  participant PostHog
  participant env.RELAY_URL
  participant connectRelay

  RelayConsumer->>host.relayEndpoint: Query relay endpoint
  host.relayEndpoint->>PostHog: Retrieve user override
  PostHog-->>host.relayEndpoint: Return override or failure
  host.relayEndpoint->>env.RELAY_URL: Use fallback when needed
  host.relayEndpoint-->>RelayConsumer: Return relay URL
  connectRelay->>host.relayEndpoint: Resolve endpoint at connection time
  host.relayEndpoint-->>connectRelay: Return effective relay URL
  connectRelay->>connectRelay: Detect protocol and build tunnel
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change and follows the repository's conventional commit format.
Description check ✅ Passed The description explains the problem, implementation, fallback behavior, and end-to-end testing, but does not include the template checklist.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch relay-endpoint-api

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR centralizes relay assignment in a new authenticated API procedure and updates desktop, CLI, and host-service consumers to use it, retaining configured relay URLs as fallbacks.

  • Adds host.relayEndpoint, backed by server-side PostHog flag evaluation.
  • Moves desktop renderer and CLI relay resolution to the shared API.
  • Makes host-service resolve its relay after authentication and log the selected endpoint.
  • Simplifies the desktop spawner to pass only its configured fallback.

Confidence Score: 4/5

The relay-resolution request needs a bounded timeout before merging so an API stall cannot leave an otherwise running host permanently unavailable through the relay.

Tunnel construction now waits for a one-shot API lookup whose transport has no timeout; if that request stalls after registration, neither the configured fallback nor either tunnel client is reached.

Files Needing Attention: packages/host-service/src/tunnel/connect.ts

Important Files Changed

Filename Overview
packages/host-service/src/tunnel/connect.ts Adds authoritative API relay resolution, but an unbounded lookup can prevent tunnel construction and fallback.
packages/trpc/src/router/host/host.ts Adds an authenticated relay endpoint using the established server-side PostHog identity and validated default URL.
apps/desktop/src/renderer/hooks/useRelayUrl/useRelayUrl.ts Replaces renderer-side flag evaluation with a cached authenticated API query and configured fallback.
packages/cli/src/lib/host/relay-url.ts Moves CLI relay selection to the shared API while preserving the environment fallback.
apps/desktop/src/main/lib/relay-url/relay-url.ts Simplifies desktop main-process resolution to provide only the child-process fallback.
apps/desktop/src/main/lib/host-service-coordinator.ts Adapts host-service environment construction to the now-synchronous fallback helper.

Sequence Diagram

sequenceDiagram
  participant Desktop as Desktop/CLI
  participant Host as Host Service
  participant API as Superset API
  participant PH as PostHog
  participant Relay as Selected Relay
  Desktop->>API: host.relayEndpoint
  API->>PH: relay-url-override payload
  PH-->>API: override or empty
  API-->>Desktop: override or configured default
  Host->>API: host.ensure
  API-->>Host: registered host
  Host->>API: host.relayEndpoint
  Note over Host,API: Lookup currently has no bounded timeout
  API->>PH: relay-url-override payload
  API-->>Host: override or configured default
  Host->>Relay: protocol probe and tunnel connection
Loading
Prompt To Fix All With AI
### Issue 1
packages/host-service/src/tunnel/connect.ts:29
**Unbounded relay lookup blocks fallback**

If the API accepts host registration but the subsequent `relayEndpoint` request stalls, `connectRelay` waits indefinitely before constructing a tunnel, causing the running host to remain unavailable remotely instead of connecting through the configured fallback.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Reviews (1): Last reviewed commit: "refactor(relay): let the API decide whic..." | Re-trigger Greptile

fallback: string,
): Promise<string> {
try {
const endpoint = await api.host.relayEndpoint.query();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Unbounded relay lookup blocks fallback

If the API accepts host registration but the subsequent relayEndpoint request stalls, connectRelay waits indefinitely before constructing a tunnel, causing the running host to remain unavailable remotely instead of connecting through the configured fallback.

Knowledge Base Used: Desktop App (Electron main + renderer)

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/host-service/src/tunnel/connect.ts
Line: 29

Comment:
**Unbounded relay lookup blocks fallback**

If the API accepts host registration but the subsequent `relayEndpoint` request stalls, `connectRelay` waits indefinitely before constructing a tunnel, causing the running host to remain unavailable remotely instead of connecting through the configured fallback.

**Knowledge Base Used:** [Desktop App (Electron main + renderer)](https://app.greptile.com/personal-org-6810/-/custom-context/knowledge-base/superset-sh/superset/-/docs/desktop-app.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/desktop/src/main/lib/host-service-coordinator.ts`:
- Line 821: Update the comment immediately above getRelayUrl() in the
relay-resolution flow to state that it reads only env.RELAY_URL, while the child
resolves the API-selected relay after authentication. Remove the outdated
reference to obtaining a PostHog override and do not alter the getRelayUrl()
call.

In `@packages/trpc/src/router/host/host.ts`:
- Around line 40-42: Update the relay override handling around payload?.url to
parse and validate the value as an absolute HTTP or HTTPS URL, rejecting
whitespace-only, malformed, and unsupported-scheme inputs. Return env.RELAY_URL
for every invalid override, and preserve the existing override return only for
valid HTTP/HTTPS URLs.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 1c334abb-a38e-480c-9f03-a315db18a248

📥 Commits

Reviewing files that changed from the base of the PR and between c920d52 and 9cd4ff7.

📒 Files selected for processing (6)
  • apps/desktop/src/main/lib/host-service-coordinator.ts
  • apps/desktop/src/main/lib/relay-url/relay-url.ts
  • apps/desktop/src/renderer/hooks/useRelayUrl/useRelayUrl.ts
  • packages/cli/src/lib/host/relay-url.ts
  • packages/host-service/src/tunnel/connect.ts
  • packages/trpc/src/router/host/host.ts

// `env.RELAY_URL` as fallback (see main/lib/relay-url) so we can A/B-test
// alternate relay deployments per-user.
const effectiveRelayUrl = await getRelayUrl();
const effectiveRelayUrl = getRelayUrl();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Update the adjacent relay-resolution comment.

The comment above this call still states that the coordinator obtains a PostHog override. getRelayUrl() now supplies only env.RELAY_URL; the child resolves the API-selected relay after authentication.

Replace the comment so future changes do not restore the removed resolution path.

🧰 Tools
🪛 ast-grep (0.45.0)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import * as childProcess from "node:child_process";
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/desktop/src/main/lib/host-service-coordinator.ts` at line 821, Update
the comment immediately above getRelayUrl() in the relay-resolution flow to
state that it reads only env.RELAY_URL, while the child resolves the
API-selected relay after authentication. Remove the outdated reference to
obtaining a PostHog override and do not alter the getRelayUrl() call.

Comment on lines +40 to +42
const override = payload?.url;
if (typeof override === "string" && override.length > 0) {
return { url: override };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate files =="
git ls-files | rg '(^|/)host\.ts$|(^|/)connect\.ts$|package\.json$' | sed -n '1,120p'

echo
echo "== host router outline =="
ast-grep outline packages/trpc/src/router/host/host.ts --view compact || true

echo
echo "== host router relevant sections =="
cat -n packages/trpc/src/router/host/host.ts | sed -n '1,120p'

echo
echo "== connect.ts relevant searches =="
rg -n "relayEndpoint|relay|RELAY|url|relayUrl|host-service" packages/host-service/src -S || true

echo
echo "== files under host-service tunnel =="
git ls-files packages/host-service/src/tunnel | sed -n '1,120p'

echo
echo "== connect.ts snippets around URL use =="
cat -n packages/host-service/src/tunnel/connect.ts | sed -n '1,220p'

echo
echo "== search relayEndpoint usages =="
rg -n "relayEndpoint|RELAY_URL|relayUrl|relayEndpoint" packages -S || true

Repository: superset-sh/superset

Length of output: 50376


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== deterministic URL validation probe =="
node - <<'JS'
const inputs = [
  "https://relay.example.com",
  "http://relay.example.com/path",
  "   ",
  "\n\n",
  "not a url",
  "telnet://relay.example.com",
  "file:///tmp/x",
  "//relay.example.com",
  "https://a",
  "",
];
for (const input of inputs) {
  let validFallback = false;
  try {
    const url = new URL(input);
    validFallback = url.protocol === "http:" || url.protocol === "https:";
  } catch (e) {
    validFallback = false;
  }
  console.log(JSON.stringify({input: input, parsedFallback: validFallback}));
}
JS

Repository: superset-sh/superset

Length of output: 693


Reject malformed relay overrides before returning them.

The current check accepts whitespace, malformed strings, and unsupported schemes. Return env.RELAY_URL unless payload?.url is a parseable HTTP/HTTPS URL.

packages/host-service/src/tunnel/connect.ts uses the returned relay value for health checks and tunnel connection construction, so a bad PostHog payload can strand those hosts on an unusable relay.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/trpc/src/router/host/host.ts` around lines 40 - 42, Update the relay
override handling around payload?.url to parse and validate the value as an
absolute HTTP or HTTPS URL, rejecting whitespace-only, malformed, and
unsupported-scheme inputs. Return env.RELAY_URL for every invalid override, and
preserve the existing override return only for valid HTTP/HTTPS URLs.

@github-actions

github-actions Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

🧹 Preview Cleanup Complete

The following preview resources have been cleaned up:

  • ✅ Neon database branch

Thank you for your contribution! 🎉

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

5 issues found across 6 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/trpc/src/router/host/host.ts">

<violation number="1" location="packages/trpc/src/router/host/host.ts:36">
P3: Relay flag resolution is now maintained in two server-side implementations, allowing the host endpoint and existing API callers to drift in validation and fallback behavior. Extract the shared payload-to-URL resolver into a package both routes can use.</violation>

<violation number="2" location="packages/trpc/src/router/host/host.ts:41">
P1: A valid override ending in `/`, or any malformed non-empty override, makes flagged clients and hosts unable to reach the relay instead of using a usable endpoint. Validate the URL and strip trailing slashes before returning it.</violation>

<violation number="3" location="packages/trpc/src/router/host/host.ts:44">
P2: The new `relayEndpoint` query swallows any PostHog flag-evaluation error in a bare catch with only a comment and no log, then falls back to `env.RELAY_URL`. Because this endpoint is hit on every cold start (desktop renderer, CLI spawn, host-service connect), a server-side failure would silently route every client and host to the default relay with no trace — the same silent-fallback behavior the change is meant to remove. Logging a warning on this failure path would make it observable. The CLI/host-service consumers log their own fallback warn, but the renderer consumer does not, so this path is effectively silent end-to-end.</violation>
</file>

<file name="apps/desktop/src/main/lib/host-service-coordinator.ts">

<violation number="1" location="apps/desktop/src/main/lib/host-service-coordinator.ts:821">
P3: The comment above this call still describes the old PostHog-override resolution flow, but `getRelayUrl()` now only returns `env.RELAY_URL` — the actual relay resolution happens later in the host-service child after authentication. Update the comment so it doesn't describe a resolution path that no longer exists here.</violation>
</file>

<file name="apps/desktop/src/renderer/hooks/useRelayUrl/useRelayUrl.ts">

<violation number="1" location="apps/desktop/src/renderer/hooks/useRelayUrl/useRelayUrl.ts:19">
P2: The relay URL still falls back to `env.RELAY_URL` on the first render before the API query resolves. `useQuery` returns undefined synchronously, so `data?.url ?? env.RELAY_URL` hands consumers the default relay for the initial mount frames, and they only reconcile to the correct URL after the round-trip. This recreates the fallback-first behavior the change is meant to eliminate: any client-side WS/target established from the first-render value can still land on the default relay and drift apart from the host-service, which now resolves the endpoint once at connect time. Consider gating consumers on the query being settled (e.g. exposing an isLoading/isFetching state so callers don't commit to `env.RELAY_URL`) rather than returning the fallback unconditionally on the first render.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant Renderer as Desktop Renderer
    participant Main as Desktop Main
    participant CLI as CLI
    participant HostSvc as Host-Service
    participant API as API (tRPC host.relayEndpoint)
    participant PostHog as PostHog Flags
    participant Relay as Relay Server

    Note over Renderer,Relay: Relay endpoint is now resolved server-side so hosts and clients stay on the same relay

    Renderer->>API: NEW: host.relayEndpoint.query() with JWT
    API->>PostHog: getFeatureFlagPayload(RELAY_URL_OVERRIDE, userId)
    PostHog-->>API: flag payload with url
    API-->>Renderer: endpoint url or env.RELAY_URL
    Note over Renderer: react-query caches 5 min, retries 3, falls back to env.RELAY_URL

    Main->>Main: CHANGED: getRelayUrl() returns env.RELAY_URL only
    Main->>HostSvc: spawn with childEnv.RELAY_URL = env.RELAY_URL

    CLI->>API: NEW: host.relayEndpoint.query() with JWT
    API->>PostHog: getFeatureFlagPayload(RELAY_URL_OVERRIDE, userId)
    PostHog-->>API: flag payload with url
    API-->>CLI: endpoint url or env.RELAY_URL
    CLI->>HostSvc: spawn with childEnv.RELAY_URL = resolved endpoint

    HostSvc->>API: authenticate and register as host
    API-->>HostSvc: registration ok
    HostSvc->>API: NEW: host.relayEndpoint.query() with own JWT after auth
    API->>PostHog: getFeatureFlagPayload(RELAY_URL_OVERRIDE, userId)
    PostHog-->>API: flag payload with url
    alt API reachable
        API-->>HostSvc: endpoint url or env.RELAY_URL
        HostSvc->>HostSvc: use API answer, do not trust spawner fallback
    else API or PostHog lookup fails
        HostSvc->>HostSvc: log warning, use spawned env.RELAY_URL
    end
    HostSvc->>Relay: detect protocol and connect tunnel to selected relay
Loading

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment on lines +41 to +43
if (typeof override === "string" && override.length > 0) {
return { url: override };
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: A valid override ending in /, or any malformed non-empty override, makes flagged clients and hosts unable to reach the relay instead of using a usable endpoint. Validate the URL and strip trailing slashes before returning it.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/trpc/src/router/host/host.ts, line 41:

<comment>A valid override ending in `/`, or any malformed non-empty override, makes flagged clients and hosts unable to reach the relay instead of using a usable endpoint. Validate the URL and strip trailing slashes before returning it.</comment>

<file context>
@@ -11,13 +11,42 @@ import {
+				ctx.userId,
+			)) as RelayUrlPayload | null | undefined;
+			const override = payload?.url;
+			if (typeof override === "string" && override.length > 0) {
+				return { url: override };
+			}
</file context>
Suggested change
if (typeof override === "string" && override.length > 0) {
return { url: override };
}
if (typeof override === "string") {
const parsed = z.string().url().safeParse(override);
if (
parsed.success &&
["http:", "https:", "ws:", "wss:"].includes(
new URL(parsed.data).protocol,
)
) {
return { url: parsed.data.replace(/\/+$/, "") };
}
}

if (typeof override === "string" && override.length > 0) {
return { url: override };
}
} catch {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The new relayEndpoint query swallows any PostHog flag-evaluation error in a bare catch with only a comment and no log, then falls back to env.RELAY_URL. Because this endpoint is hit on every cold start (desktop renderer, CLI spawn, host-service connect), a server-side failure would silently route every client and host to the default relay with no trace — the same silent-fallback behavior the change is meant to remove. Logging a warning on this failure path would make it observable. The CLI/host-service consumers log their own fallback warn, but the renderer consumer does not, so this path is effectively silent end-to-end.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/trpc/src/router/host/host.ts, line 44:

<comment>The new `relayEndpoint` query swallows any PostHog flag-evaluation error in a bare catch with only a comment and no log, then falls back to `env.RELAY_URL`. Because this endpoint is hit on every cold start (desktop renderer, CLI spawn, host-service connect), a server-side failure would silently route every client and host to the default relay with no trace — the same silent-fallback behavior the change is meant to remove. Logging a warning on this failure path would make it observable. The CLI/host-service consumers log their own fallback warn, but the renderer consumer does not, so this path is effectively silent end-to-end.</comment>

<file context>
@@ -11,13 +11,42 @@ import {
+			if (typeof override === "string" && override.length > 0) {
+				return { url: override };
+			}
+		} catch {
+			// Fall through to the default relay.
+		}
</file context>
Suggested change
} catch {
} catch (error) {
console.warn(
"[trpc] relay-url-override payload fetch failed, using default relay:",
error instanceof Error ? error.message : error,
);
// Fall through to the default relay.
}

staleTime: 5 * 60 * 1000,
retry: 3,
});
return data?.url ?? env.RELAY_URL;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The relay URL still falls back to env.RELAY_URL on the first render before the API query resolves. useQuery returns undefined synchronously, so data?.url ?? env.RELAY_URL hands consumers the default relay for the initial mount frames, and they only reconcile to the correct URL after the round-trip. This recreates the fallback-first behavior the change is meant to eliminate: any client-side WS/target established from the first-render value can still land on the default relay and drift apart from the host-service, which now resolves the endpoint once at connect time. Consider gating consumers on the query being settled (e.g. exposing an isLoading/isFetching state so callers don't commit to env.RELAY_URL) rather than returning the fallback unconditionally on the first render.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/renderer/hooks/useRelayUrl/useRelayUrl.ts, line 19:

<comment>The relay URL still falls back to `env.RELAY_URL` on the first render before the API query resolves. `useQuery` returns undefined synchronously, so `data?.url ?? env.RELAY_URL` hands consumers the default relay for the initial mount frames, and they only reconcile to the correct URL after the round-trip. This recreates the fallback-first behavior the change is meant to eliminate: any client-side WS/target established from the first-render value can still land on the default relay and drift apart from the host-service, which now resolves the endpoint once at connect time. Consider gating consumers on the query being settled (e.g. exposing an isLoading/isFetching state so callers don't commit to `env.RELAY_URL`) rather than returning the fallback unconditionally on the first render.</comment>

<file context>
@@ -1,23 +1,20 @@
+		staleTime: 5 * 60 * 1000,
+		retry: 3,
+	});
+	return data?.url ?? env.RELAY_URL;
 }
</file context>

// `env.RELAY_URL` as fallback (see main/lib/relay-url) so we can A/B-test
// alternate relay deployments per-user.
const effectiveRelayUrl = await getRelayUrl();
const effectiveRelayUrl = getRelayUrl();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The comment above this call still describes the old PostHog-override resolution flow, but getRelayUrl() now only returns env.RELAY_URL — the actual relay resolution happens later in the host-service child after authentication. Update the comment so it doesn't describe a resolution path that no longer exists here.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/main/lib/host-service-coordinator.ts, line 821:

<comment>The comment above this call still describes the old PostHog-override resolution flow, but `getRelayUrl()` now only returns `env.RELAY_URL` — the actual relay resolution happens later in the host-service child after authentication. Update the comment so it doesn't describe a resolution path that no longer exists here.</comment>

<file context>
@@ -818,7 +818,7 @@ export class HostServiceCoordinator extends EventEmitter {
 		// `env.RELAY_URL` as fallback (see main/lib/relay-url) so we can A/B-test
 		// alternate relay deployments per-user.
-		const effectiveRelayUrl = await getRelayUrl();
+		const effectiveRelayUrl = getRelayUrl();
 		if (exposeViaRelay && effectiveRelayUrl) {
 			childEnv.RELAY_URL = effectiveRelayUrl;
</file context>

*/
relayEndpoint: jwtProcedure.query(async ({ ctx }) => {
try {
const payload = (await posthog.getFeatureFlagPayload(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Relay flag resolution is now maintained in two server-side implementations, allowing the host endpoint and existing API callers to drift in validation and fallback behavior. Extract the shared payload-to-URL resolver into a package both routes can use.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/trpc/src/router/host/host.ts, line 36:

<comment>Relay flag resolution is now maintained in two server-side implementations, allowing the host endpoint and existing API callers to drift in validation and fallback behavior. Extract the shared payload-to-URL resolver into a package both routes can use.</comment>

<file context>
@@ -11,13 +11,42 @@ import {
+	 */
+	relayEndpoint: jwtProcedure.query(async ({ ctx }) => {
+		try {
+			const payload = (await posthog.getFeatureFlagPayload(
+				FEATURE_FLAGS.RELAY_URL_OVERRIDE,
+				ctx.userId,
</file context>

@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

This branch was previously deployed

1 inactive deployment
preview — b6df04a0 Deployed Aug 10, 2026 by saddlepaddle via Deploy Web #7373
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant