Skip to content

fix(api): resolve owner's relay when dispatching automations - #6337

Merged
saddlepaddle merged 3 commits into
mainfrom
relay-endpoint-api
Aug 11, 2026
Merged

saddlepaddle merged 3 commits into
mainfrom
relay-endpoint-api

Conversation

@saddlepaddle

@saddlepaddle saddlepaddle commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

Automations broke for anyone whose host moved to relay2.

apps/api/src/app/api/automations/dispatch/[id]/route.ts passed relayUrl: env.RELAY_URL — the default (Fly) relay, hardcoded. The MCP route and Slack agent already resolve getRelayUrl(userId), but automation dispatch never did. So when an owner's host tunnels into an overridden relay via relay-url-override, their scheduled automations are dispatched at the default relay, which no longer holds their host, and the run can't reach the machine (programmatic access silently fails).

Fix: resolve getRelayUrl(automation.ownerUserId), matching the other two server-side paths. getRelayUrl reads the same flag the desktop/host use; posthog-node evaluates it remotely (no personalApiKey), so the owner's stored email resolves the targeting correctly.

Found while porting the internal team to relay2 — the host moved, automations kept dialing Fly.


Summary by cubic

Dispatches automations using the owner’s resolved relay instead of the default, and centralizes relay selection in the API so hosts and clients use the same endpoint. Fixes broken automations when hosts moved to relay2 and prevents relay mismatches across desktop, CLI, and host-service.

  • Bug Fixes

    • Automation dispatch now uses getRelayUrl(automation.ownerUserId) instead of env.RELAY_URL, ensuring runs reach hosts on overridden relays.
  • Refactors

    • Added API host.relayEndpoint that returns the user’s relay (reads relay-url-override, falls back to env.RELAY_URL).
    • Desktop renderer and CLI query this endpoint; host-service resolves the relay at connect time; the desktop main process now only supplies a fallback.

Written for commit 4fb6e01. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • New Features

    • Relay connections now resolve the appropriate endpoint dynamically through the host service.
    • Automation dispatches use the automation owner’s configured relay endpoint.
    • Desktop and CLI clients retrieve relay endpoint settings through the host API.
  • Bug Fixes

    • Added reliable fallback to the default relay endpoint when the host service is unavailable or no custom endpoint is configured.
    • Improved connection logging when endpoint resolution fails.

…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
Automation dispatch hardcoded env.RELAY_URL (the default relay), so an
owner whose host moved to an overridden relay (relay-url-override) had
their automations dispatched at the default relay, which no longer holds
their host — the run fails to reach the machine. Resolve getRelayUrl for
the owner, matching the MCP and Slack-agent paths.

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

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Relay URL resolution moves from direct PostHog lookups in clients to a protected host API. Desktop, CLI, tunnel connections, and automation dispatch now use resolved relay URLs with environment fallbacks.

Changes

Relay endpoint resolution

Layer / File(s) Summary
Relay endpoint API
packages/trpc/src/router/host/host.ts
Adds hostRouter.relayEndpoint, which returns a valid authenticated-user override or env.RELAY_URL.
Relay consumer migration
apps/desktop/src/main/lib/relay-url/relay-url.ts, apps/desktop/src/main/lib/host-service-coordinator.ts, apps/desktop/src/renderer/hooks/useRelayUrl/useRelayUrl.ts, packages/cli/src/lib/host/relay-url.ts, packages/host-service/src/tunnel/connect.ts
Desktop, CLI, and tunnel code query the host endpoint or use env.RELAY_URL as a fallback.
Automation dispatch routing
apps/api/src/app/api/automations/dispatch/[id]/route.ts
Automation dispatch resolves the owner’s relay URL instead of using the static environment URL.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant hostRouter.relayEndpoint
  participant PostHog
  participant RelayService
  Client->>hostRouter.relayEndpoint: Query relay endpoint
  hostRouter.relayEndpoint->>PostHog: Read user relay override
  PostHog-->>hostRouter.relayEndpoint: Override or error
  hostRouter.relayEndpoint-->>Client: Override or env.RELAY_URL
  Client->>RelayService: Connect or dispatch using resolved URL
Loading

Possibly related PRs

Suggested reviewers: kitenite

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the problem and solution, but it omits the required testing section and checklist from the repository template. Add a "How I tested it" section with verification details and include the required checklist items with accurate completion status.
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title uses conventional commit format and clearly identifies the primary fix: resolving the owner's relay during automation dispatch.
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 💡 1
📝 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.

@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/renderer/hooks/useRelayUrl/useRelayUrl.ts`:
- Around line 13-18: Update the relay endpoint query identified by queryKey
["relay-endpoint"] to prevent reuse across account transitions: either remove
this query during the useSignOut flow or include a stable user ID in its key.
Ensure a newly signed-in user cannot receive the previous user’s cached relay
URL.

In `@packages/trpc/src/router/host/host.ts`:
- Around line 36-42: Update the relay override validation in the host handler
around FEATURE_FLAGS.RELAY_URL_OVERRIDE so it parses the string as a URL and
returns it only when valid and using an http: or https: protocol; otherwise
continue to the existing env.RELAY_URL fallback. Reject whitespace-only and
malformed values.
🪄 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: e8d995fe-009e-4cf5-a162-d08fcb94571b

📥 Commits

Reviewing files that changed from the base of the PR and between b75dd21 and 4fb6e01.

📒 Files selected for processing (7)
  • apps/api/src/app/api/automations/dispatch/[id]/route.ts
  • 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

Comment on lines +13 to +18
const { data } = useQuery({
queryKey: ["relay-endpoint"],
queryFn: () => apiTrpcClient.host.relayEndpoint.query(),
staleTime: 5 * 60 * 1000,
retry: 3,
});

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 | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

fd -a '^api-trpc-client\.ts$' apps/desktop/src/renderer \
  --exec ast-grep outline {} --items all

rg -n -C 4 --type ts --type tsx \
  'QueryClient|queryClient\.(clear|removeQueries|resetQueries)|signOut|logout|session' \
  apps/desktop/src/renderer

Repository: superset-sh/superset

Length of output: 590


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- renderer files related to query and auth lifecycle ---'
rg -n -C 5 \
  'QueryClient|QueryClientProvider|queryClient\.(clear|removeQueries|resetQueries|invalidateQueries)|signOut|logout|authClient|getSession|session' \
  apps/desktop/src/renderer \
  -g '*.ts' -g '*.tsx' -g '*.js' -g '*.jsx' \
  | head -n 1200

printf '%s\n' '--- hook ---'
cat -n apps/desktop/src/renderer/hooks/useRelayUrl/useRelayUrl.ts

printf '%s\n' '--- client and package scripts/config references ---'
cat -n apps/desktop/src/renderer/lib/api-trpc-client.ts
rg -n -C 5 'QueryClientProvider|new QueryClient|QueryClient\(' apps/desktop -g '*.ts' -g '*.tsx' -g '*.js' -g '*.jsx'

Repository: superset-sh/superset

Length of output: 50377


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- query provider ---'
rg -l 'QueryClientProvider|new QueryClient|electronQueryClient' apps/desktop/src/renderer \
  -g '*.ts' -g '*.tsx' \
  | sort
printf '%s\n' '--- provider contents ---'
provider=$(rg -l 'QueryClientProvider|new QueryClient' apps/desktop/src/renderer -g '*.ts' -g '*.tsx' | head -n 1)
test -n "$provider"
cat -n "$provider"

printf '%s\n' '--- auth transition call sites ---'
rg -n -C 8 '\.(signOut|signIn)\(|signOut|signIn' apps/desktop/src/renderer \
  -g '*.ts' -g '*.tsx' \
  | grep -E 'auth|signOut|signIn|Query|queryClient' \
  | head -n 600

printf '%s\n' '--- exact relay hook and auth client exports ---'
cat -n apps/desktop/src/renderer/hooks/useRelayUrl/useRelayUrl.ts
cat -n apps/desktop/src/renderer/lib/auth-client.ts | sed -n '1,180p'

Repository: superset-sh/superset

Length of output: 34245


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- sign-out implementation ---'
cat -n apps/desktop/src/renderer/hooks/useSignOut/useSignOut.ts

printf '%s\n' '--- sign-in success handling ---'
cat -n apps/desktop/src/renderer/routes/sign-in/page.tsx | sed -n '1,130p'

printf '%s\n' '--- all cache lifecycle operations in desktop renderer ---'
rg -n \
  'electronQueryClient\.(clear|removeQueries|resetQueries|invalidateQueries)|queryClient\.(clear|removeQueries|resetQueries|invalidateQueries)|setQueryData|removeQueries|clear\(\)' \
  apps/desktop/src/renderer \
  -g '*.ts' -g '*.tsx' \
  | head -n 500

Repository: superset-sh/superset

Length of output: 21056


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- relayEndpoint implementation and callers ---'
rg -n -C 8 'relayEndpoint' . \
  -g '*.ts' -g '*.tsx' -g '*.js' -g '*.jsx' \
  | head -n 800

Repository: superset-sh/superset

Length of output: 5474


Clear the relay endpoint query on account transitions.

The module-global QueryClient survives sign-out, and useSignOut does not remove this query. If a new user signs in within five minutes, the query can return the previous user's relay URL. Remove ["relay-endpoint"] during sign-out or include a stable user ID in the key.

🤖 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/renderer/hooks/useRelayUrl/useRelayUrl.ts` around lines 13 -
18, Update the relay endpoint query identified by queryKey ["relay-endpoint"] to
prevent reuse across account transitions: either remove this query during the
useSignOut flow or include a stable user ID in its key. Ensure a newly signed-in
user cannot receive the previous user’s cached relay URL.

Comment on lines +36 to +42
const payload = (await posthog.getFeatureFlagPayload(
FEATURE_FLAGS.RELAY_URL_OVERRIDE,
ctx.userId,
)) as RelayUrlPayload | null | undefined;
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

Validate the relay override before returning it.

override.length > 0 accepts whitespace and malformed URLs. The API then returns an unusable override instead of env.RELAY_URL. This breaks relay connections for the affected user.

Parse the value and accept only relay protocols that the consumers support, such as http: and https:.

Proposed fix
 interface RelayUrlPayload {
 	url?: string;
 }
 
+function isRelayUrl(value: unknown): value is string {
+	if (typeof value !== "string" || value.trim().length === 0) return false;
+	try {
+		const url = new URL(value);
+		return url.protocol === "http:" || url.protocol === "https:";
+	} catch {
+		return false;
+	}
+}
+
 export const hostRouter = {
@@
-			if (typeof override === "string" && override.length > 0) {
+			if (isRelayUrl(override)) {
 				return { url: override };
 			}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const payload = (await posthog.getFeatureFlagPayload(
FEATURE_FLAGS.RELAY_URL_OVERRIDE,
ctx.userId,
)) as RelayUrlPayload | null | undefined;
const override = payload?.url;
if (typeof override === "string" && override.length > 0) {
return { url: override };
const payload = (await posthog.getFeatureFlagPayload(
FEATURE_FLAGS.RELAY_URL_OVERRIDE,
ctx.userId,
)) as RelayUrlPayload | null | undefined;
const override = payload?.url;
if (isRelayUrl(override)) {
return { url: override };
🤖 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 36 - 42, Update the relay
override validation in the host handler around FEATURE_FLAGS.RELAY_URL_OVERRIDE
so it parses the string as a URL and returns it only when valid and using an
http: or https: protocol; otherwise continue to the existing env.RELAY_URL
fallback. Reject whitespace-only and malformed values.

@github-actions

github-actions Bot commented Aug 11, 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 7 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="apps/desktop/src/renderer/hooks/useRelayUrl/useRelayUrl.ts">

<violation number="1" location="apps/desktop/src/renderer/hooks/useRelayUrl/useRelayUrl.ts:14">
P1: Switching accounts without restarting can retain the prior user's relay URL and send the next user's remote-host requests to the wrong relay. Scope this query key to authenticated user ID or clear/invalidate it as part of sign-out.</violation>
</file>

<file name="packages/host-service/src/tunnel/connect.ts">

<violation number="1" location="packages/host-service/src/tunnel/connect.ts:30">
P2: Malformed `relay-url-override` payloads now override validated fallback URL and strand targeted hosts in reconnect failures; validate endpoint URL before accepting it, then retain fallback.</violation>
</file>

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

<violation number="1" location="packages/trpc/src/router/host/host.ts:44">
P2: PostHog failures silently send affected hosts/clients to the default relay, leaving relay-routing failures undiagnosable; log the caught error before fallback.

(Based on your team's feedback about observable async failures.)</violation>
</file>

<file name="packages/cli/src/lib/host/relay-url.ts">

<violation number="1" location="packages/cli/src/lib/host/relay-url.ts:10">
P2: The unit test's API mock in packages/cli/src/lib/host/spawn.test.ts still mocks `analytics.featureFlagPayload.query`, the PostHog call this change removes — it does not stub `host.relayEndpoint`, so the new path dereferences `api.host` (undefined) and throws, silently falling back inside the empty catch. The test still passes only because of the swallowed error, leaving the new relay-resolution code completely unexercised. Update `createApi()` to stub `host.relayEndpoint.query` returning e.g. `{ url: 'https://relay.test' }` and assert `RELAY_URL` is passed to the spawned host.</violation>

<violation number="2" location="packages/cli/src/lib/host/relay-url.ts:13">
P2: The empty `catch {}` silently swallows relay-resolution failures, so any API error here (network, or UNAUTHORIZED when the CLI authenticates via x-api-key instead of a bearer JWT) leaves the host spawning on the default `RELAY_URL` with no log — the exact silent-stranding scenario this fix exists to prevent. The identical helper in host-service (`resolveRelayUrl` in packages/host-service/src/tunnel/connect.ts) logs a `console.warn` with the error before falling back; mirror that here so a stranded host is observable.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant Desktop as Desktop Renderer
    participant CLI as CLI Host
    participant Deskmain as Desktop Main
    participant HSC as Host Service Coordinator
    participant HostSvc as Host Service
    participant API as API (tRPC Router)
    participant PH as PostHog
    participant Dispatch as Automation Dispatch

    Note over Desktop,API: Relay Endpoint Resolution (NEW centralized flow)

    alt Desktop Renderer needs relay URL
        Desktop->>API: host.relayEndpoint.query()
        API->>PH: getFeatureFlagPayload(relay-url-override, userId)
        PH-->>API: payload { url?: string }
        API-->>API: Read env.RELAY_URL as fallback
        API-->>Desktop: { url: string }
        Desktop->>Desktop: Use for WS connections (terminal, eventBus)
    else CLI resolves relay
        CLI->>API: host.relayEndpoint.query()
        API->>PH: getFeatureFlagPayload(relay-url-override, userId)
        PH-->>API: payload
        API-->>CLI: { url: string }
        CLI->>HostSvc: pass resolved relayUrl at spawn
    else Host Service at connect time
        HostSvc->>API: host.relayEndpoint.query() (with own credentials)
        API->>PH: getFeatureFlagPayload(relay-url-override, userId)
        PH-->>API: payload
        API-->>HostSvc: { url: string }
        HostSvc->>HostSvc: resolveRelayUrl() chooses API result over fallback
        HostSvc->>HostSvc: Use resolved relay for tunnel
    end

    Note over Dispatch,API: Automation Dispatch Flow (BUG FIX)

    Dispatch->>API: POST /dispatch/[id]
    API->>API: Lookup automation from DB
    API->>API: getRelayUrl(automation.ownerUserId)
    API->>PH: getFeatureFlagPayload(relay-url-override, ownerUserId)
    PH-->>API: payload { url: "wss://relay2..." }
    API-->>Dispatch: relayUrl = resolved override (not env.RELAY_URL)
    Dispatch->>Dispatch: dispatchAutomation({ relayUrl: resolved })
    Note over Dispatch: Run reaches the correct relay<br/>where the owner's host is tunneled

    Note over Desktop,API: Desktop Main (simplified - fallback only)
    Deskmain->>Deskmain: getRelayUrl() returns env.RELAY_URL
    Deskmain->>HSC: childEnv.RELAY_URL = fallback
    HSC->>HostSvc: Spawn with fallback
    HostSvc->>HostSvc: Override at connect time via resolveRelayUrl()

    alt API unreachable (all paths)
        Desktop->>Desktop: use env.RELAY_URL
        CLI->>CLI: use env.RELAY_URL
        HostSvc->>HostSvc: use options.relayUrl (fallback)
        Dispatch->>Dispatch: await getRelayUrl() throws?<br/>Uses env.RELAY_URL as fallback
    end
Loading

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

Re-trigger cubic

if (typeof override === "string" && override.length > 0) return override;
return env.RELAY_URL;
const { data } = useQuery({
queryKey: ["relay-endpoint"],

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: Switching accounts without restarting can retain the prior user's relay URL and send the next user's remote-host requests to the wrong relay. Scope this query key to authenticated user ID or clear/invalidate it as part of sign-out.

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 14:

<comment>Switching accounts without restarting can retain the prior user's relay URL and send the next user's remote-host requests to the wrong relay. Scope this query key to authenticated user ID or clear/invalidate it as part of sign-out.</comment>

<file context>
@@ -1,23 +1,20 @@
-	if (typeof override === "string" && override.length > 0) return override;
-	return env.RELAY_URL;
+	const { data } = useQuery({
+		queryKey: ["relay-endpoint"],
+		queryFn: () => apiTrpcClient.host.relayEndpoint.query(),
+		staleTime: 5 * 60 * 1000,
</file context>

): Promise<string> {
try {
const endpoint = await api.host.relayEndpoint.query();
if (endpoint?.url) return endpoint.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: Malformed relay-url-override payloads now override validated fallback URL and strand targeted hosts in reconnect failures; validate endpoint URL before accepting it, then retain fallback.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/host-service/src/tunnel/connect.ts, line 30:

<comment>Malformed `relay-url-override` payloads now override validated fallback URL and strand targeted hosts in reconnect failures; validate endpoint URL before accepting it, then retain fallback.</comment>

<file context>
@@ -7,13 +7,36 @@ import { TunnelClientV2 } from "./tunnel-client-v2";
+): Promise<string> {
+	try {
+		const endpoint = await api.host.relayEndpoint.query();
+		if (endpoint?.url) return endpoint.url;
+	} catch (error) {
+		console.warn(
</file context>
Suggested change
if (endpoint?.url) return endpoint.url;
if (endpoint?.url) {
try {
new URL(endpoint.url);
return endpoint.url;
} catch {
console.warn(
"[host-service] relay endpoint returned an invalid URL, using fallback:",
endpoint.url,
);
}
}

Comment on lines +44 to +46
} catch {
// Fall through to the default relay.
}

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: PostHog failures silently send affected hosts/clients to the default relay, leaving relay-routing failures undiagnosable; log the caught error before fallback.

(Based on your team's feedback about observable async failures.)

View Feedback

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>PostHog failures silently send affected hosts/clients to the default relay, leaving relay-routing failures undiagnosable; log the caught error before fallback.

(Based on your team's feedback about observable async failures.) </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 {
// Fall through to the default relay.
}
} catch (error) {
console.warn("[relay-endpoint] PostHog payload fetch failed:", error);
}

})) as RelayUrlPayload | null | undefined;
const override = payload?.url;
if (typeof override === "string" && override.length > 0) return override;
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.

P2: The unit test's API mock in packages/cli/src/lib/host/spawn.test.ts still mocks analytics.featureFlagPayload.query, the PostHog call this change removes — it does not stub host.relayEndpoint, so the new path dereferences api.host (undefined) and throws, silently falling back inside the empty catch. The test still passes only because of the swallowed error, leaving the new relay-resolution code completely unexercised. Update createApi() to stub host.relayEndpoint.query returning e.g. { url: 'https://relay.test' } and assert RELAY_URL is passed to the spawned host.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/cli/src/lib/host/relay-url.ts, line 10:

<comment>The unit test's API mock in packages/cli/src/lib/host/spawn.test.ts still mocks `analytics.featureFlagPayload.query`, the PostHog call this change removes — it does not stub `host.relayEndpoint`, so the new path dereferences `api.host` (undefined) and throws, silently falling back inside the empty catch. The test still passes only because of the swallowed error, leaving the new relay-resolution code completely unexercised. Update `createApi()` to stub `host.relayEndpoint.query` returning e.g. `{ url: 'https://relay.test' }` and assert `RELAY_URL` is passed to the spawned host.</comment>

<file context>
@@ -1,30 +1,16 @@
-		})) as RelayUrlPayload | null | undefined;
-		const override = payload?.url;
-		if (typeof override === "string" && override.length > 0) return override;
+		const endpoint = await api.host.relayEndpoint.query();
+		if (endpoint?.url) return endpoint.url;
 	} catch {
</file context>

} catch {
// Best-effort — fall back to env if the server is unreachable or
// returned an unexpected shape.
// Best-effort — fall back to the default relay.

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 empty catch {} silently swallows relay-resolution failures, so any API error here (network, or UNAUTHORIZED when the CLI authenticates via x-api-key instead of a bearer JWT) leaves the host spawning on the default RELAY_URL with no log — the exact silent-stranding scenario this fix exists to prevent. The identical helper in host-service (resolveRelayUrl in packages/host-service/src/tunnel/connect.ts) logs a console.warn with the error before falling back; mirror that here so a stranded host is observable.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/cli/src/lib/host/relay-url.ts, line 13:

<comment>The empty `catch {}` silently swallows relay-resolution failures, so any API error here (network, or UNAUTHORIZED when the CLI authenticates via x-api-key instead of a bearer JWT) leaves the host spawning on the default `RELAY_URL` with no log — the exact silent-stranding scenario this fix exists to prevent. The identical helper in host-service (`resolveRelayUrl` in packages/host-service/src/tunnel/connect.ts) logs a `console.warn` with the error before falling back; mirror that here so a stranded host is observable.</comment>

<file context>
@@ -1,30 +1,16 @@
 	} catch {
-		// Best-effort — fall back to env if the server is unreachable or
-		// returned an unexpected shape.
+		// Best-effort — fall back to the default relay.
 	}
-	return fallback;
</file context>

@saddlepaddle
saddlepaddle merged commit 922834a into main Aug 11, 2026
19 checks passed

This branch was previously deployed

1 inactive deployment
preview — 4fb6e017 Deployed Aug 11, 2026 by saddlepaddle via Deploy Docs #7418
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