Skip to content

Commit ba776b9

Browse files
wpfleger96npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
andauthored
feat(desktop): add configurable transport reconnect hook (#1059)
Adds a build-time-configured transport reconnect hook so internal builds can recover the underlying transport (e.g. WARP VPN) before the relay reconnect, while OSS builds stay a pure no-op. The generic "Reconnect to relay" button is transport-agnostic; internal users behind a VPN need the transport re-established first. A build-time env var `BUZZ_BUILD_RELAY_RECONNECT_CMD` (set only in `squareup/buzz-releases`) carries a JSON config validated into a typed Rust struct at compile time, so the OSS binary ships with zero VPN knowledge. - New Tauri command `relay_reconnect_hook` runs structured fixed-argv steps plus a readiness probe, wrapped in `tokio::task::spawn_blocking`; non-fatal end-to-end so any failure falls through to `preconnect()`. - `ReconnectHookConfig` lives in one dep-free source file `include!`'d by both `build.rs` and the runtime command, so the compile-time validation and runtime parse cannot drift. - `useReconnectRelay.ts` invokes the hook before relay preconnect, guarded so a hook rejection cannot abort the reconnect. - When `BUZZ_BUILD_RELAY_RECONNECT_CMD` is unset (OSS), the command compiles to an early-return no-op. Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@sprout-oss.stage.blox.sqprod.co>
1 parent 2300248 commit ba776b9

12 files changed

Lines changed: 451 additions & 24 deletions

File tree

‎desktop/playwright.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ export default defineConfig({
3838
"**/spoiler.spec.ts",
3939
"**/mentions.spec.ts",
4040
"**/relay-reconnect.spec.ts",
41+
"**/relay-reconnect-screenshots.spec.ts",
4142
"**/workflows.spec.ts",
4243
"**/identity-archive.spec.ts",
4344
"**/identity-archive-hide.spec.ts",

‎desktop/src-tauri/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ default = []
2121
mesh-llm = ["dep:mesh-llm-sdk", "dep:mesh-llm-host-runtime"]
2222

2323
[build-dependencies]
24+
serde = { version = "1", features = ["derive"] }
25+
serde_json = "1"
2426
tauri-build = { version = "2", features = [] }
2527

2628
[target.'cfg(unix)'.dependencies]

‎desktop/src-tauri/build.rs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
1+
// Shared schema, included from the same source the runtime command parses with,
2+
// so the build-time validation below and the runtime parse cannot drift.
3+
include!("src/commands/reconnect_hook_config.rs");
4+
15
fn main() {
26
println!("cargo:rerun-if-env-changed=BUZZ_RELAY_URL");
37
println!("cargo:rerun-if-env-changed=BUZZ_RELAY_HTTP");
48
println!("cargo:rerun-if-env-changed=BUZZ_UPDATER_PUBLIC_KEY");
59
println!("cargo:rerun-if-env-changed=BUZZ_UPDATER_ENDPOINT");
610
println!("cargo:rerun-if-env-changed=BUZZ_BUILD_DATABRICKS_HOST");
711
println!("cargo:rerun-if-env-changed=BUZZ_BUILD_DATABRICKS_MODEL");
12+
println!("cargo:rerun-if-env-changed=BUZZ_BUILD_RELAY_RECONNECT_CMD");
813
println!("cargo:rustc-check-cfg=cfg(buzz_updater_enabled)");
914

1015
if let Ok(relay_url) = std::env::var("BUZZ_RELAY_URL") {
@@ -23,6 +28,15 @@ fn main() {
2328
println!("cargo:rustc-env=BUZZ_DESKTOP_BUILD_DATABRICKS_MODEL={model}");
2429
}
2530

31+
if let Ok(val) = std::env::var("BUZZ_BUILD_RELAY_RECONNECT_CMD") {
32+
let parsed: serde_json::Value = serde_json::from_str(&val)
33+
.unwrap_or_else(|e| panic!("BUZZ_BUILD_RELAY_RECONNECT_CMD is not valid JSON: {e}"));
34+
serde_json::from_value::<ReconnectHookConfig>(parsed).unwrap_or_else(|e| {
35+
panic!("BUZZ_BUILD_RELAY_RECONNECT_CMD doesn't match ReconnectHookConfig: {e}")
36+
});
37+
println!("cargo:rustc-env=BUZZ_DESKTOP_BUILD_RELAY_RECONNECT_CMD={val}");
38+
}
39+
2640
let updater_public_key = std::env::var("BUZZ_UPDATER_PUBLIC_KEY")
2741
.ok()
2842
.map(|value| value.trim().to_string())

‎desktop/src-tauri/src/commands/mod.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ mod personas;
2222
mod prevent_sleep;
2323
mod profile;
2424
mod relay_members;
25+
mod relay_reconnect;
2526
mod social;
2627
mod teams;
2728
mod workflows;
@@ -49,6 +50,7 @@ pub use personas::*;
4950
pub use prevent_sleep::*;
5051
pub use profile::*;
5152
pub use relay_members::*;
53+
pub use relay_reconnect::*;
5254
pub use social::*;
5355
pub use teams::*;
5456
pub use workflows::*;
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Canonical `ReconnectHookConfig` definition, `include!`d into BOTH
2+
// `build.rs` (compile-time validation) and `commands/relay_reconnect.rs`
3+
// (runtime deserialization). build scripts cannot import from the crate, so
4+
// sharing the source via `include!` is what guarantees the build-time check
5+
// and the runtime parse use an identical schema — zero drift surface.
6+
//
7+
// Keep this file dependency-free: only `serde` derives, no crate-internal
8+
// imports. Both consumers have `serde` available.
9+
10+
/// Typed config carried by the build-time env var `BUZZ_BUILD_RELAY_RECONNECT_CMD`.
11+
#[derive(Debug, Clone, serde::Deserialize)]
12+
#[serde(rename_all = "camelCase")]
13+
#[allow(dead_code)] // build.rs only constructs it for validation
14+
pub struct ReconnectHookConfig {
15+
/// Ordered commands to run. Each inner vec is [program, arg1, arg2, ...].
16+
pub steps: Vec<Vec<String>>,
17+
/// Command whose stdout is polled for readiness after steps complete.
18+
pub ready_probe: Vec<String>,
19+
/// RAW SUBSTRING matched in the probe's stdout to consider the transport
20+
/// ready — NOT a parsed field. Pick a token unlikely to collide with other
21+
/// substrings in the probe output (e.g. `warp-cli -j status` JSON, where
22+
/// "Connected" can collide with "Connecting"/"Disconnected").
23+
pub ready_match: String,
24+
/// Per-process wall-clock cap (ms) for each step and the readiness probe
25+
/// phase; non-fatal on expiry — the generic relay reconnect still fires.
26+
pub timeout_ms: u64,
27+
}
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
//! Configurable transport-reconnect hook.
2+
//!
3+
//! When the build-time env var `BUZZ_BUILD_RELAY_RECONNECT_CMD` is set (internal
4+
//! builds), this command runs an ordered sequence of subprocess steps followed by
5+
//! a readiness poll before the frontend fires the relay WebSocket reconnect.
6+
//!
7+
//! OSS builds (env var unset) get a pure no-op — zero WARP knowledge compiled in.
8+
9+
// Single source of truth for the config schema, shared with build.rs via
10+
// `include!`. See reconnect_hook_config.rs for why this is shared, not a module.
11+
include!("reconnect_hook_config.rs");
12+
13+
#[tauri::command]
14+
pub async fn relay_reconnect_hook() -> Result<(), String> {
15+
let Some(config_str) = option_env!("BUZZ_DESKTOP_BUILD_RELAY_RECONNECT_CMD") else {
16+
return Ok(()); // OSS build — no-op
17+
};
18+
19+
// Safe: build.rs already validated this parses correctly against the same schema.
20+
let config: ReconnectHookConfig = serde_json::from_str(config_str)
21+
.map_err(|e| format!("reconnect hook config parse error: {e}"))?;
22+
23+
// spawn_blocking because the desktop Tauri crate doesn't enable tokio's
24+
// `process` feature; std::process::Command + thread::sleep are synchronous
25+
// and must not run on an async worker. The whole hook is non-fatal — a join
26+
// failure logs and returns Ok so the frontend's relay reconnect still fires.
27+
if let Err(e) = tokio::task::spawn_blocking(move || run_hook(&config)).await {
28+
eprintln!("[relay_reconnect_hook] task join failed: {e}");
29+
}
30+
31+
Ok(())
32+
}
33+
34+
/// Run a fixed-argv command (`argv[0]` + `argv[1..]`) with a wall-clock cap.
35+
///
36+
/// `std::process::Command::output()` blocks until the child exits — a wedged
37+
/// `warp-cli` (the exact degraded-transport case this hook targets) would hang
38+
/// forever, pinning the blocking-pool thread and leaving the frontend `invoke`
39+
/// unresolved. So we spawn, poll `try_wait()` every 500ms, and kill+reap on the
40+
/// deadline. Modeled on `media_transcode.rs` `run_ffmpeg_with_timeout`.
41+
///
42+
/// stdout/stderr are piped and read only after the child exits. The pipe-buffer
43+
/// deadlock noted there (a child blocking on write() when the ~64 KiB OS pipe
44+
/// fills) does not apply: `warp-cli` emits a few lines, far below the buffer.
45+
fn run_with_timeout(
46+
argv: &[String],
47+
timeout: std::time::Duration,
48+
) -> Result<std::process::Output, String> {
49+
let mut child = std::process::Command::new(&argv[0])
50+
.args(&argv[1..])
51+
.stdout(std::process::Stdio::piped())
52+
.stderr(std::process::Stdio::null())
53+
.spawn()
54+
.map_err(|e| format!("spawn failed: {e}"))?;
55+
56+
let deadline = std::time::Instant::now() + timeout;
57+
loop {
58+
match child.try_wait() {
59+
Ok(Some(status)) => {
60+
let stdout = child.stdout.take().map_or_else(Vec::new, |mut s| {
61+
let mut buf = Vec::new();
62+
let _ = std::io::Read::read_to_end(&mut s, &mut buf);
63+
buf
64+
});
65+
return Ok(std::process::Output {
66+
status,
67+
stdout,
68+
stderr: Vec::new(),
69+
});
70+
}
71+
Ok(None) => {
72+
if std::time::Instant::now() > deadline {
73+
let _ = child.kill();
74+
let _ = child.wait(); // reap zombie
75+
return Err(format!("timed out after {}ms", timeout.as_millis()));
76+
}
77+
std::thread::sleep(std::time::Duration::from_millis(500));
78+
}
79+
Err(e) => return Err(format!("wait failed: {e}")),
80+
}
81+
}
82+
}
83+
84+
/// Runs the configured steps then polls the readiness probe. Every failure is
85+
/// logged and swallowed — the caller treats the hook as best-effort.
86+
fn run_hook(config: &ReconnectHookConfig) {
87+
let cap = std::time::Duration::from_millis(config.timeout_ms);
88+
89+
// Run each step sequentially (fixed-argv, no shell). Each step is capped at
90+
// `timeout_ms` so a hung child can't stall the whole hook — on cap it's
91+
// killed, logged, and we move on, same non-fatal contract as a spawn error.
92+
for step in &config.steps {
93+
if step.is_empty() {
94+
continue;
95+
}
96+
match run_with_timeout(step, cap) {
97+
Ok(o) if !o.status.success() => {
98+
eprintln!("[relay_reconnect_hook] step {:?} exited {}", step, o.status);
99+
}
100+
Err(e) => {
101+
eprintln!("[relay_reconnect_hook] step {:?} failed: {e}", step);
102+
}
103+
_ => {}
104+
}
105+
}
106+
107+
// Poll readiness probe until match or timeout.
108+
if config.ready_probe.is_empty() {
109+
return;
110+
}
111+
let deadline = std::time::Instant::now() + cap;
112+
while std::time::Instant::now() < deadline {
113+
// Cap each probe at the time left to the deadline, so one wedged probe
114+
// can't push the total probe phase past `timeout_ms`.
115+
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
116+
match run_with_timeout(&config.ready_probe, remaining) {
117+
Ok(output) if String::from_utf8_lossy(&output.stdout).contains(&config.ready_match) => {
118+
return;
119+
}
120+
Err(e) => {
121+
eprintln!("[relay_reconnect_hook] probe failed: {e}");
122+
}
123+
_ => {}
124+
}
125+
std::thread::sleep(std::time::Duration::from_secs(1));
126+
}
127+
}

‎desktop/src-tauri/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -838,6 +838,7 @@ pub fn run() {
838838
get_active_workspace,
839839
set_prevent_sleep_active,
840840
get_agent_memory,
841+
relay_reconnect_hook,
841842
])
842843
.build(tauri::generate_context!())
843844
.expect("error while building tauri application");

‎desktop/src/features/sidebar/ui/AppSidebar.tsx‎

Lines changed: 37 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ import {
99
MessageCirclePlus,
1010
Zap,
1111
} from "lucide-react";
12+
import {
13+
isRelayConnectionDegraded,
14+
useRelayConnection,
15+
} from "@/shared/api/useRelayConnection";
1216
import { useReconnectRelay } from "@/shared/api/useReconnectRelay";
1317
import {
1418
isRelayUnreachableError,
@@ -282,6 +286,18 @@ export function AppSidebar({
282286

283287
const { isPending: isReconnectPending, reconnect } = useReconnectRelay();
284288

289+
// The sidebar reconnect prompt must surface the moment the relay drops, not
290+
// only after `channelsQuery` finally errors (it has a 60s staleTime +
291+
// refetchInterval, so the error lags 60-120s behind a dropped socket).
292+
// OR-in the live, debounced connection state — same signal that drives
293+
// ConnectionBanner — so the prompt flips within ~2s of degradation.
294+
const relayConnectionState = useRelayConnection();
295+
const hasRelayUnreachableError = errorMessage
296+
? isRelayUnreachableError(errorMessage)
297+
: false;
298+
const isRelayConnectionDegradedNow =
299+
hasRelayUnreachableError || isRelayConnectionDegraded(relayConnectionState);
300+
285301
const [createSectionState, setCreateSectionState] = React.useState<{
286302
open: boolean;
287303
pendingChannelId: string | null;
@@ -722,30 +738,28 @@ export function AppSidebar({
722738
</>
723739
) : null}
724740

725-
{errorMessage ? (
726-
isRelayUnreachableError(errorMessage) ? (
727-
<div
728-
className="px-3 py-2 text-sm"
729-
data-testid="sidebar-relay-unreachable"
741+
{isRelayConnectionDegradedNow ? (
742+
<div
743+
className="px-3 py-2 text-sm"
744+
data-testid="sidebar-relay-unreachable"
745+
>
746+
<span className="text-muted-foreground">
747+
{RELAY_UNREACHABLE_SHORT}{" "}
748+
</span>
749+
<button
750+
className="text-primary hover:underline disabled:opacity-50"
751+
data-testid="sidebar-reconnect"
752+
disabled={isReconnectPending}
753+
onClick={() => void reconnect()}
754+
type="button"
730755
>
731-
<span className="text-muted-foreground">
732-
{RELAY_UNREACHABLE_SHORT}{" "}
733-
</span>
734-
<button
735-
className="text-primary hover:underline disabled:opacity-50"
736-
data-testid="sidebar-reconnect"
737-
disabled={isReconnectPending}
738-
onClick={() => void reconnect()}
739-
type="button"
740-
>
741-
{isReconnectPending ? "Reconnecting…" : "Reconnect"}
742-
</button>
743-
</div>
744-
) : (
745-
<div className="px-3 py-2 text-sm text-destructive">
746-
{errorMessage}
747-
</div>
748-
)
756+
{isReconnectPending ? "Reconnecting…" : "Reconnect"}
757+
</button>
758+
</div>
759+
) : errorMessage ? (
760+
<div className="px-3 py-2 text-sm text-destructive">
761+
{errorMessage}
762+
</div>
749763
) : null}
750764
</SidebarContent>
751765

‎desktop/src/features/sidebar/ui/SidebarProfileCard.tsx‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ import type { Workspace } from "@/features/workspaces/types";
1010
import { WorkspaceSwitcher } from "@/features/workspaces/ui/WorkspaceSwitcher";
1111
import type { PresenceStatus, Profile, UserStatus } from "@/shared/api/types";
1212
import { useReconnectRelay } from "@/shared/api/useReconnectRelay";
13+
import {
14+
isRelayConnectionDegraded,
15+
useRelayConnection,
16+
} from "@/shared/api/useRelayConnection";
1317
import { cn } from "@/shared/lib/cn";
1418

1519
type SidebarProfileCardProps = {
@@ -54,6 +58,12 @@ export function SidebarProfileCard({
5458
// workspace-provider and QueryClient safe at this level.
5559
const selfProfileCache = useSelfProfileCache();
5660
const { isPending, reconnect } = useReconnectRelay();
61+
// Only offer reconnect when the relay is actually degraded — keep the item
62+
// visible while a reconnect is in flight so it does not vanish mid-click if
63+
// the live state briefly flips.
64+
const isRelayConnectionDegradedNow = isRelayConnectionDegraded(
65+
useRelayConnection(),
66+
);
5767

5868
const [profilePopoverOpen, setProfilePopoverOpen] = React.useState(false);
5969
const profileCardRef = React.useRef<HTMLDivElement | null>(null);
@@ -134,7 +144,11 @@ export function SidebarProfileCard({
134144
isStatusPending={isPresencePending}
135145
onClearUserStatus={onClearUserStatus}
136146
onOpenSettings={onOpenSettings}
137-
onReconnect={() => void reconnect()}
147+
onReconnect={
148+
isRelayConnectionDegradedNow || isPending
149+
? () => void reconnect()
150+
: undefined
151+
}
138152
onSetStatus={onSetPresenceStatus ?? (() => {})}
139153
onSetUserStatus={onSetUserStatus}
140154
triggerContainerRef={profileCardRef}

‎desktop/src/shared/api/useReconnectRelay.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
import * as React from "react";
1313
import { useQueryClient } from "@tanstack/react-query";
14+
import { invoke } from "@tauri-apps/api/core";
1415
import { toast } from "sonner";
1516

1617
import { relayClient } from "@/shared/api/relayClient";
@@ -31,6 +32,14 @@ export function useReconnectRelay(): {
3132
inFlightRef.current = true;
3233
setIsPending(true);
3334
try {
35+
// Run transport-layer reconnect hook (e.g. WARP VPN re-auth for internal builds).
36+
// No-op in OSS builds. Non-fatal — transport failure shouldn't block relay reconnect.
37+
try {
38+
await invoke("relay_reconnect_hook");
39+
} catch (err) {
40+
console.warn("[useReconnectRelay] reconnect hook failed:", err);
41+
}
42+
3443
await relayClient.preconnect();
3544
await queryClient.invalidateQueries();
3645
// No success toast — the banner auto-hides once the connection state

0 commit comments

Comments
 (0)