Skip to content

feat(core): surface mid-session transport failures via lastError (#1323) - #1489

Merged
cliffhall merged 3 commits into
v2/mainfrom
feat/1323-error-event-surface
Jun 15, 2026
Merged

cliffhall merged 3 commits into
v2/mainfrom
feat/1323-error-event-surface

Conversation

@cliffhall

Copy link
Copy Markdown
Member

Closes #1323

Background

useInspectorClient exposes status driven by the OAuth/XState machine inside InspectorClient. The status can transition connected → error when a transport dies mid-session (stdio subprocess crash, SSE stream drop, HTTP 5xx). Before this change, callers saw the status flip but not the reason: #1244 wired App.tsx to capture errorMessage only from client.connect()'s rejection (handshake-only), so a state-machine transition to "error" after a successful connect left the UI's error stale or unset.

What changed

  • InspectorClientEventMap.error — documented as the signal for status → "error" transitions that happen outside an awaited promise (the transport's onerror). The Error carries the reason (.message, optional .cause).
  • inspectorClient.ts — the awaited connect() catch no longer dispatches error. The caller already gets the reason via the rejected promise, so a second dispatch would double-report a handshake failure. The transport onerror path (the genuine mid-session case) still dispatches, unchanged.
  • useInspectorClient — new lastError?: string on the return type, set from the error event and cleared at the next connecting edge (and on client swap / null) so a reconnect starts clean.
  • App.tsx — toasts a mid-session failure (red, with the reason), naming the active server via a ref that survives the disconnect-driven activeServerId reset. The stale TODO(#1323) marker at the connect catch is updated.

Out of scope

  • Reconnection UX (per the issue). This only surfaces the reason.

Tests

  • useInspectorClient.test.tsx: captures lastError from the event, clears it on the connecting edge, keeps it across the error status transition, and resets on client swap / null.
  • inspectorClient.test.ts (integration): the transport onerror emits error + sets status: "error"; a handshake rejection sets status: "error" without emitting error.
  • App.test.tsx: generic "Connection lost" toast when no server is active, and a server-named toast after a session has connected.

Full validate, unit (2332), integration (128), storybook (362), CLI (88), and TUI (2) suites pass.

🤖 Generated with Claude Code

A `connected → error` transition from a transport that dies mid-session
(stdio crash, SSE drop, HTTP 5xx) fires the client's `error` event but
bypasses the `connect()` rejection path, so App.tsx's handshake-only catch
left `errorMessage` stale/unset.

- Document `error` on InspectorClientEventMap as the non-awaited
  (mid-session) failure signal.
- Stop dispatching `error` from the awaited `connect()` catch: the caller
  already gets the reason via the rejected promise, so a second surface
  would double-report a handshake failure.
- Expose `lastError?: string` on `useInspectorClient`, set from the `error`
  event and cleared at the next connecting edge (and on client swap/null).
- Toast mid-session failures in App.tsx, naming the active server via a ref
  that survives the disconnect-driven activeServerId reset; update the
  stale TODO(#1323) marker at the connect catch.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cliffhall cliffhall added the v2 Issues and PRs for v2 label Jun 15, 2026
@cliffhall

Copy link
Copy Markdown
Member Author

@claude review

@claude

claude Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @cliffhall's task in 2m 36s —— View job


Review: surface mid-session transport failures via lastError (#1323)

  • Read changed files & diff vs origin/v2/main
  • Review core changes (inspectorClient.ts, inspectorClientEventTarget.ts, useInspectorClient.ts)
  • Review App.tsx integration
  • Review tests
  • Post review feedback

Overall this is a clean, well-scoped change. The core insight — that the awaited connect() path already hands the reason to the caller via the rejected promise, so the error event should be reserved for the non-awaited transport onerror — is correct, and the comments documenting it (inspectorClient.ts:1024-1028, the InspectorClientEventMap.error JSDoc, the lastError JSDoc) are excellent. Tests cover capture, clear-on-connecting, persistence across the error status, and client swap/null. The App.tsx ref trick to survive the disconnect-driven activeServerId reset is a thoughtful touch and is tested both ways. Nicely done.

A few points, none blocking:

1. onerror is wired before the handshake — can a handshake failure double-toast? (worth confirming)

attachTransportListeners is called at inspectorClient.ts:678, before client.connect(this.transport) at line 694, so baseTransport.onerror (lines 438–442, which unconditionally sets status = "error" and dispatches error) is live during the handshake.

The new invariant — "handshake failures don't dispatch error" — holds only if real transports report connect-time failures exclusively by rejecting connect(), never via onerror. The integration test confirms this for a transport whose start() rejects without calling onerror, but that's one shape. If any SDK transport (SSE / streamable-http on a mid-handshake socket error) also calls onerror, you'd get both the Failed to connect to "…" toast (from the onToggleConnection catch, App.tsx:1533) and the Connection to "…" lost toast (from lastError).

Worth either confirming the SDK transports never onerror during connect, or scoping the dispatch to genuine mid-session, e.g.:

baseTransport.onerror = (error: Error) => {
  // Handshake failures reject connect(); the error event is for
  // post-connect transport death only.
  if (this.status !== "connected") return;
  this.status = "error";
  this.dispatchTypedEvent("statusChange", this.status);
  this.dispatchTypedEvent("error", error);
};

(One caveat with that guard: it would suppress reporting for a hypothetical transport that only signals connect failures through onerror and never rejects — but in that case connect() would hang anyway, which is a separate problem.) Fix this →

2. activeServerNameRef is never reset (minor)

App.tsx:1091-1094 only ever sets the ref (when activeServer is truthy); it's never cleared. After connecting to server A and disconnecting cleanly, the ref still holds "A". If a lastError were ever to surface with no genuinely-active server, the toast would name the stale "A". In practice the error event only originates from the just-connected client so this is almost always correct — and clearing the ref on disconnect would defeat the whole point (the name must survive the disconnect that precedes lastError). So the current tradeoff is reasonable; just flagging that the ref outlives its relevance. No change needed unless you want to belt-and-suspenders it.

3. Identical consecutive errors won't re-toast (informational)

The toast effect keys on [lastError], so the same message twice in a row without an intervening connecting edge won't fire a second toast (state doesn't change). Since every reconnect drives status → "connecting" (which clears lastError to undefined first), the realistic crash→reconnect→crash sequence works correctly. Noting only so it's a known property, not a surprise.

Nits

  • Consider a brief integration assertion that onerror firing during connecting doesn't surface a spurious error event — this would pin down finding Progress notifications #1 either way.

Nothing here blocks merge; finding #1 is the only one I'd want a quick confirmation on before sign-off.

Review follow-up (#1489): the transport listeners are attached before the
handshake runs, so an SDK transport that reports a connect-time error via
`onerror` — in addition to rejecting `connect()` — would flip status to
"error" and dispatch the `error` event during a handshake the awaited
`connect()` path already surfaces via its rejection, double-reporting it.

Guard `onerror` on `status === "connected"` so the `error` event stays
exclusive to post-handshake transport death. Add an integration test
covering an `onerror` that fires while status is "connecting".

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cliffhall

Copy link
Copy Markdown
Member Author

Thanks for the thorough review! Addressed in 74904df.

#1 — onerror wired before the handshake → possible double-toast (actionable, fixed). You're right that this is the one with real risk: attachTransportListeners runs at inspectorClient.ts:678, before status = "connecting" (686) and client.connect() (694), so the unconditional onerror was live during the handshake. If any SDK transport (SSE / streamable-http on a mid-handshake socket error) reported via onerror in addition to rejecting connect(), you'd get both the Failed to connect to "…" toast (handshake catch) and the Connection to "…" lost toast (lastError). I applied your suggested guard:

baseTransport.onerror = (error: Error) => {
  if (this.status !== "connected") return; // mid-session only
  this.status = "error";
  this.dispatchTypedEvent("statusChange", this.status);
  this.dispatchTypedEvent("error", error);
};

Now the error event is exclusive to post-handshake transport death (the one path with no promise to reject); a connect-time onerror is ignored and connect()'s rejection remains the sole handshake surface. The hypothetical "onerror-only, never-rejects" transport would hang in connecting regardless — a separate problem, as you noted.

Added an integration test (covering your nit too): a transport whose start() parks keeps status at connecting, and firing onerror mid-handshake dispatches no error event and does not flip to error; once the handshake rejects, status reaches error via the rejection path, still without an error event.

#2 — activeServerNameRef never reset (minor, leaving as-is). Agreed this is the right tradeoff: clearing on disconnect would defeat the purpose (the name must outlive the disconnect that precedes lastError), and the error event only ever originates from the just-connected client, so the ref is current whenever a toast actually fires. Documented intent already lives in the ref's comment.

#3 — identical consecutive errors won't re-toast (informational, no change). Correct and intended: every reconnect drives status → "connecting", which clears lastError to undefined first, so the realistic crash → reconnect → crash sequence re-toasts. Noted as a known property.

Full validate (exit 0) and the integration suite (now 129) pass.

@cliffhall

Copy link
Copy Markdown
Member Author

@claude review

@claude

claude Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @cliffhall's task in 1m 37s —— View job


Re-review: surface mid-session transport failures via lastError (#1323)

  • Read the new commit (74904dfe) addressing prior feedback
  • Review core changes (inspectorClient.ts, event target, useInspectorClient.ts)
  • Review App.tsx integration + tests
  • Post review

The follow-up commit (74904dfe) cleanly addresses the prior round. The if (this.status !== "connected") return; guard at inspectorClient.ts:447 does close the double-toast window, the comments are excellent, and the new "onerror during the handshake" integration test pins the behavior down exactly as described. Findings #2 and #3 from the last round were reasonably resolved.

One new observation surfaced by the guard itself — worth a quick think before sign-off, not a hard blocker:

onerror vs. onclose ordering on a real crash — the guard can now swallow a genuine mid-session reason

Both listeners are live post-handshake (inspectorClient.ts:431 / :438). On a real transport death, many SDK transports fire both onclose and onerror, and the order is transport-dependent. Walking the two orderings through the new guard:

  • onerror first, then onclose — onerror sees status === "connected" → flips to "error", dispatches error (reason captured ✅). Then onclose sees status === "error" (≠ "disconnected") → flips to "disconnected", dispatches disconnect. Works.
  • onclose first, then onerror — onclose flips to "disconnected", dispatches disconnect. Then onerror sees status === "disconnected" (≠ "connected") → returns early. The error event is never dispatched, lastError stays unset, no toast / no reason surfaced.

So the guard's predicate (!== "connected") conflates two distinct non-connected states: "connecting" (the handshake — correctly suppressed) and "disconnected" (a mid-session crash where onclose merely landed first — incorrectly suppressed). Note this is a slight regression vs. the pre-guard behavior: previously onclose-then-onerror still surfaced the reason.

The distinguishing characteristic of a handshake is specifically status === "connecting" (that's the only state where an awaited connect() is pending and will reject). So the semantically precise guard is:

baseTransport.onerror = (error: Error) => {
  // Suppress only the handshake case: status is "connecting" while connect()
  // is pending and will reject. Any non-connecting state (connected, or
  // disconnected because onclose landed first) is a genuine mid-session
  // failure whose reason has no other surface.
  if (this.status === "connecting") return;
  this.status = "error";
  this.dispatchTypedEvent("statusChange", this.status);
  this.dispatchTypedEvent("error", error);
};

This surfaces the reason regardless of onclose/onerror ordering while still suppressing the handshake double-report.

Tradeoff to weigh (why this is a judgment call, not an obvious fix): === "connecting" would also dispatch an error if a transport emits a stray onerror during/after a clean user-initiated disconnect (status "disconnected"), producing a spurious toast. The current !== "connected" errs toward fewer false toasts at the cost of possibly dropping a real reason. Which way to lean depends on the real ordering for stdio / SSE / streamable-http:

  • If those transports reliably fire onerror before onclose on a crash, the current guard is fine as-is — just worth a confirming integration test (fire onclose then onerror from "connected" and assert the error event still lands), so a future SDK ordering change doesn't silently regress reason-surfacing.
  • If any fire onclose first (or onclose-only with an error), switch to === "connecting" to avoid losing the reason.

Fix this →

Nits

  • useInspectorClient.test.tsx — the "keeps lastError across the error status transition" test fires setStatus("error") then error in the same act(). The real onerror order is statusChange("error") → error, which the test matches; good. Worth one more case asserting lastError survives a subsequent statusChange("disconnected") (the onclose that often trails onerror), since the toast effect depends on lastError not being cleared by that trailing transition. (It isn't — only "connecting" clears it — but a test would lock that in.)

Everything else (the lastError clear-on-connecting semantics, the activeServerNameRef survival trick, the JSDoc on the error event and lastError, and the App.test.tsx generic-vs-named toast coverage) is in good shape. The only thing I'd want confirmed before sign-off is the onclose/onerror ordering question above.

Re-review follow-up (#1489): the prior `!== "connected"` guard regressed
the onclose-before-onerror ordering. On a real mid-session crash many
transports fire both onclose and onerror in a transport-dependent order;
when onclose lands first it flips status to "disconnected", so a
"connected"-only guard swallowed the reason the trailing onerror carries
(its only surface).

Guard on `=== "connecting"` instead — precisely the handshake state with a
pending awaited connect() that will reject — so the error event fires from
any non-connecting state regardless of onclose/onerror ordering, while
still suppressing the handshake double-report.

Tests: integration case firing onclose-then-onerror from connected asserts
the error event still lands; hook test asserts lastError survives a
trailing statusChange("disconnected").

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cliffhall

Copy link
Copy Markdown
Member Author

Great catch — that's a real regression. Fixed in 5cbb1b8.

onclose/onerror ordering — guard now keys on connecting, not connected. You're right that !== "connected" conflated "connecting" (handshake, correctly suppressed) with "disconnected" (a crash where onclose merely landed first, incorrectly suppressed). I traced the clean-disconnect path to weigh your tradeoff: disconnect() calls this.client.close() (a graceful close, which standard transports don't follow with onerror) and then nulls baseTransport/transport, so the "stray onerror after a clean disconnect → spurious toast" case requires a non-standard transport emitting onerror on graceful close — unlikely. Meanwhile the onclose-first crash ordering losing the reason is a concrete regression. So I went with your semantically-precise guard:

baseTransport.onerror = (error: Error) => {
  // "connecting" is the only state with a pending awaited connect() that
  // will reject; suppress just that. connected / disconnected are genuine
  // mid-session failures whose reason has no other surface.
  if (this.status === "connecting") return;
  this.status = "error";
  this.dispatchTypedEvent("statusChange", this.status);
  this.dispatchTypedEvent("error", error);
};

Walking the orderings now: onerror-first (connected → error, then onclose: error → disconnected) and onclose-first (connected → disconnected via onclose, then onerror: disconnected → error) both end with the error event dispatched and lastError set. The comment spells out why !== "connected" was wrong so it doesn't regress back.

Tests added (both of your suggestions):

  • Integration: from a connected session, fire onclose (→ "disconnected") then onerror and assert the error event still lands with the right reason and status reaches "error". Locks the ordering against a future SDK change.
  • Hook nit: assert lastError survives a trailing statusChange("disconnected") (only the "connecting" edge clears it) — pins the property the toast effect depends on.

validate (exit 0), integration suite (now 130), hook unit (18) all pass.

@cliffhall

Copy link
Copy Markdown
Member Author

@claude review

@claude

claude Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @cliffhall's task in 1m 28s —— View job


Re-review (#1323): lastError surface — ✅ LGTM

  • Read latest commit (5cbb1b80) + full diff vs origin/v2/main
  • Review core changes (inspectorClient.ts, event target, useInspectorClient.ts)
  • Review App.tsx + tests
  • Post review

The two findings from the previous round are cleanly resolved. The guard at core/mcp/inspectorClient.ts:454 now keys on === "connecting", and walking both crash orderings confirms the reason now surfaces regardless of onclose/onerror interleaving:

  • onerror first: connected → error (dispatches error), then onclose flips error → disconnected. lastError set ✅
  • onclose first: connected → disconnected, then onerror (status "disconnected" ≠ "connecting") → disconnected → error (dispatches error). lastError set ✅

Both new integration tests (inspectorClient.test.ts:2530 mid-session crash, and the onclose-before-onerror regression lock) pin this down, and the inline comment now explains why !== "connected" was wrong so it can't silently regress. The handshake-suppression test and the hook test asserting lastError survives a trailing statusChange("disconnected") are the right belt-and-suspenders. I also confirmed the disconnect() cleanup the author cited (client.close() then null baseTransport/transport, :1079-1086), which makes the "stray onerror after a clean disconnect → spurious toast" path require a non-standard transport — an acceptable tradeoff against the concrete onclose-first regression.

One informational note (no change needed)

The guard fixes reason-surfacing, but the persistent status a real crash leaves behind is still ordering-dependent:

  • onerror-then-onclose → final status "disconnected" (the trailing onclose overwrites "error" via the !== "disconnected" guard at :432)
  • onclose-then-onerror → final status "error"

lastError (and thus the toast) fires in both, so this PR's goal is fully met — I'm only flagging that the steady-state status after an identical crash can differ between transports. The :2530 test fires onerror alone and asserts "error", but on a real stdio crash the trailing onclose would land and leave "disconnected". If the UI ever branches on status === "error" (vs. just consuming lastError), that asymmetry could matter. Reconciling it (e.g. not letting onclose downgrade an "error" status) is out of scope here — noting only so it's a known property rather than a future surprise.

Everything else — the lastError clear-on-connecting semantics, the activeServerNameRef survival trick, the JSDoc on the error event / lastError, and the App.test.tsx generic-vs-named toast coverage — is in good shape. Nothing blocks merge.

@cliffhall

Copy link
Copy Markdown
Member Author

Thanks for the thorough re-reviews — appreciate the rigor on the onclose/onerror ordering.

On the informational note: you're right that this PR fixes reason-surfacing but the persistent status a real crash lands on is still ordering-dependent (onclose-then-onerror → "error"; onerror-then-onclose → "disconnected", since the trailing onclose downgrades "error" via the !== "disconnected" guard at inspectorClient.ts:432). It's benign today because the UI consumes lastError, not status === "error" — but it's a genuine latent asymmetry. I've filed it as a tracked follow-up so it isn't a future surprise: #1490 (on the v2 board). Keeping it out of this PR, which stays scoped to #1323 (surface the reason).

Calling this one done — thanks again.

@cliffhall

cliffhall commented Jun 15, 2026 •

Copy link
Copy Markdown
Member Author

Manual smoke test — mid-session crash surfaces the reason ✅

Verified the end-to-end path in a real browser against the web dev server on this branch (not just unit/integration tests).

smoke-02-toast

Setup

  • cd clients/web && npm run dev, opened the Inspector.
  • Added a stdio server smoke-crash → command node, arg test-servers/build/test-server-stdio.js (a real MCP server, so the handshake completes — the precondition, since this PR only covers post-handshake death).
  • Connected → card showed Connected, subprocess live.

Trigger

  • kill -9 <test-server-stdio pid> to simulate a mid-session transport death (stdio subprocess crash).

Result

A red toast appeared:

Connection to "smoke-crash" lost
Transport closed - process may have exited

Both halves of the feature are exercised: the named-server title (via activeServerNameRef, which survives the disconnect-driven activeServerId reset) and the transport reason as the message.

Chain confirmed (matches the code under review)

kill subprocess
  → backend transport.onclose → session.markTransportDead("Transport closed - process may have exited")
  → queues a `transport_error` SSE event
  → browser RemoteClientTransport maps it to onerror()  (status still "connected")
  → InspectorClient.onerror dispatches the `error` event   (the guard's `status === "connecting"` is false → fires)
  → useInspectorClient sets `lastError`
  → App.tsx red "Connection to …" toast

Notes

  • The toast auto-closes (Mantine default), so a first DOM query a few seconds later found nothing — a MutationObserver recorder captured the title/message verbatim and a screenshot caught it live. Functionally correct; just flagging the auto-close so a future reader doesn't think it's flaky.
  • After the toast, the card settled on Disconnected (not "error"). That's exactly the onerror-then-onclose ordering where the trailing onclose downgrades the terminal status — the latent asymmetry tracked in the follow-up Mid-session crash leaves ordering-dependent terminal status (onclose can downgrade "error" → "disconnected") #1490. The reason still surfaced, which is this PR's whole goal.

Negative control (path separation)

A handshake failure (bad command / unreachable server) still produces the existing Failed to connect to "…" toast from the connect() catch — not the new "Connection lost" toast — confirming the awaited-rejection path and the mid-session error-event path remain distinct and don't double-report.

@cliffhall
cliffhall merged commit b4716a1 into v2/main Jun 15, 2026
1 check passed
@cliffhall
cliffhall deleted the feat/1323-error-event-surface branch June 15, 2026 12:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v2 Issues and PRs for v2

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add an error event to InspectorClientEventMap so mid-session transport failures surface

1 participant