diff --git a/connector/src/main.rs b/connector/src/main.rs index 863c16f..4dfe9ba 100644 --- a/connector/src/main.rs +++ b/connector/src/main.rs @@ -1,5 +1,6 @@ use std::borrow::Cow; use std::collections::{HashMap, HashSet}; +use std::time::Duration; use anyhow::Result; use audiopus::coder::Encoder as OpusEncoder; @@ -146,23 +147,54 @@ async fn main() { } } +/// tsclientlib's error `Display` impls mostly fall back to `{:?}` for nested +/// errors (e.g. `Failed to connect to server at "x": [Connect(TsProto(Timeout(..)))]`), +/// which is accurate but not something an end user can act on. Map the cases +/// that come up in practice to plain-language messages instead. +fn friendly_connect_error(address: &str, e: tsclientlib::Error) -> anyhow::Error { + match &e { + tsclientlib::Error::ConnectTs(inner) => { + anyhow::anyhow!("The server rejected the connection: {inner}") + } + tsclientlib::Error::InitserverTimeout => anyhow::anyhow!( + "The server did not finish logging us in within the timeout - please try again" + ), + _ if e.to_string().contains("Timeout") => anyhow::anyhow!( + "Could not reach \"{address}\": connection timed out. Check the address/port and that the server is reachable." + ), + _ => anyhow::anyhow!("Could not connect to \"{address}\": {e}"), + } +} + async fn run(args: Args) -> Result<()> { // stdout is a strict newline-delimited-JSON channel for the gateway to parse; // all diagnostic logging must go to stderr instead. tracing_subscriber::fmt().with_env_filter("warn").with_writer(std::io::stderr).init(); + let address = args.address.clone(); let con_config = Connection::build(args.address).name(args.nickname); - let mut con = con_config.connect()?; + let mut con = con_config.connect().map_err(|e| friendly_connect_error(&address, e))?; - // Wait for the initial book events (means we're logged in and have server state) - let r = con - .events() - .try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_)))) - .next() - .await; - if let Some(r) = r { - r?; + // Wait for the initial book events (means we're logged in and have server state). + // Bounded by a timeout: an unreachable host/port otherwise leaves this waiting + // forever with no error, since tsclientlib only reports failures through this + // event stream rather than from `connect()` itself. + const CONNECT_TIMEOUT_SECS: u64 = 15; + { + let mut login_events = + con.events().try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_)))); + match tokio::time::timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS), login_events.next()).await { + Ok(Some(r)) => { + r.map_err(|e| friendly_connect_error(&address, e))?; + } + Ok(None) => {} + Err(_) => { + anyhow::bail!( + "Could not reach \"{address}\": connection timed out after {CONNECT_TIMEOUT_SECS}s. Check the address/port and that the server is reachable." + ); + } + } } let welcome_message = con.get_state()?.server.welcome_message.clone(); diff --git a/web/src/App.css b/web/src/App.css index 2865ad8..5b89ac2 100644 --- a/web/src/App.css +++ b/web/src/App.css @@ -332,3 +332,27 @@ .ts-log-error { color: var(--log-error); } + +.ts-connect-error { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.75rem; + padding: 0.5rem 0.9rem; + background: var(--log-error); + color: #fff; + font-size: 13px; +} + +.ts-connect-error button { + background: transparent; + border: none; + color: #fff; + cursor: pointer; + font-size: 13px; + opacity: 0.85; +} + +.ts-connect-error button:hover { + opacity: 1; +} diff --git a/web/src/App.tsx b/web/src/App.tsx index 4a5a02f..19ded77 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -145,6 +145,8 @@ function App() { const [nickname, setNickname] = useState("Claude Code"); const [log, setLog] = useState([]); const [connected, setConnected] = useState(false); + const [connecting, setConnecting] = useState(false); + const [connectError, setConnectError] = useState(null); const [channels, setChannels] = useState([]); const [clients, setClients] = useState([]); const [chat, setChat] = useState([]); @@ -168,6 +170,7 @@ function App() { const audioPlayerRef = useRef(null); const micCaptureRef = useRef(null); const activeTabRef = useRef("channel"); + const hasConnectedRef = useRef(false); useEffect(() => { chatEndRef.current?.scrollIntoView({ block: "nearest" }); @@ -216,6 +219,10 @@ function App() { }; const handleConnect = () => { + hasConnectedRef.current = false; + setConnecting(true); + setConnectError(null); + const audioContext = new AudioContext({ sampleRate: SAMPLE_RATE }); audioContextRef.current = audioContext; audioPlayerRef.current = new AudioPlayer(audioContext); @@ -231,6 +238,9 @@ function App() { const data = JSON.parse(event.data); switch (data.type) { case "connected": + hasConnectedRef.current = true; + setConnecting(false); + setConnectError(null); setConnected(true); setServerChat((prev) => [...prev, { from: "Server", message: data.welcomeMessage }]); break; @@ -271,6 +281,8 @@ function App() { setTalkers(new Set(data.clients)); break; case "disconnected": + hasConnectedRef.current = false; + setConnecting(false); setConnected(false); setChannels([]); setClients([]); @@ -283,13 +295,29 @@ function App() { appendLog({ text: `Disconnected: ${data.reason}`, kind: "info" }); break; case "error": - appendLog({ text: data.message, kind: "error" }); + if (hasConnectedRef.current) { + appendLog({ text: data.message, kind: "error" }); + } else { + setConnecting(false); + setConnectError(data.message); + } break; } }; - socket.onerror = () => appendLog({ text: "WebSocket error (is the gateway running?)", kind: "error" }); + socket.onerror = () => { + if (!hasConnectedRef.current) { + setConnecting(false); + setConnectError("Could not reach the gateway - is it running?"); + } else { + appendLog({ text: "WebSocket error (is the gateway running?)", kind: "error" }); + } + }; socket.onclose = () => { + if (!hasConnectedRef.current) { + setConnecting(false); + setConnectError((prev) => prev ?? "Connection closed before the server responded"); + } setConnected(false); stopMic(); audioPlayerRef.current?.dispose(); @@ -384,14 +412,20 @@ function App() {
{!connected ? ( - + ) : ( )} @@ -445,6 +479,15 @@ function App() {
+ {connectError && ( +
+ ⚠️ {connectError} + +
+ )} +
{connected ? (