Repository navigation
feat(mobile): live terminal screen over the relay — WebView xterm, quick keys, PTY reattach - #6342
saddlepaddle wants to merge 2 commits into
Conversation
… reconnecting socket
expo-font 56.0.7 (June 15 batch) references a Record symbol added to expo-modules-core after 56.0.15, crashing the app at launch with a DYLD missing-symbol abort. Pin to 56.0.5, the newest build predating the symbol.
📝 WalkthroughWalkthroughAdds an authenticated mobile terminal route. The implementation embeds xterm in a WebView, connects through an authenticated WebSocket flow, supports retry and resume handling, and provides terminal session controls and quick keys. ChangesMobile terminal workspace
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant TerminalScreen
participant TerminalWebView
participant TERMINAL_HTML
participant WebSocketRelay
TerminalScreen->>TerminalWebView: Render terminal identifiers
TerminalWebView->>TERMINAL_HTML: Load generated terminal HTML
TERMINAL_HTML->>TerminalWebView: Request signed dial URL
TerminalWebView->>WebSocketRelay: Provide authenticated dial URL
TERMINAL_HTML->>WebSocketRelay: Open terminal WebSocket
WebSocketRelay-->>TERMINAL_HTML: Send terminal state and output
TERMINAL_HTML-->>TerminalWebView: Send bridge messages
TerminalWebView-->>TerminalScreen: Report state and control events
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/TerminalScreen.tsx (1)
136-138: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMove
Centeredto its own file.
Centeredis a second component defined inTerminalScreen.tsx. The coding guidelines require one component per file, organized asComponentName/ComponentName.tsxwith anindex.tsbarrel export. Co-locate it undercomponents/Centered/.As per coding guidelines: "Use one component per file and organize components as
ComponentName/ComponentName.tsxwith anindex.tsbarrel export."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/mobile/screens/`(authenticated)/workspace/[id]/terminal/[terminalId]/TerminalScreen.tsx around lines 136 - 138, Move the Centered component out of TerminalScreen.tsx into components/Centered/Centered.tsx, add components/Centered/index.ts as its barrel export, and update TerminalScreen.tsx to import Centered from that barrel instead of defining it locally.Source: Coding guidelines
apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalWebView/TerminalWebView.tsx (1)
152-166: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winHandle WKWebView content-process termination.
When iOS terminates the WKWebView content process, reload the WebView with
onContentProcessDidTerminate. The pinned[email protected]supports this iOS prop, and the page reconnects during initialization.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/mobile/screens/`(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalWebView/TerminalWebView.tsx around lines 152 - 166, Add an onContentProcessDidTerminate handler to the StyledWebView in TerminalWebView that reloads the WebView through webViewRef, preserving the existing initialization and reconnection behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@apps/mobile/screens/`(authenticated)/workspace/[id]/terminal/[terminalId]/components/QuickKeysRow/QuickKeysRow.tsx:
- Around line 46-60: Update the Pressable elements rendered by QuickKeysRow to
include an accessibilityLabel derived from each key’s semantic label, such as
“Arrow up” for the up key, and explicitly set the button accessibility role.
Ensure all four arrow quick keys are distinguishable to VoiceOver while
preserving their existing onPress behavior.
In
`@apps/mobile/screens/`(authenticated)/workspace/[id]/terminal/[terminalId]/TerminalScreen.tsx:
- Around line 50-58: Update handleControl to capture error control messages in
an errorMessage state, then render the session overlay when either exitCode or
errorMessage is set and pass the captured error through it. Also gate
QuickKeysRow on both values so error-terminated sessions show the retry/error
UI.
In `@apps/mobile/scripts/generate-terminal-html.ts`:
- Around line 105-141: Update primeAffinity to bound its fetch with the existing
timing-constant pattern and an AbortController, aborting the probe when the
timeout expires. Ensure timeout or abort failures resolve to null so connect
continues to openSocket for unknown affinity status, while preserving the
existing 403 handling.
---
Nitpick comments:
In
`@apps/mobile/screens/`(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalWebView/TerminalWebView.tsx:
- Around line 152-166: Add an onContentProcessDidTerminate handler to the
StyledWebView in TerminalWebView that reloads the WebView through webViewRef,
preserving the existing initialization and reconnection behavior.
In
`@apps/mobile/screens/`(authenticated)/workspace/[id]/terminal/[terminalId]/TerminalScreen.tsx:
- Around line 136-138: Move the Centered component out of TerminalScreen.tsx
into components/Centered/Centered.tsx, add components/Centered/index.ts as its
barrel export, and update TerminalScreen.tsx to import Centered from that barrel
instead of defining it locally.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 99baa902-12fc-4bbf-9d53-487f59eb619b
⛔ Files ignored due to path filters (2)
apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalWebView/terminalHtml.generated.tsis excluded by!**/*.generated.*bun.lockis excluded by!**/*.lock
📒 Files selected for processing (11)
apps/mobile/app/(authenticated)/_layout.tsxapps/mobile/app/(authenticated)/workspace/[id]/terminal/[terminalId].tsxapps/mobile/package.jsonapps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/TerminalScreen.tsxapps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/QuickKeysRow/QuickKeysRow.tsxapps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/QuickKeysRow/index.tsapps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalWebView/TerminalWebView.tsxapps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalWebView/index.tsapps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/index.tsapps/mobile/scripts/generate-terminal-html.tsbiome.jsonc
| {QUICK_KEYS.map((key) => ( | ||
| <Pressable | ||
| key={key.id} | ||
| onPress={() => onKey(key.data)} | ||
| className="bg-secondary min-w-11 items-center justify-center rounded-md px-3 py-1.5 active:opacity-60" | ||
| > | ||
| {key.icon ? ( | ||
| <key.icon size={14} color={theme.secondaryForeground} /> | ||
| ) : ( | ||
| <Text className="text-secondary-foreground font-mono text-xs"> | ||
| {key.label} | ||
| </Text> | ||
| )} | ||
| </Pressable> | ||
| ))} |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Add accessibility labels to the quick keys.
The arrow keys render an icon only. VoiceOver announces them as an unlabeled button, so a screen-reader user cannot tell the four arrows apart. Add a label and the button role.
♿ Proposed fix
interface QuickKey {
id: string;
label?: string;
icon?: LucideIcon;
+ /** Announced by screen readers; required for icon-only keys. */
+ accessibilityLabel: string;
/** Raw bytes written into the PTY. */
data: string;
} <Pressable
key={key.id}
onPress={() => onKey(key.data)}
+ accessibilityRole="button"
+ accessibilityLabel={key.accessibilityLabel}
className="bg-secondary min-w-11 items-center justify-center rounded-md px-3 py-1.5 active:opacity-60"
>Set accessibilityLabel on each entry, for example "Arrow up" for the up key.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@apps/mobile/screens/`(authenticated)/workspace/[id]/terminal/[terminalId]/components/QuickKeysRow/QuickKeysRow.tsx
around lines 46 - 60, Update the Pressable elements rendered by QuickKeysRow to
include an accessibilityLabel derived from each key’s semantic label, such as
“Arrow up” for the up key, and explicitly set the button accessibility role.
Ensure all four arrow quick keys are distinguishable to VoiceOver while
preserving their existing onPress behavior.
| const handleControl = useCallback((message: TerminalControlMessage) => { | ||
| if (message.type === "title") { | ||
| setTitle(message.title ?? null); | ||
| } else if (message.type === "exit") { | ||
| setExitCode(message.exitCode ?? 0); | ||
| } | ||
| }, []); | ||
|
|
||
| const banner = STATE_BANNERS[connectionState]; |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Surface the error control message.
handleControl handles only title and exit. The page runtime also forwards {type:"error", message} control frames, and it sets terminated = true for them, so the connection state becomes ended. STATE_BANNERS has no ended entry and exitCode stays null, so the screen shows a frozen terminal with no banner, no overlay, and no way to retry.
Capture the error message and show it in the session overlay.
🐛 Proposed fix
const [exitCode, setExitCode] = useState<number | null>(null);
+ const [errorMessage, setErrorMessage] = useState<string | null>(null);
const handleControl = useCallback((message: TerminalControlMessage) => {
if (message.type === "title") {
setTitle(message.title ?? null);
} else if (message.type === "exit") {
setExitCode(message.exitCode ?? 0);
+ } else if (message.type === "error") {
+ setErrorMessage(message.message ?? "The terminal session failed.");
}
}, []);Then render the overlay when either exitCode or errorMessage is set, and gate QuickKeysRow on both.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@apps/mobile/screens/`(authenticated)/workspace/[id]/terminal/[terminalId]/TerminalScreen.tsx
around lines 50 - 58, Update handleControl to capture error control messages in
an errorMessage state, then render the session overlay when either exitCode or
errorMessage is set and pass the captured error through it. Also gate
QuickKeysRow on both values so error-terminated sessions show the retry/error
UI.
| function primeAffinity(wsUrl) { | ||
| try { | ||
| var url = new URL(wsUrl); | ||
| var match = url.pathname.match(/^\\/hosts\\/[^/]+/); | ||
| if (!match) return Promise.resolve(null); | ||
| url.pathname = match[0] + "/_whoowns"; | ||
| url.protocol = url.protocol === "wss:" ? "https:" : "http:"; | ||
| return fetch(url.toString(), { cache: "no-store" }) | ||
| .then(function (res) { | ||
| return res.status; | ||
| }) | ||
| .catch(function () { | ||
| return null; | ||
| }); | ||
| } catch (error) { | ||
| return Promise.resolve(null); | ||
| } | ||
| } | ||
|
|
||
| function connect() { | ||
| if (terminated) return; | ||
| setState(everAttached ? "reconnecting" : "connecting"); | ||
| requestDialUrl() | ||
| .then(function (url) { | ||
| return primeAffinity(url).then(function (status) { | ||
| if (status === 403) { | ||
| terminated = true; | ||
| setState("denied"); | ||
| return; | ||
| } | ||
| openSocket(url); | ||
| }); | ||
| }) | ||
| .catch(function () { | ||
| scheduleReconnect(); | ||
| }); | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Add a timeout to the primeAffinity fetch.
primeAffinity calls fetch with no timeout or abort signal. On a stalled mobile network, the promise can stay pending indefinitely. connect() then never calls openSocket and never calls scheduleReconnect, so the terminal stays in connecting/reconnecting with no recovery until the user backgrounds and resumes the app. requestDialUrl has DIAL_TIMEOUT_MS, but that timer does not cover this stage.
Bound the affinity probe with AbortController and treat a timeout as "unknown status", which already falls through to openSocket.
🛡️ Proposed fix to bound the affinity probe
function primeAffinity(wsUrl) {
try {
var url = new URL(wsUrl);
var match = url.pathname.match(/^\\/hosts\\/[^/]+/);
if (!match) return Promise.resolve(null);
url.pathname = match[0] + "/_whoowns";
url.protocol = url.protocol === "wss:" ? "https:" : "http:";
- return fetch(url.toString(), { cache: "no-store" })
+ var controller = new AbortController();
+ var timer = setTimeout(function () {
+ controller.abort();
+ }, AFFINITY_TIMEOUT_MS);
+ return fetch(url.toString(), {
+ cache: "no-store",
+ signal: controller.signal,
+ })
.then(function (res) {
+ clearTimeout(timer);
return res.status;
})
.catch(function () {
+ clearTimeout(timer);
return null;
});
} catch (error) {
return Promise.resolve(null);
}
}Declare the constant with the other timing constants:
var DIAL_TIMEOUT_MS = 15000;
+ var AFFINITY_TIMEOUT_MS = 8000;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| function primeAffinity(wsUrl) { | |
| try { | |
| var url = new URL(wsUrl); | |
| var match = url.pathname.match(/^\\/hosts\\/[^/]+/); | |
| if (!match) return Promise.resolve(null); | |
| url.pathname = match[0] + "/_whoowns"; | |
| url.protocol = url.protocol === "wss:" ? "https:" : "http:"; | |
| return fetch(url.toString(), { cache: "no-store" }) | |
| .then(function (res) { | |
| return res.status; | |
| }) | |
| .catch(function () { | |
| return null; | |
| }); | |
| } catch (error) { | |
| return Promise.resolve(null); | |
| } | |
| } | |
| function connect() { | |
| if (terminated) return; | |
| setState(everAttached ? "reconnecting" : "connecting"); | |
| requestDialUrl() | |
| .then(function (url) { | |
| return primeAffinity(url).then(function (status) { | |
| if (status === 403) { | |
| terminated = true; | |
| setState("denied"); | |
| return; | |
| } | |
| openSocket(url); | |
| }); | |
| }) | |
| .catch(function () { | |
| scheduleReconnect(); | |
| }); | |
| } | |
| function primeAffinity(wsUrl) { | |
| try { | |
| var url = new URL(wsUrl); | |
| var match = url.pathname.match(/^\/hosts\/[^/]+/); | |
| if (!match) return Promise.resolve(null); | |
| url.pathname = match[0] + "/_whoowns"; | |
| url.protocol = url.protocol === "wss:" ? "https:" : "http:"; | |
| var controller = new AbortController(); | |
| var timer = setTimeout(function () { | |
| controller.abort(); | |
| }, AFFINITY_TIMEOUT_MS); | |
| return fetch(url.toString(), { | |
| cache: "no-store", | |
| signal: controller.signal, | |
| }) | |
| .then(function (res) { | |
| clearTimeout(timer); | |
| return res.status; | |
| }) | |
| .catch(function () { | |
| clearTimeout(timer); | |
| return null; | |
| }); | |
| } catch (error) { | |
| return Promise.resolve(null); | |
| } | |
| } | |
| function connect() { | |
| if (terminated) return; | |
| setState(everAttached ? "reconnecting" : "connecting"); | |
| requestDialUrl() | |
| .then(function (url) { | |
| return primeAffinity(url).then(function (status) { | |
| if (status === 403) { | |
| terminated = true; | |
| setState("denied"); | |
| return; | |
| } | |
| openSocket(url); | |
| }); | |
| }) | |
| .catch(function () { | |
| scheduleReconnect(); | |
| }); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/mobile/scripts/generate-terminal-html.ts` around lines 105 - 141, Update
primeAffinity to bound its fetch with the existing timing-constant pattern and
an AbortController, aborting the probe when the timeout expires. Ensure timeout
or abort failures resolve to null so connect continues to openSocket for unknown
affinity status, while preserving the existing 403 handling.
🚀 Preview Deployment🔗 Preview Links
Preview updates automatically with new commits |
There was a problem hiding this comment.
8 issues found across 13 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="apps/mobile/package.json">
<violation number="1" location="apps/mobile/package.json:83">
P3: expo-font is added as a direct dependency but never imported or configured anywhere in apps/mobile — the only references are in bun.lock (already satisfied transitively via `expo`). If it isn't needed for this feature, drop it to keep the dependency list accurate; if it is planned for later, note that in the PR so reviewers know it's intentional.</violation>
</file>
<file name="apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/TerminalScreen.tsx">
<violation number="1" location="apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/TerminalScreen.tsx:53">
P1: A server-side terminal error leaves the screen looking usable while the socket is permanently terminated: `TerminalWebView` forwards the error, but this handler drops it and the resulting `ended` state renders no banner. Handling the error control message and displaying its message with a recovery path would prevent users from being stranded on a dead terminal.</violation>
</file>
<file name="apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalWebView/TerminalWebView.tsx">
<violation number="1" location="apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalWebView/TerminalWebView.tsx:137">
P1: Returning to the app while the initial dial/preflight is still pending can open multiple sockets for the same terminal, leaving an orphaned live attachment and causing duplicate replay/input behavior. The page-side connect lifecycle should deduplicate in-flight dials and ignore stale dial/preflight completions before opening a socket.
(Based on your team's feedback about deduplicating concurrent terminal attaches and guarding stale terminal preflights.)</violation>
</file>
<file name="apps/mobile/scripts/generate-terminal-html.ts">
<violation number="1" location="apps/mobile/scripts/generate-terminal-html.ts:112">
P2: A hung `_whoowns` request can leave the mobile terminal stuck in connecting/reconnecting forever because the preflight has no timeout. Applying an abort timeout comparable to the desktop preflight would let the existing reconnect/error handling proceed.</violation>
<violation number="2" location="apps/mobile/scripts/generate-terminal-html.ts:129">
P1: A stale affinity preflight can replace a newer terminal connection or permanently mark a successfully reconnected terminal as denied. Guard each preflight callback with a connect epoch before opening the socket or applying the 403 transition, as the desktop transport does.</violation>
<violation number="3" location="apps/mobile/scripts/generate-terminal-html.ts:177">
P3: A socket-close failure is silently swallowed, which makes termination problems invisible during WebView debugging. Logging the exception with terminal/socket context would keep this failure observable.</violation>
<violation number="4" location="apps/mobile/scripts/generate-terminal-html.ts:185">
P2: Attach errors are reported to the page as ended terminals, so the mobile screen loses its failure banner and Retry action. Preserve the error state for `error` controls and reserve `ended` for an actual PTY exit.</violation>
</file>
<file name="apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/QuickKeysRow/QuickKeysRow.tsx">
<violation number="1" location="apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/QuickKeysRow/QuickKeysRow.tsx:47">
P3: The arrow quick-keys render icon-only, with no accessibilityLabel or accessibilityRole set on the Pressable. VoiceOver users won't be able to distinguish the up/down/left/right keys since they're announced as unlabeled buttons.</violation>
</file>
Architecture diagram
sequenceDiagram
participant User
participant RN as React Native Bridge
participant WebView as WKWebView (xterm.js)
participant Relay as WebSocket Relay
participant Host as Host Service
participant Token as getHostAuthToken()
Note over User,Host: Terminal Screen Initialization
User->>RN: Deep link: /workspace/[id]/terminal/[terminalId]
RN->>RN: Load terminalHtml.generated.ts (~403 KiB)
RN->>WebView: source={{ html }} - render xterm page
WebView->>WebView: Page ready, postMessage {type:"ready"}
WebView->>WebView: Call connect()
Note over WebView,Token: Dial Flow (per connect attempt, up to 12 attempts)
WebView->>WebView: requestDialUrl() - postMessage {type:"dial", id, replay}
WebView->>RN: {type:"dial", id, replay: "1" or "0"}
Note over RN: replay="1" first time, "0" after bytes received
RN->>Token: getHostAuthToken() - fresh JWT
Token-->>RN: JWT token
RN->>RN: Build WS URL: relay/hosts/{routingKey}/terminal/{terminalId}?workspaceId=&token=&replay=&themeType=dark
RN->>WebView: postMessage {type:"dialUrl", id, url}
WebView->>WebView: primeAffinity(url) - GET /_whoowns
alt 403 Forbidden
WebView->>RN: postMessage {type:"state", state:"denied"}
WebView->>WebView: terminated = true
else OK or other
WebView->>Relay: WebSocket connect(url)
Relay->>Host: Validate token, attach to PTY
Host-->>Relay: PTY attached
Relay-->>WebView: JSON {type:"attached"}
WebView->>WebView: everAttached = true, attempts = 0
WebView->>WebView: sendResize() - {type:"resize", cols, rows}
WebView->>RN: postMessage {type:"state", state:"open"}
end
Note over WebView,Host: PTY I/O Stream
alt Binary Frame from PTY
Host->>Relay: Raw PTY bytes
Relay-->>WebView: ArrayBuffer (binary frame)
WebView->>WebView: term.write(Uint8Array)
else JSON Control Frame
Host->>Relay: {type:"title", title: "..."}
Relay-->>WebView: JSON text frame
WebView->>RN: postMessage {type:"control", message:{type:"title", title}}
RN->>RN: setTitle(title) - update native header
else Exit/Error
Host->>Relay: {type:"exit", exitCode:0}
Relay-->>WebView: JSON text frame
WebView->>WebView: terminated = true, close socket
WebView->>RN: postMessage {type:"control", message:{type:"exit", exitCode:0}}
RN->>RN: Show "Session ended" overlay
end
Note over User,WebView: Quick Keys Input Path
User->>RN: Tap quick key (e.g. ⇧tab)
RN->>WebView: postMessage {type:"input", data:"\u001b[Z"}
WebView->>WebView: sendInput(data) - JSON {type:"input", data}
WebView->>Relay: WebSocket.send(JSON)
Relay->>Host: Relay input to PTY
Host-->>Relay: PTY response bytes
Relay-->>WebView: Binary frame - updated TUI renders
Note over WebView,RN: Reconnect & Error Handling
WebView->>WebView: WebSocket closed unexpectedly
alt terminated (exit/error/denied)
WebView->>RN: postMessage {type:"state", state:"ended"}
else attempts < 12
WebView->>WebView: scheduleReconnect() - exponential backoff (500ms-10s)
WebView->>RN: postMessage {type:"state", state:"reconnecting"}
else attempts >= 12
WebView->>RN: postMessage {type:"state", state:"error"}
RN->>User: Show "Connection failed" + Retry button
alt User taps Retry
User->>RN: Press Retry
RN->>WebView: postMessage {type:"resume"}
WebView->>WebView: attempts = 0, reset, connect()
end
end
Note over RN,WebView: App Lifecycle
User->>RN: App returns to foreground
RN->>RN: AppState "active" event
RN->>WebView: postMessage {type:"resume"}
WebView->>WebView: Reset attempts, reconnect if socket closed
Note over User,Host: Session Reattach (deep link again)
User->>RN: Deep link same terminalId again
RN->>WebView: New WebView with fresh html
WebView->>WebView: requestDialUrl() - hasReceivedBytes = false, replay="1"
RN->>Token: getHostAuthToken()
RN-->>WebView: dialUrl with replay=1
WebView->>Relay: WebSocket connect with replay=1
Relay->>Host: Attach to existing PTY by terminalId
Host->>Relay: Full screen replay
Relay-->>WebView: Binary frames - replay buffer
WebView->>WebView: term.write() - renders full session history
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| const handleControl = useCallback((message: TerminalControlMessage) => { | ||
| if (message.type === "title") { | ||
| setTitle(message.title ?? null); | ||
| } else if (message.type === "exit") { |
There was a problem hiding this comment.
P1: A server-side terminal error leaves the screen looking usable while the socket is permanently terminated: TerminalWebView forwards the error, but this handler drops it and the resulting ended state renders no banner. Handling the error control message and displaying its message with a recovery path would prevent users from being stranded on a dead terminal.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/TerminalScreen.tsx, line 53:
<comment>A server-side terminal error leaves the screen looking usable while the socket is permanently terminated: `TerminalWebView` forwards the error, but this handler drops it and the resulting `ended` state renders no banner. Handling the error control message and displaying its message with a recovery path would prevent users from being stranded on a dead terminal.</comment>
<file context>
@@ -0,0 +1,138 @@
+ const handleControl = useCallback((message: TerminalControlMessage) => {
+ if (message.type === "title") {
+ setTitle(message.title ?? null);
+ } else if (message.type === "exit") {
+ setExitCode(message.exitCode ?? 0);
+ }
</file context>
|
|
||
| useEffect(() => { | ||
| const subscription = AppState.addEventListener("change", (state) => { | ||
| if (state === "active") postToPage({ type: "resume" }); |
There was a problem hiding this comment.
P1: Returning to the app while the initial dial/preflight is still pending can open multiple sockets for the same terminal, leaving an orphaned live attachment and causing duplicate replay/input behavior. The page-side connect lifecycle should deduplicate in-flight dials and ignore stale dial/preflight completions before opening a socket.
(Based on your team's feedback about deduplicating concurrent terminal attaches and guarding stale terminal preflights.)
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalWebView/TerminalWebView.tsx, line 137:
<comment>Returning to the app while the initial dial/preflight is still pending can open multiple sockets for the same terminal, leaving an orphaned live attachment and causing duplicate replay/input behavior. The page-side connect lifecycle should deduplicate in-flight dials and ignore stale dial/preflight completions before opening a socket.
(Based on your team's feedback about deduplicating concurrent terminal attaches and guarding stale terminal preflights.) </comment>
<file context>
@@ -0,0 +1,167 @@
+
+ useEffect(() => {
+ const subscription = AppState.addEventListener("change", (state) => {
+ if (state === "active") postToPage({ type: "resume" });
+ });
+ return () => subscription.remove();
</file context>
| setState(everAttached ? "reconnecting" : "connecting"); | ||
| requestDialUrl() | ||
| .then(function (url) { | ||
| return primeAffinity(url).then(function (status) { |
There was a problem hiding this comment.
P1: A stale affinity preflight can replace a newer terminal connection or permanently mark a successfully reconnected terminal as denied. Guard each preflight callback with a connect epoch before opening the socket or applying the 403 transition, as the desktop transport does.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/scripts/generate-terminal-html.ts, line 129:
<comment>A stale affinity preflight can replace a newer terminal connection or permanently mark a successfully reconnected terminal as denied. Guard each preflight callback with a connect epoch before opening the socket or applying the 403 transition, as the desktop transport does.</comment>
<file context>
@@ -0,0 +1,309 @@
+ setState(everAttached ? "reconnecting" : "connecting");
+ requestDialUrl()
+ .then(function (url) {
+ return primeAffinity(url).then(function (status) {
+ if (status === 403) {
+ terminated = true;
</file context>
| socket.onclose = function () { | ||
| if (ws === socket) ws = null; | ||
| if (terminated) { | ||
| setState("ended"); |
There was a problem hiding this comment.
P2: Attach errors are reported to the page as ended terminals, so the mobile screen loses its failure banner and Retry action. Preserve the error state for error controls and reserve ended for an actual PTY exit.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/scripts/generate-terminal-html.ts, line 185:
<comment>Attach errors are reported to the page as ended terminals, so the mobile screen loses its failure banner and Retry action. Preserve the error state for `error` controls and reserve `ended` for an actual PTY exit.</comment>
<file context>
@@ -0,0 +1,309 @@
+ socket.onclose = function () {
+ if (ws === socket) ws = null;
+ if (terminated) {
+ setState("ended");
+ return;
+ }
</file context>
| if (!match) return Promise.resolve(null); | ||
| url.pathname = match[0] + "/_whoowns"; | ||
| url.protocol = url.protocol === "wss:" ? "https:" : "http:"; | ||
| return fetch(url.toString(), { cache: "no-store" }) |
There was a problem hiding this comment.
P2: A hung _whoowns request can leave the mobile terminal stuck in connecting/reconnecting forever because the preflight has no timeout. Applying an abort timeout comparable to the desktop preflight would let the existing reconnect/error handling proceed.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/scripts/generate-terminal-html.ts, line 112:
<comment>A hung `_whoowns` request can leave the mobile terminal stuck in connecting/reconnecting forever because the preflight has no timeout. Applying an abort timeout comparable to the desktop preflight would let the existing reconnect/error handling proceed.</comment>
<file context>
@@ -0,0 +1,309 @@
+ if (!match) return Promise.resolve(null);
+ url.pathname = match[0] + "/_whoowns";
+ url.protocol = url.protocol === "wss:" ? "https:" : "http:";
+ return fetch(url.toString(), { cache: "no-store" })
+ .then(function (res) {
+ return res.status;
</file context>
| "expo-device": "56.0.4", | ||
| "expo-document-picker": "56.0.4", | ||
| "expo-file-system": "56.0.7", | ||
| "expo-font": "56.0.5", |
There was a problem hiding this comment.
P3: expo-font is added as a direct dependency but never imported or configured anywhere in apps/mobile — the only references are in bun.lock (already satisfied transitively via expo). If it isn't needed for this feature, drop it to keep the dependency list accurate; if it is planned for later, note that in the PR so reviewers know it's intentional.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/package.json, line 83:
<comment>expo-font is added as a direct dependency but never imported or configured anywhere in apps/mobile — the only references are in bun.lock (already satisfied transitively via `expo`). If it isn't needed for this feature, drop it to keep the dependency list accurate; if it is planned for later, note that in the PR so reviewers know it's intentional.</comment>
<file context>
@@ -80,6 +80,7 @@
"expo-device": "56.0.4",
"expo-document-picker": "56.0.4",
"expo-file-system": "56.0.7",
+ "expo-font": "56.0.5",
"expo-glass-effect": "56.0.4",
"expo-haptics": "~56.0.3",
</file context>
| terminated = true; | ||
| try { | ||
| socket.close(); | ||
| } catch (error) {} |
There was a problem hiding this comment.
P3: A socket-close failure is silently swallowed, which makes termination problems invisible during WebView debugging. Logging the exception with terminal/socket context would keep this failure observable.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/scripts/generate-terminal-html.ts, line 177:
<comment>A socket-close failure is silently swallowed, which makes termination problems invisible during WebView debugging. Logging the exception with terminal/socket context would keep this failure observable.</comment>
<file context>
@@ -0,0 +1,309 @@
+ terminated = true;
+ try {
+ socket.close();
+ } catch (error) {}
+ }
+ post({ type: "control", message: message });
</file context>
| contentContainerClassName="gap-2 px-3 py-2" | ||
| > | ||
| {QUICK_KEYS.map((key) => ( | ||
| <Pressable |
There was a problem hiding this comment.
P3: The arrow quick-keys render icon-only, with no accessibilityLabel or accessibilityRole set on the Pressable. VoiceOver users won't be able to distinguish the up/down/left/right keys since they're announced as unlabeled buttons.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/QuickKeysRow/QuickKeysRow.tsx, line 47:
<comment>The arrow quick-keys render icon-only, with no accessibilityLabel or accessibilityRole set on the Pressable. VoiceOver users won't be able to distinguish the up/down/left/right keys since they're announced as unlabeled buttons.</comment>
<file context>
@@ -0,0 +1,64 @@
+ contentContainerClassName="gap-2 px-3 py-2"
+ >
+ {QUICK_KEYS.map((key) => (
+ <Pressable
+ key={key.id}
+ onPress={() => onKey(key.data)}
</file context>
First surface of the terminal-first mobile direction: a live terminal attached to a host PTY over the relay, at
workspace/[id]/terminal/[terminalId](deep-link only for now — home-screen rows land with the terminals-as-sessions swap after #6328).Architecture
scripts/generate-terminal-html.tsand committed asterminalHtml.generated.ts) speaks the same wire contract as web'sTerminalConnection: binary frames = raw PTY bytes, JSON text frames = control (attached/title/exit/error), client sendsinput/resize,_whoownspreflight before each dial for fly affinity + definitive 403 detection, exponential backoff with a 12-attempt budget,replay=0once bytes have been received.getHostAuthToken, expiry-aware), sets the nav title from the PTY's OSC title, shows connection banners, relays app-resume to the page, and renders a quick-keys row (esc · tab · ⇧tab · arrows · ^C) writing raw bytes through the bridge.react-native-webview13.16.1 — dev clients need a rebuild (bunx expo run:ios).Also in this PR
fix(mobile): pinexpo-font56.0.5 — bun resolved 56.0.7 (June 15 batch), whose precompiled framework references aRecord.from(dictionary:appContext:)symbol that doesn't exist in ourexpo-modules-core56.0.15 (June 5 batch) → DYLD missing-symbol crash at launch. Anyone prebuilding from current main hits this.Verified on simulator (iPhone 16 Pro, full local stack: api + relay + desktop-spawned host-service)
End-to-end, driven via Maestro:
Known follow-ups
terminal.send/writeInput. Quick keys (the bridge path) work today.[RNScreens] sheetPresentationController is nullredbox appeared on a single deep-link entry and never reproduced; watching for it.Summary by cubic
Adds a live terminal screen on mobile at
workspace/[id]/terminal/[terminalId], powered by xterm in aWebView, with quick keys, reconnect, and session reattach. Also adds required deps and pinsexpo-fontto fix a launch crash; dev clients must rebuild.New Features
WebView; socket lives in-page so PTY bytes don’t cross the RN bridge.terminalIdwith replay; exit overlay shows code.Dependencies
[email protected](native change; rebuild dev clients, e.g.bunx expo run:ios).@xterm/xtermand@xterm/addon-fitfor the generated terminal page (scripts/generate-terminal-html.ts).[email protected]to avoid a DYLD missing-symbol crash with[email protected].Written for commit 3c71e19. Summary will update on new commits.
Summary by CodeRabbit