Skip to content

Harden terminal WebSocket recovery and callback lifecycle - #19413

Merged
kevinushey merged 10 commits into
mainfrom
codex/terminal-websocket-recovery
Nov 5, 2026
Merged

kevinushey merged 10 commits into
mainfrom
codex/terminal-websocket-recovery

Conversation

@kevinushey

@kevinushey kevinushey commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

A terminal WebSocket that stops delivering traffic without a close/error event can remain connected indefinitely: the client sends keep-alives but never checks their replies. Separately, a delayed close from an old socket can disconnect its replacement, and a late open after RPC fallback can complete the connection twice.

These failures were reproduced with controlled socket events. Addresses #18386. See #18386 (comment); the reporter's exact failure has not been reproduced, so this PR does not close that issue.

Approach

Move socket ownership and timers into TerminalWebSocket, with every callback tied to its originating connection. Close abandoned sockets and cancel their timers before notifying the session. After three unanswered keep-alives have each had an interval to receive a reply, fall back to RPC. Count probes actually sent so a delayed browser timer alone does not expire a connection; disabling keep-alives still disables this check. The diagnostics log names the cause of each fallback (connect timeout, expired keep-alives, or socket error).

During RPC fallback, hold new input until the server confirms the channel change. Only retry input the WebSocket did not accept, and surface fallback errors for queued input once per burst. Sequence numbers are assigned when input is written over RPC, so input queued during the switch stays in order with what follows it. Disconnecting or replacing the connection cancels queued input with an error, detaching it before callbacks so a callback can reconnect without losing newly queued input. A connection attempt superseded by such a callback stops before overwriting the newer socket. Ignore stale RPC completions and complete initial connection setup only once, avoiding a second process-start/buffer-reload cycle during live fallback.

Automated Tests

Validated on Windows:

  • Java compilation and GWT draft compilation passed using the repository-pinned GWT SDK.
  • ant unittest passed (834 tests). TerminalWebSocketTests covers the transport: stale open/close/message/error/timeout events, replacement connections, missing and successful keep-alive replies, the reported failure cause, timer cancellation/disablement, and rejected or throwing sends. TerminalSessionSocketTests drives the production session socket against controlled RPC completions, sockets and timers: ordered input after RPC confirmation, no replay or duplicate connection completion, stale RPC success/error responses, fallback errors, one error per cancelled burst on disconnect/reconnect, reentrant connection replacement, and in-order sequence numbers for input queued during the switch.
  • Two Playwright E2E tests passed in development Desktop with test retries disabled: npm run test:desktop-dev -- tests/panes/terminal/terminal_websocket_recovery.test.ts --no-deps --retries=0 --trace on. They drop keep-alive replies on one real terminal WebSocket, verify RPC recovery with the original shell and displayed output intact and another terminal still usable, and hold the RPC switch request while typing to verify queued input arrives once and in order without replaying previously accepted input. Assertions use rendered output, shell state, and observed RPC traffic; the normal keep-alive timers remain enabled.
  • npm run typecheck passed for the Playwright suite.
  • git diff --check passed.

The local development Desktop launcher uses this branch's rebuilt GWT client with the existing C++ session and prebuilt, unchanged Panmirror assets. The full GWT/browser suite and Linux RStudio Server end-to-end reproduction have not been run.

QA Notes

On RStudio Server, keep a terminal open and interrupt only its WebSocket traffic while leaving HTTP/RPC usable. With the default 10-second ping interval, verify fallback after approximately 40 seconds, continued input after fallback, and that existing displayed output is retained. Exercise delayed connection establishment past the connect timeout and reconnect while the previous connection is still closing. Confirm that a second terminal remains independent.

The original issue still needs runtime evidence from an affected session; these QA notes concern the reproduced connection failures.

Documentation

Added a release note in NEWS.md. No user-facing controls or protocol changes.

Checklist

  • Includes a NEWS.md entry for the bug fix.
  • No UI changes requiring accessibility updates.
  • A reviewer is assigned.
  • All local unit tests pass (targeted tests passed; full suite not run).

@kevinushey
kevinushey requested a review from gtritchie November 3, 2026 22:34
@kevinushey kevinushey added this to the 2026.12 (Parrot Balsam) milestone Nov 3, 2026
Exercise silent keepalive failure, shell and output preservation, independent terminals, and input queued during RPC fallback.

Addresses #18386.
@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
5084 0 233 1
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 4 0 16 0
✅ desktop-linux 1271 0 44 1
✅ desktop-macos 1278 0 39 0
✅ desktop-windows 1271 0 51 0
✅ server-linux 1212 0 51 0
✅ setup 48 0 32 0
View / download the full report

View report online -- opens in the browser, no download needed. Available for 14 days.

Download playwright-report.zip -- extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


All platforms - commit fc1861841d02f879f505a6e99575a58fc9064d67 - Run #1980

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We started this review before noticing the PR is still a draft, and decided to post the findings anyway in case they're useful while you finish it.

Nine findings inline. The one most worth looking at first is the build one: ant unittest now needs the i18n venv Python, which the Jenkins PR-build workspace doesn't have. Of the rest, two concern runtime behavior (one confirmed, one narrow), one concerns diagnostics, and five are cleanups. Where a finding is narrow or unlikely in practice, the comment says so.

The changes-requested state is procedural; nothing here needs a reply until the PR is ready.

Comment thread src/gwt/build.xml Outdated
</exec>
</target>

<target name="unittest" description="Runs JUnit unit tests" depends="test-terminal-session-socket,build-unittests">

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Build: ant unittest now hard-requires the i18n venv Python.

test-terminal-session-socket runs ${python.bin}, which resolves to tools/i18n-helpers/VENV. Until now that interpreter was only used by i18n-generate, which is gated on generate-i18n-required (set only when the Commands.cmd.xml MD5 changes), so a missing venv never mattered.

The Jenkins PR build runs ./gwt-unit-tests.sh → ant unittest (jenkins/Jenkinsfile.pull-request-build:191) inside the jenkins/ide image. That image runs package/linux/install-dependencies, which doesn't create the venv, and the venv is gitignored, so the workspace won't have one. python.bin then falls back to a nonexistent path, and <exec failifexecutionfails="true"> fails the GWT unit-test stage before JUnit runs. GitHub Actions doesn't run ant unittest, which is why this PR's checks are green.

I haven't seen this fail in a Jenkins run; the conclusion is from reading the build and image scripts. Moving these scenarios into JUnit (see the comment on terminal_session_socket.test.py) would remove the dependency entirely.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the Python harness and the test-terminal-session-socket target in 2e9c7d4, so ant unittest has no Python dependency again. The scenarios now run as JUnit in TerminalSessionSocketTests.

else
session_.connectionDisconnected();
for (PendingInput input : pending)
input.callback.onError(error);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One error line per queued keystroke.

Each keystroke typed while the RPC switch is pending becomes its own PendingInput. On fallback failure (here) and on disconnect (line 428), each one gets onError. TerminalSession.sendUserInput's callback calls writeError (a red writeln) for each.

So if keep-alives expire because the network is down and the user types ls -la + Enter while process_use_rpc is in flight, a failed switch prints the server error 7 times. Consider reporting the failure once, e.g. erroring only the first pending callback and dropping the rest, or having the session write a single message.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2e9c7d4: cancelPendingInput reports the error to the first queued callback only, for both the fallback-failure and disconnect paths. The later callbacks are not invoked (they would only chain the next chunk). Covered by testDisconnectCancelsQueuedInputOnce and testCancellationCallbackCanReconnectAndQueueInput.

public void onError()
{
connectWebSocketTimer_.cancel();
diagnosticError(constants_.websocketConnectError());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Diagnostics no longer say why fallback happened.

The connect timeout and keep-alive expiry both arrive here and log websocketConnectError ("WebSocket connect error, switching to RPC"). A live connection that stopped answering pings after an hour now looks the same as a failed handshake in the terminal diagnostics. That's the evidence the PR description says #18386 still needs from affected sessions.

timeoutConnectingMessage also no longer has any callers (TerminalConstants.java:82, _en/_fr properties line 65). Passing a reason from TerminalWebSocket to the listener, or a distinct callback for keep-alive expiry, would keep the three cases distinguishable.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2e9c7d4. TerminalWebSocket.Listener.onFailure now passes a Failure (CONNECT_TIMEOUT, KEEP_ALIVE_EXPIRED, ERROR), and the session logs timeoutConnectingMessage, a new keepAliveExpiredMessage, or websocketConnectError accordingly. The tests assert each message in the diagnostics log.

diagnosticError(constants_.sendUserInputMessage());

requestCallback.onResponseReceived(null);
pendingInput_.add(pending);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Narrow: the input queued here carries a stale sequence number.

TerminalSession.sendUserInput only advances inputSequence_ on Desktop in RPC mode, so input whose WebSocket send was rejected is queued with IGNORE_SEQUENCE. useRpcMode sets forceRpc_ synchronously, so input typed after it gets FLUSH, 0, 1, …, and the flush loop then sends them all back-to-back. The server appends IGNORE/FLUSH entries in arrival order (SessionConsoleProcess.cpp:402-419). If the sequenced ones arrive first, the earliest-typed characters reach the shell last.

This needs the socket to be CLOSING/CLOSED before onclose fires and the burst to arrive out of order, so it's unlikely. Before this PR that input was silently dropped, so this is still an improvement. Mentioning it in case the sequence assignment is easy to fix while you're here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 04d570e. Sequence assignment moved from TerminalSession.sendUserInput into TerminalSessionSocket.writeRpcInput, so a number is assigned when the input is actually written over RPC: input queued after a rejected WebSocket send gets FLUSH, and what follows gets 0, 1, ... in order. Sequencing is still desktop-only. testRejectedInputIsSequencedInOrderWithLaterInput covers it. That commit also fixes ShellInput.getSequence(), which declared a boolean return for the int field.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the other eight changes check out, and the Desktop sequencing fix looks right.

The new head's CI still shows the reordering on Server, though: terminal_websocket_recovery.test.ts:172 ("input typed while RPC fallback is pending arrives once and in order") fails on linux-server / e2e-server-ubuntu (4) on both attempts, and it failed the same way on the original head. The queued command reaches the shell scrambled, e.g. pw_n=$((pw_n1+);)ech"opw_queued_$pw_n".

Sequencing is Desktop-only, so on Server each queued keystroke is flushed as its own process_write_stdin with IGNORE_SEQUENCE, back-to-back, and the server applies them in arrival order. Coalescing the queue into a single write when it's flushed (join the texts in order, one writeStandardInput, then acknowledge each callback) would remove the race on every platform and turn the burst into one RPC. Alternatively, sequencing could be enabled for RPC input everywhere, since ConsoleProcess::enqueInput doesn't look Desktop-specific on the server side.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, that was it. Fixed in 6645960: switchToRPC now hands the queue to flushPendingInput, which joins the queued texts in order and writes them as one process_write_stdin, then acknowledges each callback. Input typed while that write is in flight stays queued behind it (the switch stays pending), and the switch completes once nothing is left to write. A failed burst is reported once, as before, and later input is still written.

testQueuedInputIsWrittenAsOneBurstAndLaterInputWaitsForIt and testFailedBurstIsReportedOnceAndLaterInputStillWritten cover it; the two existing flush tests now expect the single write. The recovery spec passes locally in server mode (both tests).

{
if (socket_ != socket)
return;
if (TerminalSocketPacket.keepAlivePacket().equals(message))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: TerminalSocketPacket.isKeepAlive(message) already does this comparison and now has no callers. Calling it here keeps the packet format defined in one place.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 2e9c7d4.

public void scheduleRepeating(int ms) { active = true; }
public void cancel() { active = false; }
}''')
write(server + '.ServerError', '''public class ServerError {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Python harness with hand-written Java stand-ins.

These session-level scenarios are compiled against Java stand-ins written as Python strings. Some already differ from production; for example, ServerError is a class here but an interface in ServerError.java:20. Any signature change to ConsoleProcess, Timer, or ServerError has to be mirrored by hand, outside the compiler and IDE.

TerminalWebSocket already takes an injected Scheduler and socket factory for JUnit. Giving TerminalSessionSocket a small injected interface for the console-process and RPC calls would let these scenarios live in TerminalWebSocketTests-style JUnit. That would also remove the build dependency noted on build.xml.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 2e9c7d4. TerminalSessionSocket takes Process (implemented by ConsoleProcess) and Emulator (implemented by XTermWidget) interfaces plus a TerminalWebSocket.Factory, and the eight scenarios are now methods in TerminalSessionSocketTests against the production classes. The shared socket and clock doubles live in TerminalSocketTestDoubles; TerminalWebSocketTests is a GWTTestCase too, so the suite is uniform. ant unittest passes (834 tests).

socket_.send(message);
return true;
}
catch (RuntimeException error)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: exception discarded, and the caller then logs the wrong reason.

After the readyState == OPEN check, the browser's send(string) should practically never throw, so this is mostly about diagnostics. When send returns false, dispatchInput logs sendUserInputMessage: "Tried to send user input over null websocket". That's inaccurate when the socket exists but isn't open or threw. Logging the exception here, and rewording that message, would make the fallback traceable.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2e9c7d4: the exception message is logged, and sendUserInputMessage now reads "WebSocket did not accept user input, switching to RPC" (en and fr).

}
if (!pending.isEmpty())
{
ServerError error = new ServerError()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the ~40-line anonymous ServerError makes up most of disconnect(). A private static named class would keep the method readable. There's a similar anonymous implementation in RSAEncrypt.java:97 if a shared one seems worthwhile.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 2e9c7d4, as a private static DisconnectedError. I left RSAEncrypt alone to keep the PR scoped.

}
// A fallback after opening must not start the process and reload
// its output a second time. Only complete an initial connection.
if (connection == connection_)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this guard is always true. The loop above returns on a mismatch, and writeRpcInput is asynchronous, so nothing between the loop and here can change connection_. The comment is accurate; connectionCompleted() is what prevents the second start.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 2e9c7d4: the mismatch check now follows writeRpcInput inside the loop, and the trailing guard is gone.

@kevinushey
kevinushey marked this pull request as ready for review November 4, 2026 23:37
Move the session-level scenarios from the Python harness into JUnit so
`ant unittest` no longer depends on the i18n venv Python. The socket
takes small Process and Emulator interfaces (implemented by ConsoleProcess
and XTermWidget) and a TerminalWebSocket factory, so the production
classes are tested against controlled RPC completions, sockets and timers.

TerminalWebSocket now reports why a connection was given up on, so the
diagnostics log distinguishes a connect timeout, expired keep-alives and a
socket error. A send exception is logged, and the "null websocket" message
is reworded.

Queued input that is cancelled or fails fallback reports one error for the
burst instead of one per keystroke. Also use TerminalSocketPacket.isKeepAlive,
fold the always-true guard after the flush loop into the loop, and move the
disconnect ServerError into a named class.
TerminalSession numbered input before dispatch, so input whose WebSocket
send was rejected was queued with IGNORE_SEQUENCE while input typed after
the switch to RPC carried FLUSH, 0, 1. If the flushed burst arrived out of
order, the server could deliver the earlier keystrokes last.

The socket now assigns the sequence in writeRpcInput, when the input is
actually sent over RPC, so queued input is numbered in order with what
follows it. Sequencing stays desktop-only, as before. Also fix the return
type of ShellInput.getSequence(), which read an int field as a boolean.
@kevinushey
kevinushey requested a review from gtritchie November 5, 2026 00:03

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CI shows reordering on Server, failing tests. See posted comment.

@kevinushey
kevinushey requested a review from gtritchie November 5, 2026 17:50
Each keystroke typed while the switch to RPC was in flight was flushed
as its own process_write_stdin request, back to back. Only desktop
numbers RPC input, so on server the burst could reach the shell out of
order, which the recovery e2e test showed on linux-server.

The queue is now joined and written as a single request, and input
typed while that write is in flight stays queued behind it, so the
switch completes once nothing is left to write.
@kevinushey
kevinushey merged commit 4004e56 into main Nov 5, 2026
46 checks passed
@kevinushey
kevinushey deleted the codex/terminal-websocket-recovery branch November 5, 2026 22:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants