mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-03 01:42:50 +08:00
Surface connection errors clearly instead of hanging or failing silently
Bounds the connector's initial connect/login wait with a 15s timeout (an unreachable host previously hung forever with no error), rewrites tsclientlib's Debug-formatted errors into plain text, and adds a connecting/error UI state in the frontend with a dismissible banner instead of burying failures in the bottom log. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
02c5335a65
commit
4306da474b
3 files changed
+113
-14
No files matched your search
+41
-9
@@ -1,5 +1,6 @@
|
|||||||
use std::borrow::Cow;
|
use std::borrow::Cow;
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use audiopus::coder::Encoder as OpusEncoder;
|
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<()> {
|
async fn run(args: Args) -> Result<()> {
|
||||||
// stdout is a strict newline-delimited-JSON channel for the gateway to parse;
|
// stdout is a strict newline-delimited-JSON channel for the gateway to parse;
|
||||||
// all diagnostic logging must go to stderr instead.
|
// all diagnostic logging must go to stderr instead.
|
||||||
tracing_subscriber::fmt().with_env_filter("warn").with_writer(std::io::stderr).init();
|
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 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)
|
// Wait for the initial book events (means we're logged in and have server state).
|
||||||
let r = con
|
// Bounded by a timeout: an unreachable host/port otherwise leaves this waiting
|
||||||
.events()
|
// forever with no error, since tsclientlib only reports failures through this
|
||||||
.try_filter(|e| future::ready(matches!(e, StreamItem::BookEvents(_))))
|
// event stream rather than from `connect()` itself.
|
||||||
.next()
|
const CONNECT_TIMEOUT_SECS: u64 = 15;
|
||||||
.await;
|
{
|
||||||
if let Some(r) = r {
|
let mut login_events =
|
||||||
r?;
|
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();
|
let welcome_message = con.get_state()?.server.welcome_message.clone();
|
||||||
|
|||||||
@@ -332,3 +332,27 @@
|
|||||||
.ts-log-error {
|
.ts-log-error {
|
||||||
color: var(--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;
|
||||||
|
}
|
||||||
+48
-5
@@ -145,6 +145,8 @@ function App() {
|
|||||||
const [nickname, setNickname] = useState("Claude Code");
|
const [nickname, setNickname] = useState("Claude Code");
|
||||||
const [log, setLog] = useState<LogEntry[]>([]);
|
const [log, setLog] = useState<LogEntry[]>([]);
|
||||||
const [connected, setConnected] = useState(false);
|
const [connected, setConnected] = useState(false);
|
||||||
|
const [connecting, setConnecting] = useState(false);
|
||||||
|
const [connectError, setConnectError] = useState<string | null>(null);
|
||||||
const [channels, setChannels] = useState<ChannelInfo[]>([]);
|
const [channels, setChannels] = useState<ChannelInfo[]>([]);
|
||||||
const [clients, setClients] = useState<ClientInfo[]>([]);
|
const [clients, setClients] = useState<ClientInfo[]>([]);
|
||||||
const [chat, setChat] = useState<ChatEntry[]>([]);
|
const [chat, setChat] = useState<ChatEntry[]>([]);
|
||||||
@@ -168,6 +170,7 @@ function App() {
|
|||||||
const audioPlayerRef = useRef<AudioPlayer | null>(null);
|
const audioPlayerRef = useRef<AudioPlayer | null>(null);
|
||||||
const micCaptureRef = useRef<MicCapture | null>(null);
|
const micCaptureRef = useRef<MicCapture | null>(null);
|
||||||
const activeTabRef = useRef<ActiveTab>("channel");
|
const activeTabRef = useRef<ActiveTab>("channel");
|
||||||
|
const hasConnectedRef = useRef(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
chatEndRef.current?.scrollIntoView({ block: "nearest" });
|
chatEndRef.current?.scrollIntoView({ block: "nearest" });
|
||||||
@@ -216,6 +219,10 @@ function App() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleConnect = () => {
|
const handleConnect = () => {
|
||||||
|
hasConnectedRef.current = false;
|
||||||
|
setConnecting(true);
|
||||||
|
setConnectError(null);
|
||||||
|
|
||||||
const audioContext = new AudioContext({ sampleRate: SAMPLE_RATE });
|
const audioContext = new AudioContext({ sampleRate: SAMPLE_RATE });
|
||||||
audioContextRef.current = audioContext;
|
audioContextRef.current = audioContext;
|
||||||
audioPlayerRef.current = new AudioPlayer(audioContext);
|
audioPlayerRef.current = new AudioPlayer(audioContext);
|
||||||
@@ -231,6 +238,9 @@ function App() {
|
|||||||
const data = JSON.parse(event.data);
|
const data = JSON.parse(event.data);
|
||||||
switch (data.type) {
|
switch (data.type) {
|
||||||
case "connected":
|
case "connected":
|
||||||
|
hasConnectedRef.current = true;
|
||||||
|
setConnecting(false);
|
||||||
|
setConnectError(null);
|
||||||
setConnected(true);
|
setConnected(true);
|
||||||
setServerChat((prev) => [...prev, { from: "Server", message: data.welcomeMessage }]);
|
setServerChat((prev) => [...prev, { from: "Server", message: data.welcomeMessage }]);
|
||||||
break;
|
break;
|
||||||
@@ -271,6 +281,8 @@ function App() {
|
|||||||
setTalkers(new Set<number>(data.clients));
|
setTalkers(new Set<number>(data.clients));
|
||||||
break;
|
break;
|
||||||
case "disconnected":
|
case "disconnected":
|
||||||
|
hasConnectedRef.current = false;
|
||||||
|
setConnecting(false);
|
||||||
setConnected(false);
|
setConnected(false);
|
||||||
setChannels([]);
|
setChannels([]);
|
||||||
setClients([]);
|
setClients([]);
|
||||||
@@ -283,13 +295,29 @@ function App() {
|
|||||||
appendLog({ text: `Disconnected: ${data.reason}`, kind: "info" });
|
appendLog({ text: `Disconnected: ${data.reason}`, kind: "info" });
|
||||||
break;
|
break;
|
||||||
case "error":
|
case "error":
|
||||||
appendLog({ text: data.message, kind: "error" });
|
if (hasConnectedRef.current) {
|
||||||
|
appendLog({ text: data.message, kind: "error" });
|
||||||
|
} else {
|
||||||
|
setConnecting(false);
|
||||||
|
setConnectError(data.message);
|
||||||
|
}
|
||||||
break;
|
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 = () => {
|
socket.onclose = () => {
|
||||||
|
if (!hasConnectedRef.current) {
|
||||||
|
setConnecting(false);
|
||||||
|
setConnectError((prev) => prev ?? "Connection closed before the server responded");
|
||||||
|
}
|
||||||
setConnected(false);
|
setConnected(false);
|
||||||
stopMic();
|
stopMic();
|
||||||
audioPlayerRef.current?.dispose();
|
audioPlayerRef.current?.dispose();
|
||||||
@@ -384,14 +412,20 @@ function App() {
|
|||||||
<div className="ts-toolbar-fields">
|
<div className="ts-toolbar-fields">
|
||||||
<label>
|
<label>
|
||||||
Server
|
Server
|
||||||
<input value={host} onChange={(e) => setHost(e.target.value)} disabled={connected} />
|
<input value={host} onChange={(e) => setHost(e.target.value)} disabled={connected || connecting} />
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
Nickname
|
Nickname
|
||||||
<input value={nickname} onChange={(e) => setNickname(e.target.value)} disabled={connected} />
|
<input
|
||||||
|
value={nickname}
|
||||||
|
onChange={(e) => setNickname(e.target.value)}
|
||||||
|
disabled={connected || connecting}
|
||||||
|
/>
|
||||||
</label>
|
</label>
|
||||||
{!connected ? (
|
{!connected ? (
|
||||||
<button onClick={handleConnect}>Connect</button>
|
<button onClick={handleConnect} disabled={connecting}>
|
||||||
|
{connecting ? "Connecting…" : "Connect"}
|
||||||
|
</button>
|
||||||
) : (
|
) : (
|
||||||
<button onClick={handleDisconnect}>Disconnect</button>
|
<button onClick={handleDisconnect}>Disconnect</button>
|
||||||
)}
|
)}
|
||||||
@@ -445,6 +479,15 @@ function App() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{connectError && (
|
||||||
|
<div className="ts-connect-error">
|
||||||
|
<span>⚠️ {connectError}</span>
|
||||||
|
<button onClick={() => setConnectError(null)} title="Dismiss">
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="ts-body">
|
<div className="ts-body">
|
||||||
<div className="ts-tree-panel">
|
<div className="ts-tree-panel">
|
||||||
{connected ? (
|
{connected ? (
|
||||||
|
|||||||
Reference in new issue
Block a user