Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/desktop/src-tauri/src/connections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,8 @@ impl ConnectionRuntimes {
ConnectionLifecycle::Error
};
entry.state.ready = false;
entry.state.tunnel_ready = None;
entry.state.local_mcp_ready = None;
entry.state.health = ConnectionHealth::Unknown;
entry.state.last_error = if success {
None
Expand Down Expand Up @@ -489,6 +491,8 @@ impl ConnectionRuntimes {
if self.update(id, generation, |state| {
state.lifecycle = ConnectionLifecycle::Error;
state.ready = false;
state.tunnel_ready = None;
state.local_mcp_ready = None;
state.health = ConnectionHealth::Degraded;
state.last_error = Some(failure);
if state.reason_code.is_none() {
Expand Down
20 changes: 19 additions & 1 deletion apps/desktop/src-tauri/src/connections/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,13 +255,26 @@ async fn optional_command_diagnostics_preserve_health_and_reset_for_a_new_proces
.runtime
.command_diagnostics
.is_none());
registry.stopping(id);
// End the child without cancelling the observer, as on an unexpected exit.
supervisor
.lock()
.await
.stop_checked(ProcessKey::RegularTunnel(id))
.await
.unwrap();
let deadline = Instant::now() + Duration::from_secs(8);
loop {
let mut current = snapshot(&[id]);
registry.project(&mut current, true);
let state = &current.profiles[0].runtime;
if state.lifecycle == ConnectionLifecycle::Error {
assert_eq!(state.tunnel_ready, None);
assert_eq!(state.local_mcp_ready, None);
break;
}
assert!(Instant::now() < deadline, "child exit was not observed: {current:?}");
tokio::time::sleep(Duration::from_millis(20)).await;
}
registry.stopped(id, true);
}

Expand Down Expand Up @@ -292,6 +305,11 @@ async fn concurrent_observers_are_independent_and_stale_generation_cannot_kill_r
.await
.unwrap();
registry.stopped(a, true);
let mut stopped = snapshot(&[a, b]);
registry.project(&mut stopped, true);
assert_eq!(stopped.profiles[0].runtime.tunnel_ready, None);
assert_eq!(stopped.profiles[0].runtime.local_mcp_ready, None);
assert_eq!(stopped.profiles[1].runtime.tunnel_ready, Some(true));
assert_eq!(
supervisor
.lock()
Expand Down
26 changes: 23 additions & 3 deletions apps/desktop/src/features/connection/ConnectionCard.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ describe("Connection advanced details", () => {
const profile = connectionFixture({
runtime_directory: path,
startup_timings_ms: { cli_total: 5540, initial_poll: 5510, poll_attempts: 1, poll_request_ms: 5502 },
tunnel_ready: true,
local_mcp_ready: false,
tunnel_ready: null,
local_mcp_ready: null,
process_ready: true,
process_started: true,
command_diagnostics: { rejected_commands: 2, terminal_response_delivery_failures: 1 },
Expand Down Expand Up @@ -63,7 +63,7 @@ describe("Connection advanced details", () => {
expect(pairs.has(connectionsToolsText(locale, key))).toBe(true);
}
expect(pairs.get(connectionsToolsText(locale, "processReady"))).toBe(connectionsToolsText(locale, "yes"));
expect(pairs.get(connectionsToolsText(locale, "localMcpReady"))).toBe(connectionsToolsText(locale, "no"));
expect(pairs.get(connectionsToolsText(locale, "localMcpReady"))).toBe("—");
expect(pairs.get(connectionsToolsText(locale, "pollRetryWait"))).toBe("8 ms");
expect(pairs.get(connectionsToolsText(locale, "runtimeDirectory"))).toBe(path);
expect(pairs.get(connectionsToolsText(locale, "rejectedCommands"))).toBe("2");
Expand All @@ -73,6 +73,26 @@ describe("Connection advanced details", () => {
expect(details?.querySelector("dd.connection-meta-path code:last-child")).toBeTruthy();
});

it.each(["tunnel_unavailable", null] as const)("distinguishes local access and automatic poll recovery with reason %s", (reason_code) => {
localStorage.setItem("webcodex.desktop.locale", "zh-CN");
const ready = connectionFixture({ lifecycle: "running", ready: true, tunnel_ready: true, local_mcp_ready: true });
const card = (profile: typeof ready) => <LocaleProvider>
<ConnectionCard profile={profile} canStart={true} busy={false} copied={false}
onAction={() => undefined} onEdit={() => undefined} onDelete={() => undefined}
onCopy={() => undefined} onSettings={() => undefined} />
</LocaleProvider>;
const { container, rerender } = render(card(ready));
const checks = () => Array.from(container.querySelectorAll("dl.connection-checks dd"), (check) => check.textContent);
expect(checks()).toEqual(["轮询正常", "可访问"]);

rerender(card({ ...ready, ready: false, tunnel_ready: false, last_error: "tunnel_unavailable", reason_code }));
expect(checks()).toEqual(["等待轮询自动恢复", "可访问"]);
expect(container.querySelector(".connection-recovery")).toBeNull();

rerender(card(ready));
expect(checks()).toEqual(["轮询正常", "可访问"]);
});

it("omits unavailable optional diagnostics without creating empty labels", () => {
const profile = connectionFixture({ startup_timings_ms: null, local_mcp_ready: null, runtime_directory: null });
const { container } = render(
Expand Down
16 changes: 12 additions & 4 deletions apps/desktop/src/features/connection/ConnectionCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,16 @@ export function ConnectionCard({ profile, canStart, busy, copied, onAction, onEd
const failed = !profile.ready && Boolean(profile.last_error || profile.lifecycle === "error");
const recovery = recoveryFor(profile);
const healthStale = profile.last_error === "health_stale";
const waitingForPoll = profile.lifecycle === "running" && profile.last_error === "tunnel_unavailable"
&& (profile.reason_code == null || profile.reason_code === "tunnel_unavailable")
&& profile.tunnel_ready === false && profile.local_mcp_ready === true;
const status = profile.server_restart_required
? c("pendingServerRestart")
: profile.ready
? p("running")
: failed
: waitingForPoll
? c("awaitingStatus")
: failed
? c("connectionUnavailable")
: profile.lifecycle === "starting"
? p("starting")
Expand Down Expand Up @@ -111,11 +116,14 @@ export function ConnectionCard({ profile, canStart, busy, copied, onAction, onEd
if (profile.local_mcp_url) detailRows.push({ label: "mcpAddress", value: <code>{profile.local_mcp_url}</code>, path: true });
if (profile.runtime_directory) detailRows.push({ label: "runtimeDirectory", value: <code>{profile.runtime_directory}</code>, path: true });
return <article className="connection-profile" aria-labelledby={`connection-${profile.id}`} data-tunnel-profile-id={profile.id}>
<header className="workspace-section-heading"><div><h2 id={`connection-${profile.id}`}>{profile.name}</h2><span className="workspace-observation">{owner}</span></div><span className={`connection-state ${profile.ready ? "ready" : ""}`} role="status"><i className={`status-dot ${profile.ready ? "ready" : failed ? "error" : "unknown"}`} aria-hidden="true" />{status}</span></header>
{(active || failed) && <dl className="connection-checks">{([[c("secureTunnel"), healthStale ? null : profile.tunnel_ready], [c("localMcp"), healthStale ? null : profile.local_mcp_ready]] as const).map(([label, ready]) => <div key={label}><dt>{label}</dt><dd><i className={`status-dot ${ready === true ? "ready" : ready === false ? "error" : "unknown"}`} aria-hidden="true" />{ready === true ? c("reachable") : ready === false ? c("unreachable") : healthStale ? c("awaitingStatus") : p("unknown")}</dd></div>)}</dl>}
<header className="workspace-section-heading"><div><h2 id={`connection-${profile.id}`}>{profile.name}</h2><span className="workspace-observation">{owner}</span></div><span className={`connection-state ${profile.ready ? "ready" : ""}`} role="status"><i className={`status-dot ${profile.ready ? "ready" : failed && !waitingForPoll ? "error" : "unknown"}`} aria-hidden="true" />{status}</span></header>
{(active || failed) && <dl className="connection-checks">{([
[c("secureTunnel"), healthStale || waitingForPoll ? null : profile.tunnel_ready, c("pollResponsive"), waitingForPoll ? c("pollRecovering") : undefined],
[c("localMcp"), healthStale ? null : profile.local_mcp_ready, c("reachable")],
] as const).map(([label, ready, readyLabel, waitingLabel]) => <div key={label}><dt>{label}</dt><dd><i className={`status-dot ${ready === true ? "ready" : ready === false ? "error" : "unknown"}`} aria-hidden="true" />{ready === true ? readyLabel : ready === false ? c("unreachable") : waitingLabel ?? (healthStale ? c("awaitingStatus") : p("unknown"))}</dd></div>)}</dl>}
<div className="connection-id"><span>{c("tunnelId")}</span><code>{profile.tunnel_id || "—"}</code>{profile.tunnel_id && <button type="button" className="text-button" aria-label={`${c("copyId")} ${profile.name}`} onClick={onCopy}>{copied ? p("copied") : c("copyId")}</button>}</div>
{profile.server_restart_required && <div className="connection-apply-note" role="status"><strong>{c("pendingServerRestart")}</strong><span>{c("profileRestartHelp")}</span></div>}
{failed && <div className="connection-recovery" role="status"><strong>{c(recovery.title)}</strong><p>{c(recovery.action)}</p>{autoProxyRecovery && <p>{c("autoProxyHint")}</p>}
{failed && !waitingForPoll && <div className="connection-recovery" role="status"><strong>{c(recovery.title)}</strong><p>{c(recovery.action)}</p>{autoProxyRecovery && <p>{c("autoProxyHint")}</p>}
<button type="button" className="secondary-button" onClick={() => onSettings(recovery.settings)}>{recovery.settings === "network" ? c("proxySettings") : s(recovery.settings === "runtime" ? "Runtime" : "Troubleshooting")}</button>
<p className="connection-impact">{c("chatgptImpact")}</p>
</div>}
Expand Down
2 changes: 2 additions & 0 deletions apps/desktop/src/i18n/connections-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ export const CONNECTIONS_TOOLS_MESSAGES = {
missingCredentials: ["Add a Tunnel ID and API key to start this connection.", "请编辑并填写 Tunnel ID 与 API key,再启动连接。", "Tunnel-ID und API-Key hinzufügen, um diese Verbindung zu starten.", "Ajoutez un Tunnel ID et une API Key pour démarrer cette connexion.", "Tunnel ID と API Key を設定して接続を開始してください。", "연결을 시작하려면 Tunnel ID와 API Key를 추가하세요.", "請編輯並填寫 Tunnel ID 與 API key,再啟動連線。"],
externalConnectionUnobserved: ["This page shows Tunnel connections saved in Desktop. External connections to this Server are not observed here. Manage independent deployments where they are configured.", "此页显示 Desktop 中保存的 Tunnel 连接。此 Server 的外部连接状态未在此观测;独立部署请使用其现有管理方式。", "Diese Seite zeigt in Desktop gespeicherte Tunnel-Verbindungen. Externe Verbindungen zu diesem Server werden hier nicht beobachtet. Unabhängige Installationen dort verwalten, wo sie eingerichtet sind.", "Cette page affiche les connexions Tunnel enregistrées dans Desktop. Les connexions externes à ce serveur ne sont pas observées ici. Gérez les déploiements indépendants là où ils sont configurés.", "このページには Desktop に保存した Tunnel 接続が表示されます。この Server の外部接続状態はここでは観測されません。独立した構成は既存の管理方法で管理してください。", "이 페이지는 Desktop에 저장된 Tunnel 연결을 표시합니다. 이 Server의 외부 연결 상태는 여기서 관찰하지 않습니다. 독립 배포는 기존 관리 방식으로 관리하세요.", "此頁顯示 Desktop 中儲存的 Tunnel 連線。此 Server 的外部連線狀態未在此觀測;獨立部署請使用其現有管理方式。"],
reachable: ["Reachable", "可访问", "Erreichbar", "Accessible", "アクセス可能", "접근 가능", "可訪問"],
pollResponsive: ["Polling OK", "轮询正常", "Abfrage erfolgreich", "Interrogation réussie", "ポーリング正常", "폴링 정상", "輪詢正常"],
pollRecovering: ["Waiting for polling to resume automatically", "等待轮询自动恢复", "Warten auf automatisches Fortsetzen der Abfrage", "Reprise automatique de l’interrogation en attente", "ポーリングの自動再開を待機中", "폴링 자동 재개 대기 중", "等待輪詢自動恢復"],
unreachable: ["Unreachable", "不可访问", "Nicht erreichbar", "Inaccessible", "アクセス不可", "접근 불가", "不可訪問"],
localMcp: ["Local MCP", "本机 MCP", "Lokales MCP", "MCP local", "ローカル MCP", "로컬 MCP", "本機 MCP"],

Expand Down
10 changes: 10 additions & 0 deletions crates/webcodex-openai-tunnel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,16 @@ live OpenAI service or real ChatGPT end-to-end acceptance.
`GET /health` returns the same snapshot as the library. These are loopback-only,
read-only observations: they do not claim that the target MCP server or ChatGPT
connector is ready. HTTP connections, request sizes and waits are bounded.
Poll readiness expires after one configured poll timeout without a new
successful poll, including when a full batch delays admission. Transport
failures clear readiness immediately. Within the existing retry policy the client
uses short polls until one succeeds, then returns to ordinary long polling.
Fast recovery polls wait up to six seconds for response headers, within the
configured request timeout. Every third recovery attempt after consecutive
failures uses the original budget so slow routes can reconnect. Body reads
continue under the original request deadline. After transport failures, the
recovery backoff caps at 3.2 seconds plus jitter. Retryable HTTP responses retain
the regular backoff and Retry-After policy.
The CLI owns a per-tunnel run marker using the same default location/key as the
embedded WebCodex host. Normal observed shutdown clears it. A crash or unconfirmed
effect retains it; first resolve prior work rather than deleting the marker or
Expand Down
41 changes: 30 additions & 11 deletions crates/webcodex-openai-tunnel/src/control_plane.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,26 @@ pub(crate) fn backoff(attempt: u32) -> Duration {
}
pub(crate) struct PollFailure {
pub error: Error,
pub delay: Duration,
/// A retryable HTTP response, including those without a Retry-After header.
pub retry_after: Option<Duration>,
}
impl From<Error> for PollFailure {
fn from(error: Error) -> Self {
Self {
error,
delay: Duration::ZERO,
retry_after: None,
}
}
}

pub(crate) enum PollPhase {
Short,
Steady,
FastRecovery,
}

const RECOVERY_HEADER_TIMEOUT: Duration = Duration::from_secs(6);

impl TunnelClient {
pub(crate) fn endpoint(&self, operation: &str) -> String {
format!(
Expand All @@ -60,22 +70,31 @@ impl TunnelClient {
pub(crate) async fn poll(
&self,
limit: usize,
startup: bool,
phase: PollPhase,
) -> Result<(Instant, Vec<Command>), PollFailure> {
// OpenAI's empty long poll can hold the first ready signal for 15s.
// A bounded 1s initial poll still requires a real successful response.
let timeout_ms = if startup { "1000" } else { "15000" };
let response = self
// Avoid waiting for an empty 15s long poll to confirm startup or recovery.
let timeout_ms = if matches!(phase, PollPhase::Steady) {
"15000"
} else {
"1000"
};
let request = self
.control
.get(self.endpoint("poll"))
.query(&[
("limit", limit.min(25).to_string()),
("timeout_ms", timeout_ms.into()),
])
.timeout(self.limits.poll_timeout)
.send()
.await
.map_err(|_| Error::Transport)?;
.send();
// Once headers arrive, preserve the configured budget for reading the body.
let response = match phase {
PollPhase::FastRecovery => tokio::time::timeout(RECOVERY_HEADER_TIMEOUT, request)
.await
.map_err(|_| Error::Transport)?,
_ => request.await,
}
.map_err(|_| Error::Transport)?;
// Capture headers receipt before decoding, including all time spent reading the body.
let received = Instant::now();
let status = response.status().as_u16();
Expand All @@ -94,7 +113,7 @@ impl TunnelClient {
300..=399 => Err(Error::Redirect.into()),
408 | 429 | 500..=599 => Err(PollFailure {
error: Error::Transport,
delay: retry_after(response.headers()),
retry_after: Some(retry_after(response.headers())),
}),
_ => Err(Error::Protocol.into()),
}
Expand Down
26 changes: 19 additions & 7 deletions crates/webcodex-openai-tunnel/src/health.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
use std::sync::{
atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
Arc,
use std::{
sync::{
atomic::{AtomicU64, AtomicUsize, Ordering},
Arc, Mutex,
},
time::Duration,
};
use tokio::time::Instant;

/// Safe, payload-free process-local observations. Readiness requires a successful poll.
#[derive(Clone, Default)]
pub struct Health(pub(crate) Arc<State>);
#[derive(Default)]
pub(crate) struct State {
pub ready: AtomicBool,
poll_ready_until: Mutex<Option<Instant>>,
/// Elapsed milliseconds until first successful control-plane poll (+1).
pub first_poll_ms_plus_one: AtomicU64,
/// Total requests and HTTP time before the first successful poll.
Expand Down Expand Up @@ -80,7 +84,11 @@ impl Health {
}
}
pub fn is_ready(&self) -> bool {
self.0.ready.load(Ordering::SeqCst)
self.0
.poll_ready_until
.lock()
.unwrap()
.is_some_and(|until| Instant::now() < until)
}
/// Payload-free, monotonic duration to the first successful remote poll.
pub fn initial_poll_ms(&self) -> Option<u64> {
Expand Down Expand Up @@ -122,8 +130,12 @@ impl Health {
pub fn rejected_commands(&self) -> usize {
self.0.rejected.load(Ordering::Relaxed)
}
pub(crate) fn ready(&self, ready: bool) {
self.0.ready.store(ready, Ordering::SeqCst);
pub(crate) fn poll_succeeded(&self, valid_for: Duration) {
*self.0.poll_ready_until.lock().unwrap() = Some(Instant::now() + valid_for);
}

pub(crate) fn clear_poll_readiness(&self) {
*self.0.poll_ready_until.lock().unwrap() = None;
}
}

Expand Down
Loading
Loading