Skip to content

feat(mobile): live terminal screen over the relay — WebView xterm, quick keys, PTY reattach - #6342

Closed
saddlepaddle wants to merge 2 commits into
mainfrom
mobile-terminal-screen
Closed

saddlepaddle wants to merge 2 commits into
mainfrom
mobile-terminal-screen

Conversation

@saddlepaddle

@saddlepaddle saddlepaddle commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

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

  • The WebSocket lives inside the WebView, next to xterm — PTY bytes never cross the RN bridge. The page (xterm.js + fit addon + a small reconnect runtime, ~403 KiB self-contained HTML generated by scripts/generate-terminal-html.ts and committed as terminalHtml.generated.ts) speaks the same wire contract as web's TerminalConnection: binary frames = raw PTY bytes, JSON text frames = control (attached/title/exit/error), client sends input/resize, _whoowns preflight before each dial for fly affinity + definitive 403 detection, exponential backoff with a 12-attempt budget, replay=0 once bytes have been received.
  • React Native owns auth and chrome: signs each dial URL with a fresh JWT (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.
  • New native dep: react-native-webview 13.16.1 — dev clients need a rebuild (bunx expo run:ios).

Also in this PR

  • fix(mobile): pin expo-font 56.0.5 — bun resolved 56.0.7 (June 15 batch), whose precompiled framework references a Record.from(dictionary:appContext:) symbol that doesn't exist in our expo-modules-core 56.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:

  • Deep link opens the screen; xterm renders a live Claude Code TUI streaming over the relay; the PTY's title lands in the native header.
  • Input path: tapping the ⇧tab quick key cycled Claude Code's permission mode on the host (auto → manual) and the TUI update streamed back.
  • Reattach: leaving and re-opening the deep link resumed the same PTY with a full screen replay (server adopts by terminalId).
  • Typecheck (repo-wide) and lint clean.

Known follow-ups

  • Soft-keyboard input: tapping the terminal doesn't reliably focus xterm's hidden textarea in WKWebView, so freeform typing needs the planned native input bar writing via terminal.send/writeInput. Quick keys (the bridge path) work today.
  • One [RNScreens] sheetPresentationController is null redbox 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 a WebView, with quick keys, reconnect, and session reattach. Also adds required deps and pins expo-font to fix a launch crash; dev clients must rebuild.

  • New Features

    • xterm runs inside WebView; socket lives in-page so PTY bytes don’t cross the RN bridge.
    • Quick keys row (esc, tab, ⇧tab, arrows, ^C) sends raw bytes to the PTY.
    • Reconnect with backoff and reattach by terminalId with replay; exit overlay shows code.
    • Native chrome: sets title from PTY OSC, shows connection banners; deep-link only for now.
  • Dependencies

    • Add [email protected] (native change; rebuild dev clients, e.g. bunx expo run:ios).
    • Add @xterm/xterm and @xterm/addon-fit for the generated terminal page (scripts/generate-terminal-html.ts).
    • Pin [email protected] to avoid a DYLD missing-symbol crash with [email protected].

Written for commit 3c71e19. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • New Features
    • Added mobile terminal access within workspace sessions.
    • Added live terminal interaction with connection, loading, offline, error, and ended-session states.
    • Added retry and reconnect support for interrupted sessions.
    • Added quick-access controls for Escape, Tab, Shift-Tab, arrow keys, and Ctrl-C.
    • Added mobile-friendly keyboard handling, terminal resizing, and session close actions.
    • Added a dedicated Terminal screen with streamlined navigation and presentation.

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.
@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds 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.

Changes

Mobile terminal workspace

Layer / File(s) Summary
Embedded terminal runtime
apps/mobile/scripts/generate-terminal-html.ts, apps/mobile/package.json, biome.jsonc
Adds xterm assets and generates the embedded HTML runtime. The runtime handles WebSocket connections, reconnection, terminal input, resizing, and bridge messages.
Terminal WebView bridge
apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalWebView/*
Adds WebView contracts and implementation for authenticated dial requests, state and control messages, app resume, retry, focus, and input forwarding.
Terminal screen and input controls
apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/TerminalScreen.tsx, apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/QuickKeysRow/*
Adds terminal state handling, connection banners, loading and error states, session-ended navigation, keyboard avoidance, and quick-key PTY input.
Workspace terminal route
apps/mobile/app/(authenticated)/_layout.tsx, apps/mobile/app/(authenticated)/workspace/[id]/terminal/[terminalId].tsx, apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/index.ts
Registers the terminal route with its header and back-navigation settings, then exposes TerminalScreen as the route component.

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
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the mobile terminal feature, its WebView implementation, quick keys, and PTY reattachment.
Description check ✅ Passed The description explains the changes, architecture, testing results, dependencies, known limitations, and required dev-client rebuild.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch mobile-terminal-screen

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 value

Move Centered to its own file.

Centered is a second component defined in TerminalScreen.tsx. The coding guidelines require one component per file, organized as ComponentName/ComponentName.tsx with an index.ts barrel export. Co-locate it under components/Centered/.

As per coding guidelines: "Use one component per file and organize components as ComponentName/ComponentName.tsx with an index.ts barrel 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 win

Handle 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9b12164 and 3c71e19.

⛔ Files ignored due to path filters (2)
  • apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalWebView/terminalHtml.generated.ts is excluded by !**/*.generated.*
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (11)
  • apps/mobile/app/(authenticated)/_layout.tsx
  • apps/mobile/app/(authenticated)/workspace/[id]/terminal/[terminalId].tsx
  • apps/mobile/package.json
  • apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/TerminalScreen.tsx
  • apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/QuickKeysRow/QuickKeysRow.tsx
  • apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/QuickKeysRow/index.ts
  • apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalWebView/TerminalWebView.tsx
  • apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/components/TerminalWebView/index.ts
  • apps/mobile/screens/(authenticated)/workspace/[id]/terminal/[terminalId]/index.ts
  • apps/mobile/scripts/generate-terminal-html.ts
  • biome.jsonc

Comment on lines +46 to +60
{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>
))}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 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.

Comment on lines +50 to +58
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];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

Comment on lines +105 to +141
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();
});
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 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.

Suggested change
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.

@github-actions

Copy link
Copy Markdown
Contributor

🚀 Preview Deployment

🔗 Preview Links

Service Status Link
Neon Database (Neon) ✅ View Branch
Vercel API (Vercel) ✅ Open Preview
Vercel Web (Vercel) ✅ Open Preview
Vercel Marketing (Vercel) ✅ Open Preview
Vercel Admin (Vercel) ✅ Open Preview
Vercel Docs (Vercel) ✅ Open Preview

Preview updates automatically with new commits

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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
Loading

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") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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" });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.)

View Feedback: 1 2

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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" })

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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>

Comment thread apps/mobile/package.json
"expo-device": "56.0.4",
"expo-document-picker": "56.0.4",
"expo-file-system": "56.0.7",
"expo-font": "56.0.5",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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) {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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>

@saddlepaddle

Copy link
Copy Markdown
Member Author

Folded into #6366 — the terminal screen ships there (its commits are in #6366's history), landing as one squash per review preference.

This branch was previously deployed

1 inactive deployment
preview — 3c71e19d Deployed Aug 11, 2026 by saddlepaddle via Deploy Web #7445
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.

1 participant