Stage remote terminal launches and replay hydrated buffers

- Carry pending launch context into terminal open
- Delay buffer replay until surface hydration is stable
- Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marminge committed 2026-04-17 19:48:19 -07:00
1 parent 97263c5db4
commit 034a8bcab3
15 files changed
+697 -171

No files matched your search

@@ -47,10 +47,11 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
}
}
var fontSize: Float = 12f
var fontSize: Float = 10f
set(value) {
field = value
textView.textSize = value
inputView.textSize = max(value, 13f)
emitResize()
}
@@ -100,23 +100,26 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
}
}
var fontSize: CGFloat = 12 {
var fontSize: CGFloat = 10 {
didSet {
guard oldValue != fontSize else { return }
inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular)
resetSurface()
refreshSurface()
}
}
var appearanceScheme: String = TerminalAppearanceScheme.dark.rawValue {
didSet {
guard oldValue != appearanceScheme else { return }
appearance = TerminalAppearanceScheme(value: appearanceScheme)
updateGhosttyTheme()
refreshSurface()
}
}
var themeConfig: String = "" {
didSet {
updateGhosttyTheme()
guard oldValue != themeConfig else { return }
refreshSurface()
}
}
@@ -353,6 +356,11 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
setNeedsLayout()
}
private func refreshSurface() {
resetSurface()
createSurfaceIfPossible()
}
private func destroySurface() {
if let surface {
ghostty_surface_set_write_callback(surface, nil, nil)
@@ -525,19 +533,6 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
terminalViewport.backgroundColor = backgroundColorValue
}
private func updateGhosttyTheme() {
guard let app, let surface else { return }
guard let config = ghostty_config_new() else { return }
loadThemeConfig(into: config)
ghostty_config_finalize(config)
ghostty_app_update_config(app, config)
ghostty_surface_update_config(surface, config)
ghostty_app_set_color_scheme(app, appearance.ghosttyColorScheme)
ghostty_surface_set_color_scheme(surface, appearance.ghosttyColorScheme)
ghostty_config_free(config)
redrawSurface()
}
private func loadThemeConfig(into config: ghostty_config_t) {
guard let path = writeThemeConfigFile() else { return }
path.withCString { cString in
@@ -18,11 +18,10 @@ import { connectionTone } from "../connection/connectionTone";
import { useRemoteCatalog } from "../../state/use-remote-catalog";
import {
getEnvironmentClient,
useRemoteConnectionStatus,
useRemoteEnvironmentState,
} from "../../state/use-remote-environment-registry";
import { terminalSessionManager, useKnownTerminalSessions } from "../../state/use-terminal-session";
import { useKnownTerminalSessions } from "../../state/use-terminal-session";
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
import { useThreadSelection } from "../../state/use-thread-selection";
import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
@@ -31,7 +30,10 @@ import {
nextTerminalId,
resolveProjectScriptTerminalId,
} from "./terminalMenu";
import { resolvePreferredThreadWorktreePath } from "./terminalLaunchContext";
import {
resolvePreferredThreadWorktreePath,
stagePendingTerminalLaunch,
} from "./terminalLaunchContext";
import { ThreadDetailScreen } from "./ThreadDetailScreen";
import { ThreadGitControls } from "./ThreadGitControls";
import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
@@ -166,11 +168,6 @@ export function ThreadRouteScreen() {
return;
}
const client = getEnvironmentClient(selectedThread.environmentId);
if (!client) {
return;
}
const targetTerminalId = resolveProjectScriptTerminalId({
existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
hasRunningTerminal: terminalMenuSessions.some(
@@ -189,23 +186,20 @@ export function ThreadRouteScreen() {
project: { cwd: selectedThreadProject.workspaceRoot },
worktreePath: preferredWorktreePath,
});
const snapshot = await client.terminal.open({
threadId: selectedThread.id,
terminalId: targetTerminalId,
cwd,
worktreePath: preferredWorktreePath,
env,
stagePendingTerminalLaunch({
target: {
environmentId: selectedThread.environmentId,
threadId: selectedThread.id,
terminalId: targetTerminalId,
},
launch: {
cwd,
worktreePath: preferredWorktreePath,
env,
initialInput: `${script.command}\r`,
},
});
terminalSessionManager.syncSnapshot(
{ environmentId: selectedThread.environmentId },
snapshot,
);
await client.terminal.write({
threadId: selectedThread.id,
terminalId: targetTerminalId,
data: `${script.command}\r`,
});
void router.push(buildThreadTerminalRoutePath(selectedThread, targetTerminalId));
},
[
@@ -12,6 +12,8 @@ describe("resolveTerminalRouteBootstrap", () => {
requestedTerminalId: null,
currentTerminalId: "default",
runningTerminalId: "term-2",
currentTerminalStatus: "closed",
hasCurrentTerminalHydration: false,
}),
).toEqual({
kind: "redirect",
@@ -19,7 +21,7 @@ describe("resolveTerminalRouteBootstrap", () => {
});
});
it("hydrates the current running terminal instead of skipping open", () => {
it("hydrates the current running terminal when client state is not hydrated yet", () => {
expect(
resolveTerminalRouteBootstrap({
hasThread: true,
@@ -28,13 +30,15 @@ describe("resolveTerminalRouteBootstrap", () => {
requestedTerminalId: null,
currentTerminalId: "default",
runningTerminalId: "default",
currentTerminalStatus: "running",
hasCurrentTerminalHydration: false,
}),
).toEqual({
kind: "open",
});
});
it("opens explicit terminal routes once so they replay existing history", () => {
it("opens explicit terminal routes when the session still needs hydration", () => {
expect(
resolveTerminalRouteBootstrap({
hasThread: true,
@@ -43,6 +47,8 @@ describe("resolveTerminalRouteBootstrap", () => {
requestedTerminalId: "term-2",
currentTerminalId: "term-2",
runningTerminalId: "term-2",
currentTerminalStatus: "running",
hasCurrentTerminalHydration: false,
}),
).toEqual({
kind: "open",
@@ -58,6 +64,42 @@ describe("resolveTerminalRouteBootstrap", () => {
requestedTerminalId: null,
currentTerminalId: "default",
runningTerminalId: "default",
currentTerminalStatus: "running",
hasCurrentTerminalHydration: true,
}),
).toEqual({
kind: "idle",
});
});
it("stays idle when the current running terminal is already hydrated in client state", () => {
expect(
resolveTerminalRouteBootstrap({
hasThread: true,
hasWorkspaceRoot: true,
hasOpened: false,
requestedTerminalId: null,
currentTerminalId: "default",
runningTerminalId: "default",
currentTerminalStatus: "running",
hasCurrentTerminalHydration: true,
}),
).toEqual({
kind: "idle",
});
});
it("stays idle for explicit running terminal routes that already have hydrated output", () => {
expect(
resolveTerminalRouteBootstrap({
hasThread: true,
hasWorkspaceRoot: true,
hasOpened: false,
requestedTerminalId: "term-2",
currentTerminalId: "term-2",
runningTerminalId: "term-2",
currentTerminalStatus: "running",
hasCurrentTerminalHydration: true,
}),
).toEqual({
kind: "idle",
@@ -1,7 +1,7 @@
import { DEFAULT_TERMINAL_ID } from "@t3tools/contracts";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Pressable, ScrollView, Text as RNText, View } from "react-native";
import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
import { KeyboardStickyView } from "react-native-keyboard-controller";
import Animated, { useAnimatedKeyboard, useAnimatedStyle } from "react-native-reanimated";
@@ -21,9 +21,19 @@ import {
import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
import { TerminalSurface } from "../../native/terminal/NativeTerminalSurface";
import { getPierreTerminalTheme } from "../../native/terminal/terminalTheme";
import { loadPreferences, savePreferencesPatch } from "../../lib/storage";
import {
getTerminalBufferReplayKey,
getTerminalSurfaceReplayBuffer,
TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
} from "./terminalBufferReplay";
import { resolveTerminalRouteBootstrap } from "./terminalRouteBootstrap";
import { resolveTerminalOpenLocation } from "./terminalLaunchContext";
import {
resolveTerminalOpenLocation,
stagePendingTerminalLaunch,
takePendingTerminalLaunch,
} from "./terminalLaunchContext";
import {
basename,
buildTerminalMenuSessions,
@@ -38,6 +48,12 @@ import {
TERMINAL_FONT_SIZE_STEP,
normalizeTerminalFontSize,
} from "./terminalPreferences";
import {
cacheTerminalFontSize,
cacheTerminalGridSize,
getCachedTerminalFontSize,
getCachedTerminalGridSize,
} from "./terminalUiState";
const DEFAULT_TERMINAL_COLS = 80;
const DEFAULT_TERMINAL_ROWS = 24;
@@ -154,9 +170,14 @@ function applyCtrlModifier(input: string): string {
return input;
}
function withAlpha(hexColor: string, alpha: string): string {
return /^#[0-9a-f]{6}$/i.test(hexColor) ? `${hexColor}${alpha}` : hexColor;
}
export function ThreadTerminalRouteScreen() {
const router = useRouter();
const keyboard = useAnimatedKeyboard();
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
const { isLoadingSavedConnection } = useRemoteEnvironmentState();
const params = useLocalSearchParams<{
environmentId?: string | string[];
@@ -166,21 +187,45 @@ export function ThreadTerminalRouteScreen() {
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
useThreadSelection();
const selectedThreadDetail = useSelectedThreadDetail();
const routeEnvironmentId = firstRouteParam(params.environmentId);
const routeThreadId = firstRouteParam(params.threadId);
const requestedTerminalId = firstRouteParam(params.terminalId);
const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID;
const cachedFontSize = getCachedTerminalFontSize();
const cachedRouteGridSize =
routeEnvironmentId && routeThreadId
? getCachedTerminalGridSize({
environmentId: routeEnvironmentId,
threadId: routeThreadId,
terminalId,
})
: null;
const knownSessions = useKnownTerminalSessions({
environmentId: selectedThread?.environmentId ?? null,
threadId: selectedThread?.id ?? null,
});
const [lastGridSize, setLastGridSize] = useState({
cols: DEFAULT_TERMINAL_COLS,
rows: DEFAULT_TERMINAL_ROWS,
});
const [pendingModifier, setPendingModifier] = useState<PendingModifier | null>(null);
const [fontSize, setFontSize] = useState(DEFAULT_TERMINAL_FONT_SIZE);
const [lastGridSize, setLastGridSize] = useState(
cachedRouteGridSize ?? {
cols: DEFAULT_TERMINAL_COLS,
rows: DEFAULT_TERMINAL_ROWS,
},
);
const [fontSize, setFontSize] = useState(cachedFontSize ?? DEFAULT_TERMINAL_FONT_SIZE);
const hasOpenedRef = useRef(false);
const hasLoadedFontPreferenceRef = useRef(false);
const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID;
const bufferReplayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const lastBufferReplayKeyRef = useRef<string | null>(null);
const [readyBufferReplayKey, setReadyBufferReplayKey] = useState<string | null>(null);
const [hasResolvedFontPreference, setHasResolvedFontPreference] = useState(
cachedFontSize !== null,
);
const [hasMeasuredSurface, setHasMeasuredSurface] = useState(cachedRouteGridSize !== null);
const [pendingModifierState, setPendingModifierState] = useState<{
readonly terminalId: string;
readonly value: PendingModifier | null;
}>({
terminalId,
value: null,
});
const target = useTerminalSessionTarget({
environmentId: selectedThread?.environmentId ?? null,
threadId: selectedThread?.id ?? null,
@@ -194,6 +239,18 @@ export function ThreadTerminalRouteScreen() {
: terminalId,
[selectedThread, terminalId],
);
const bufferReplayKey = useMemo(
() => getTerminalBufferReplayKey({ terminalKey, fontSize }),
[fontSize, terminalKey],
);
if (lastBufferReplayKeyRef.current === null) {
lastBufferReplayKeyRef.current = bufferReplayKey;
}
const terminalSurfaceBuffer = getTerminalSurfaceReplayBuffer({
buffer: terminal.buffer,
replayKey: bufferReplayKey,
readyReplayKey: readyBufferReplayKey,
});
const isRunning = terminal.status === "running" || terminal.status === "starting";
const cwd = terminal.snapshot?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;
const hostPlatform = useMemo(
@@ -219,6 +276,9 @@ export function ThreadTerminalRouteScreen() {
}),
[terminal.hasRunningSubprocess, terminal.status],
);
const terminalTheme = getPierreTerminalTheme(appearanceScheme);
const pendingModifier =
pendingModifierState.terminalId === terminalId ? pendingModifierState.value : null;
const headerTitle = useMemo(() => {
const topLineParts = [
selectedEnvironmentConnection?.environmentLabel ?? null,
@@ -301,24 +361,59 @@ export function ThreadTerminalRouteScreen() {
return;
}
const launchLocation = resolveTerminalOpenLocation({
terminalSnapshot: terminal.snapshot,
activeSessionSnapshot: activeKnownSession?.state.snapshot ?? null,
workspaceRoot: selectedThreadProject.workspaceRoot,
threadShellWorktreePath: selectedThread.worktreePath ?? null,
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
});
const snapshot = await client.terminal.open({
const pendingLaunchTarget = {
environmentId: selectedThread.environmentId,
threadId: selectedThread.id,
terminalId,
cwd: launchLocation.cwd,
worktreePath: launchLocation.worktreePath,
cols: lastGridSize.cols,
rows: lastGridSize.rows,
});
};
const pendingLaunch = takePendingTerminalLaunch(pendingLaunchTarget);
terminalSessionManager.syncSnapshot({ environmentId: selectedThread.environmentId }, snapshot);
try {
const launchLocation = pendingLaunch
? {
cwd: pendingLaunch.cwd,
worktreePath: pendingLaunch.worktreePath,
}
: resolveTerminalOpenLocation({
terminalSnapshot: terminal.snapshot,
activeSessionSnapshot: activeKnownSession?.state.snapshot ?? null,
workspaceRoot: selectedThreadProject.workspaceRoot,
threadShellWorktreePath: selectedThread.worktreePath ?? null,
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
});
const snapshot = await client.terminal.open({
threadId: selectedThread.id,
terminalId,
cwd: launchLocation.cwd,
worktreePath: launchLocation.worktreePath,
cols: lastGridSize.cols,
rows: lastGridSize.rows,
env: pendingLaunch?.env,
});
terminalSessionManager.syncSnapshot(
{ environmentId: selectedThread.environmentId },
snapshot,
);
if (pendingLaunch?.initialInput) {
await client.terminal.write({
threadId: selectedThread.id,
terminalId,
data: pendingLaunch.initialInput,
});
}
} catch (error) {
if (pendingLaunch) {
stagePendingTerminalLaunch({
target: pendingLaunchTarget,
launch: pendingLaunch,
});
}
throw error;
}
}, [
lastGridSize.cols,
lastGridSize.rows,
@@ -334,6 +429,74 @@ export function ThreadTerminalRouteScreen() {
hasOpenedRef.current = false;
}, [terminalKey]);
const clearBufferReplayTimer = useCallback(() => {
if (bufferReplayTimerRef.current !== null) {
clearTimeout(bufferReplayTimerRef.current);
bufferReplayTimerRef.current = null;
}
}, []);
const scheduleBufferReplayReady = useCallback(() => {
clearBufferReplayTimer();
const replayKey = bufferReplayKey;
bufferReplayTimerRef.current = setTimeout(() => {
bufferReplayTimerRef.current = null;
setReadyBufferReplayKey(replayKey);
}, TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS);
}, [bufferReplayKey, clearBufferReplayTimer]);
useEffect(() => {
if (lastBufferReplayKeyRef.current === bufferReplayKey) {
return;
}
lastBufferReplayKeyRef.current = bufferReplayKey;
clearBufferReplayTimer();
setReadyBufferReplayKey(null);
}, [bufferReplayKey, clearBufferReplayTimer]);
useEffect(() => clearBufferReplayTimer, [clearBufferReplayTimer]);
useEffect(() => {
if (!routeEnvironmentId || !routeThreadId) {
setLastGridSize({
cols: DEFAULT_TERMINAL_COLS,
rows: DEFAULT_TERMINAL_ROWS,
});
return;
}
setLastGridSize(
getCachedTerminalGridSize({
environmentId: routeEnvironmentId,
threadId: routeThreadId,
terminalId,
}) ?? {
cols: DEFAULT_TERMINAL_COLS,
rows: DEFAULT_TERMINAL_ROWS,
},
);
setHasMeasuredSurface(
getCachedTerminalGridSize({
environmentId: routeEnvironmentId,
threadId: routeThreadId,
terminalId,
}) !== null,
);
}, [routeEnvironmentId, routeThreadId, terminalId]);
useEffect(() => {
setHasMeasuredSurface(
routeEnvironmentId !== null &&
routeThreadId !== null &&
getCachedTerminalGridSize({
environmentId: routeEnvironmentId,
threadId: routeThreadId,
terminalId,
}) !== null,
);
}, [fontSize, routeEnvironmentId, routeThreadId, terminalId]);
useEffect(() => {
let cancelled = false;
@@ -343,15 +506,15 @@ export function ThreadTerminalRouteScreen() {
return;
}
setFontSize(normalizeTerminalFontSize(preferences.terminalFontSize));
hasLoadedFontPreferenceRef.current = true;
setFontSize(cacheTerminalFontSize(preferences.terminalFontSize));
setHasResolvedFontPreference(true);
})
.catch(() => {
if (cancelled) {
return;
}
hasLoadedFontPreferenceRef.current = true;
setHasResolvedFontPreference(true);
});
return () => {
@@ -360,16 +523,21 @@ export function ThreadTerminalRouteScreen() {
}, []);
useEffect(() => {
if (!hasLoadedFontPreferenceRef.current) {
if (!hasResolvedFontPreference) {
return;
}
cacheTerminalFontSize(fontSize);
void savePreferencesPatch({
terminalFontSize: normalizeTerminalFontSize(fontSize),
});
}, [fontSize]);
}, [fontSize, hasResolvedFontPreference]);
useEffect(() => {
if (!hasResolvedFontPreference || !hasMeasuredSurface) {
return;
}
const bootstrapAction = resolveTerminalRouteBootstrap({
hasThread: selectedThread !== null,
hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
@@ -377,6 +545,8 @@ export function ThreadTerminalRouteScreen() {
requestedTerminalId,
currentTerminalId: terminalId,
runningTerminalId: runningSession?.target.terminalId ?? null,
currentTerminalStatus: terminal.status,
hasCurrentTerminalHydration: terminal.snapshot !== null || terminal.buffer.length > 0,
});
if (bootstrapAction.kind === "idle" || !selectedThread) {
return;
@@ -398,13 +568,14 @@ export function ThreadTerminalRouteScreen() {
runningSession,
selectedThread,
selectedThreadProject?.workspaceRoot,
terminal.buffer.length,
terminal.snapshot,
terminal.status,
terminalId,
hasMeasuredSurface,
hasResolvedFontPreference,
]);
useEffect(() => {
setPendingModifier(null);
}, [terminalId]);
const writeInput = useCallback(
(data: string) => {
if (!selectedThread || !isRunning) {
@@ -432,20 +603,34 @@ export function ThreadTerminalRouteScreen() {
}
if (pendingModifier === "ctrl") {
setPendingModifier(null);
setPendingModifierState({ terminalId, value: null });
writeInput(applyCtrlModifier(data));
} else if (pendingModifier === "meta") {
setPendingModifier(null);
setPendingModifierState({ terminalId, value: null });
writeInput(`\u001b${data}`);
} else {
writeInput(data);
}
},
[pendingModifier, writeInput],
[pendingModifier, terminalId, writeInput],
);
const handleResize = useCallback(
(size: { readonly cols: number; readonly rows: number }) => {
setHasMeasuredSurface(true);
if (readyBufferReplayKey !== bufferReplayKey) {
scheduleBufferReplayReady();
}
if (routeEnvironmentId && routeThreadId) {
cacheTerminalGridSize(
{
environmentId: routeEnvironmentId,
threadId: routeThreadId,
terminalId,
},
size,
);
}
if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) {
return;
}
@@ -467,7 +652,18 @@ export function ThreadTerminalRouteScreen() {
rows: size.rows,
});
},
[isRunning, lastGridSize.cols, lastGridSize.rows, selectedThread, terminalId],
[
isRunning,
lastGridSize.cols,
lastGridSize.rows,
bufferReplayKey,
readyBufferReplayKey,
routeEnvironmentId,
routeThreadId,
scheduleBufferReplayReady,
selectedThread,
terminalId,
],
);
const handleSelectTerminal = useCallback(
@@ -496,7 +692,7 @@ export function ThreadTerminalRouteScreen() {
const adjustFontSize = useCallback((delta: number) => {
setTimeout(() => {
setFontSize((current) => normalizeTerminalFontSize(current + delta));
setFontSize((current) => cacheTerminalFontSize(current + delta));
}, 0);
}, []);
@@ -511,11 +707,17 @@ export function ThreadTerminalRouteScreen() {
const handleToolbarActionPress = useCallback(
(action: TerminalToolbarAction) => {
if (action.kind === "modifier") {
setPendingModifier((current) => (current === action.modifier ? null : action.modifier));
setPendingModifierState((current) => ({
terminalId,
value:
(current.terminalId === terminalId ? current.value : null) === action.modifier
? null
: action.modifier,
}));
return;
}
setPendingModifier(null);
setPendingModifierState({ terminalId, value: null });
if (pendingModifier === "ctrl") {
writeInput(applyCtrlModifier(action.data));
} else if (pendingModifier === "meta") {
@@ -524,7 +726,7 @@ export function ThreadTerminalRouteScreen() {
writeInput(action.data);
}
},
[pendingModifier, writeInput],
[pendingModifier, terminalId, writeInput],
);
if (!selectedThread) {
@@ -561,8 +763,8 @@ export function ThreadTerminalRouteScreen() {
headerBackButtonDisplayMode: "minimal",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: { backgroundColor: "#0a0a0a" },
headerTintColor: "#f5f5f5",
headerStyle: { backgroundColor: terminalTheme.background },
headerTintColor: terminalTheme.foreground,
headerTitleAlign: "center",
title: "",
headerTitle: () => (
@@ -576,7 +778,7 @@ export function ThreadTerminalRouteScreen() {
<RNText
numberOfLines={1}
style={{
color: "#f5f5f5",
color: terminalTheme.foreground,
fontFamily: "DMSans_700Bold",
fontSize: 13,
lineHeight: 16,
@@ -588,7 +790,7 @@ export function ThreadTerminalRouteScreen() {
ellipsizeMode="middle"
numberOfLines={1}
style={{
color: "#8f8f94",
color: terminalTheme.mutedForeground,
fontFamily: "Menlo",
fontSize: 11,
lineHeight: 14,
@@ -658,10 +860,10 @@ export function ThreadTerminalRouteScreen() {
</Stack.Toolbar.Menu>
</Stack.Toolbar>
<View style={{ flex: 1, backgroundColor: "#050505" }}>
<View style={{ flex: 1, backgroundColor: terminalTheme.background }}>
<Animated.View style={[{ flex: 1 }, terminalContainerAnimatedStyle]}>
<TerminalSurface
buffer={terminal.buffer}
buffer={terminalSurfaceBuffer}
fontSize={fontSize}
isRunning={isRunning}
onInput={handleInput}
@@ -674,8 +876,8 @@ export function ThreadTerminalRouteScreen() {
<KeyboardStickyView style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}>
<View
style={{
backgroundColor: "#0a0a0a",
borderTopColor: "rgba(255,255,255,0.08)",
backgroundColor: terminalTheme.background,
borderTopColor: terminalTheme.border,
borderTopWidth: 1,
minHeight: TERMINAL_ACCESSORY_HEIGHT,
paddingBottom: 4,
@@ -698,11 +900,13 @@ export function ThreadTerminalRouteScreen() {
style={({ pressed }) => ({
alignItems: "center",
backgroundColor: active
? "rgba(74, 222, 128, 0.18)"
? withAlpha(terminalTheme.palette[10] ?? terminalTheme.foreground, "2e")
: pressed
? "rgba(255,255,255,0.12)"
: "rgba(255,255,255,0.06)",
borderColor: active ? "rgba(74, 222, 128, 0.36)" : "rgba(255,255,255,0.08)",
? withAlpha(terminalTheme.foreground, "1f")
: withAlpha(terminalTheme.foreground, "12"),
borderColor: active
? withAlpha(terminalTheme.palette[10] ?? terminalTheme.foreground, "52")
: terminalTheme.border,
borderRadius: 12,
borderWidth: 1,
justifyContent: "center",
@@ -713,7 +917,9 @@ export function ThreadTerminalRouteScreen() {
>
<RNText
style={{
color: active ? "#bbf7d0" : "#f5f5f5",
color: active
? (terminalTheme.palette[10] ?? terminalTheme.foreground)
: terminalTheme.foreground,
fontFamily: "DMSans_700Bold",
fontSize: 12,
fontWeight: "700",
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import { getTerminalBufferReplayKey, getTerminalSurfaceReplayBuffer } from "./terminalBufferReplay";
describe("terminalBufferReplay", () => {
it("keys replay readiness by terminal identity and font metrics", () => {
expect(
getTerminalBufferReplayKey({
terminalKey: "env-1:thread-1:default",
fontSize: 10,
}),
).toBe("env-1:thread-1:default:10");
});
it("holds back terminal history until the measured surface is ready", () => {
const replayKey = getTerminalBufferReplayKey({
terminalKey: "env-1:thread-1:default",
fontSize: 10,
});
expect(
getTerminalSurfaceReplayBuffer({
buffer: "fastfetch output",
replayKey,
readyReplayKey: null,
}),
).toBe("");
expect(
getTerminalSurfaceReplayBuffer({
buffer: "fastfetch output",
replayKey,
readyReplayKey: "env-1:thread-1:default:11",
}),
).toBe("");
expect(
getTerminalSurfaceReplayBuffer({
buffer: "fastfetch output",
replayKey,
readyReplayKey: replayKey,
}),
).toBe("fastfetch output");
});
});
@@ -0,0 +1,16 @@
export const TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS = 180;
export function getTerminalBufferReplayKey(input: {
readonly terminalKey: string;
readonly fontSize: number;
}): string {
return `${input.terminalKey}:${input.fontSize}`;
}
export function getTerminalSurfaceReplayBuffer(input: {
readonly buffer: string;
readonly replayKey: string;
readonly readyReplayKey: string | null;
}): string {
return input.readyReplayKey === input.replayKey ? input.buffer : "";
}
@@ -1,8 +1,11 @@
import { describe, expect, it } from "vitest";
import {
peekPendingTerminalLaunch,
resolvePreferredThreadWorktreePath,
resolveTerminalOpenLocation,
stagePendingTerminalLaunch,
takePendingTerminalLaunch,
} from "./terminalLaunchContext";
describe("resolvePreferredThreadWorktreePath", () => {
@@ -59,3 +62,68 @@ describe("resolveTerminalOpenLocation", () => {
});
});
});
describe("pending terminal launches", () => {
it("stages and consumes launch details for a specific terminal target", () => {
const target = {
environmentId: "env-1",
threadId: "thread-1",
terminalId: "term-2",
};
stagePendingTerminalLaunch({
target,
launch: {
cwd: "/repo/worktrees/feature",
worktreePath: "/repo/worktrees/feature",
env: { FOO: "bar" },
initialInput: "pnpm dev\r",
},
});
expect(peekPendingTerminalLaunch(target)).toEqual({
cwd: "/repo/worktrees/feature",
worktreePath: "/repo/worktrees/feature",
env: { FOO: "bar" },
initialInput: "pnpm dev\r",
});
expect(takePendingTerminalLaunch(target)).toEqual({
cwd: "/repo/worktrees/feature",
worktreePath: "/repo/worktrees/feature",
env: { FOO: "bar" },
initialInput: "pnpm dev\r",
});
expect(peekPendingTerminalLaunch(target)).toBeNull();
});
it("keeps pending launches isolated per terminal target", () => {
const primaryTarget = {
environmentId: "env-1",
threadId: "thread-1",
terminalId: "term-2",
};
const otherTarget = {
environmentId: "env-1",
threadId: "thread-1",
terminalId: "term-3",
};
stagePendingTerminalLaunch({
target: primaryTarget,
launch: {
cwd: "/repo/root",
worktreePath: null,
initialInput: "pnpm i\r",
},
});
expect(peekPendingTerminalLaunch(otherTarget)).toBeNull();
expect(takePendingTerminalLaunch(otherTarget)).toBeNull();
expect(takePendingTerminalLaunch(primaryTarget)).toEqual({
cwd: "/repo/root",
worktreePath: null,
env: undefined,
initialInput: "pnpm i\r",
});
});
});
@@ -3,6 +3,55 @@ interface TerminalSnapshotLike {
readonly worktreePath: string | null;
}
interface PendingTerminalLaunchTarget {
readonly environmentId: string;
readonly threadId: string;
readonly terminalId: string;
}
export interface PendingTerminalLaunch {
readonly cwd: string;
readonly worktreePath: string | null;
readonly env?: Record<string, string>;
readonly initialInput?: string;
}
const pendingTerminalLaunches = new Map<string, PendingTerminalLaunch>();
function pendingTerminalLaunchKey(input: PendingTerminalLaunchTarget): string {
return `${input.environmentId}:${input.threadId}:${input.terminalId}`;
}
export function stagePendingTerminalLaunch(input: {
readonly target: PendingTerminalLaunchTarget;
readonly launch: PendingTerminalLaunch;
}) {
pendingTerminalLaunches.set(pendingTerminalLaunchKey(input.target), {
cwd: input.launch.cwd,
worktreePath: input.launch.worktreePath,
env: input.launch.env ? { ...input.launch.env } : undefined,
initialInput: input.launch.initialInput,
});
}
export function peekPendingTerminalLaunch(
target: PendingTerminalLaunchTarget,
): PendingTerminalLaunch | null {
return pendingTerminalLaunches.get(pendingTerminalLaunchKey(target)) ?? null;
}
export function takePendingTerminalLaunch(
target: PendingTerminalLaunchTarget,
): PendingTerminalLaunch | null {
const key = pendingTerminalLaunchKey(target);
const launch = pendingTerminalLaunches.get(key) ?? null;
if (launch) {
pendingTerminalLaunches.delete(key);
}
return launch;
}
export function resolvePreferredThreadWorktreePath(input: {
readonly threadShellWorktreePath: string | null;
readonly threadDetailWorktreePath: string | null;
@@ -5,6 +5,8 @@ export function resolveTerminalRouteBootstrap(input: {
readonly requestedTerminalId: string | null;
readonly currentTerminalId: string;
readonly runningTerminalId: string | null;
readonly currentTerminalStatus: "starting" | "running" | "exited" | "error" | "closed";
readonly hasCurrentTerminalHydration: boolean;
}):
| { readonly kind: "idle" }
| { readonly kind: "redirect"; readonly terminalId: string }
@@ -21,5 +23,12 @@ export function resolveTerminalRouteBootstrap(input: {
return { kind: "redirect", terminalId: input.runningTerminalId };
}
if (
(input.currentTerminalStatus === "running" || input.currentTerminalStatus === "starting") &&
input.hasCurrentTerminalHydration
) {
return { kind: "idle" };
}
return { kind: "open" };
}
@@ -0,0 +1,52 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
cacheTerminalFontSize,
cacheTerminalGridSize,
getCachedTerminalFontSize,
getCachedTerminalGridSize,
resetTerminalUiStateCaches,
} from "./terminalUiState";
describe("terminalUiState", () => {
beforeEach(() => {
resetTerminalUiStateCaches();
});
it("caches terminal font size using the shared normalization rules", () => {
expect(getCachedTerminalFontSize()).toBeNull();
expect(cacheTerminalFontSize(8.5)).toBe(8.5);
expect(getCachedTerminalFontSize()).toBe(8.5);
expect(cacheTerminalFontSize(100)).toBe(14);
expect(getCachedTerminalFontSize()).toBe(14);
});
it("stores terminal grid sizes per terminal target", () => {
const primaryTarget = {
environmentId: "env-1",
threadId: "thread-1",
terminalId: "default",
};
const otherTarget = {
environmentId: "env-1",
threadId: "thread-1",
terminalId: "term-2",
};
expect(getCachedTerminalGridSize(primaryTarget)).toBeNull();
expect(
cacheTerminalGridSize(primaryTarget, {
cols: 107.9,
rows: 33.2,
}),
).toEqual({
cols: 107,
rows: 33,
});
expect(getCachedTerminalGridSize(primaryTarget)).toEqual({
cols: 107,
rows: 33,
});
expect(getCachedTerminalGridSize(otherTarget)).toBeNull();
});
});
@@ -0,0 +1,50 @@
import { DEFAULT_TERMINAL_FONT_SIZE, normalizeTerminalFontSize } from "./terminalPreferences";
export interface TerminalGridSize {
readonly cols: number;
readonly rows: number;
}
export interface TerminalUiStateTarget {
readonly environmentId: string;
readonly threadId: string;
readonly terminalId: string;
}
const terminalGridSizeCache = new Map<string, TerminalGridSize>();
let cachedTerminalFontSize: number | null = null;
function terminalUiStateKey(target: TerminalUiStateTarget): string {
return `${target.environmentId}:${target.threadId}:${target.terminalId}`;
}
export function getCachedTerminalFontSize(): number | null {
return cachedTerminalFontSize;
}
export function cacheTerminalFontSize(value: number | null | undefined): number {
const normalized = normalizeTerminalFontSize(value ?? DEFAULT_TERMINAL_FONT_SIZE);
cachedTerminalFontSize = normalized;
return normalized;
}
export function getCachedTerminalGridSize(target: TerminalUiStateTarget): TerminalGridSize | null {
return terminalGridSizeCache.get(terminalUiStateKey(target)) ?? null;
}
export function cacheTerminalGridSize(
target: TerminalUiStateTarget,
size: TerminalGridSize,
): TerminalGridSize {
const normalized = {
cols: Math.max(1, Math.floor(size.cols)),
rows: Math.max(1, Math.floor(size.rows)),
};
terminalGridSizeCache.set(terminalUiStateKey(target), normalized);
return normalized;
}
export function resetTerminalUiStateCaches() {
cachedTerminalFontSize = null;
terminalGridSizeCache.clear();
}
@@ -14,7 +14,7 @@ import { AppText as Text } from "../../components/AppText";
import { resolveNativeTerminalSurfaceView } from "./nativeTerminalModule";
import {
buildGhosttyThemeConfig,
getGitHubTerminalTheme,
getPierreTerminalTheme,
type TerminalTheme,
} from "./terminalTheme";
@@ -53,7 +53,7 @@ function estimateGridSize(input: {
const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: TerminalSurfaceProps) {
const fontSize = props.fontSize ?? 12;
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
const theme = props.theme ?? getGitHubTerminalTheme(appearanceScheme);
const theme = props.theme ?? getPierreTerminalTheme(appearanceScheme);
const statusLabel = props.isRunning
? "Native terminal unavailable. Using text fallback."
: "Open terminal to start a shell.";
@@ -165,7 +165,7 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) {
const fontSize = props.fontSize ?? 12;
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
const theme = props.theme ?? getGitHubTerminalTheme(appearanceScheme);
const theme = props.theme ?? getPierreTerminalTheme(appearanceScheme);
const { onInput, onResize } = props;
const NativeTerminalSurfaceView = resolveNativeTerminalSurfaceView();
const handleNativeInput = useCallback(
@@ -1,36 +1,36 @@
import { describe, expect, it } from "vitest";
import { buildGhosttyThemeConfig, getGitHubTerminalTheme } from "./terminalTheme";
import { buildGhosttyThemeConfig, getPierreTerminalTheme } from "./terminalTheme";
describe("getGitHubTerminalTheme", () => {
it("returns the GitHub light terminal palette", () => {
expect(getGitHubTerminalTheme("light")).toMatchObject({
background: "#ffffff",
foreground: "#586069",
cursorForeground: "#005cc5",
cursorBackground: "#d1d5da",
describe("getPierreTerminalTheme", () => {
it("returns the Pierre light terminal palette", () => {
expect(getPierreTerminalTheme("light")).toMatchObject({
background: "#f2f2f7",
foreground: "#6C6C71",
cursorForeground: "#009fff",
cursorBackground: "#f2f2f7",
});
});
it("returns the GitHub dark terminal palette", () => {
expect(getGitHubTerminalTheme("dark")).toMatchObject({
background: "#24292e",
foreground: "#d1d5da",
cursorForeground: "#79b8ff",
cursorBackground: "#586069",
it("returns the Pierre dark terminal palette", () => {
expect(getPierreTerminalTheme("dark")).toMatchObject({
background: "#0a0a0a",
foreground: "#adadb1",
cursorForeground: "#009fff",
cursorBackground: "#0a0a0a",
});
});
});
describe("buildGhosttyThemeConfig", () => {
it("serializes theme colors into a ghostty config file", () => {
const config = buildGhosttyThemeConfig(getGitHubTerminalTheme("dark"));
const config = buildGhosttyThemeConfig(getPierreTerminalTheme("dark"));
expect(config).toContain("background = #24292e");
expect(config).toContain("foreground = #d1d5da");
expect(config).toContain("cursor-color = #79b8ff");
expect(config).toContain("palette = 0=#586069");
expect(config).toContain("palette = 15=#fafbfc");
expect(config).toContain("background = #0a0a0a");
expect(config).toContain("foreground = #adadb1");
expect(config).toContain("cursor-color = #009fff");
expect(config).toContain("palette = 0=#141415");
expect(config).toContain("palette = 15=#c6c6c8");
expect(config.endsWith("\n")).toBe(true);
});
});
@@ -10,63 +10,64 @@ export interface TerminalTheme {
readonly palette: readonly string[];
}
const GITHUB_LIGHT_THEME: TerminalTheme = {
// Sourced from GitHub's official VS Code theme terminal palette.
background: "#ffffff",
foreground: "#586069",
mutedForeground: "#6a737d",
border: "rgba(27,31,35,0.12)",
cursorForeground: "#005cc5",
cursorBackground: "#d1d5da",
const PIERRE_LIGHT_THEME: TerminalTheme = {
// Pierre terminal palette with the app's shared screen background.
background: "#f2f2f7",
foreground: "#6C6C71",
mutedForeground: "#8E8E95",
border: "#eeeeef",
cursorForeground: "#009fff",
cursorBackground: "#f2f2f7",
palette: [
"#24292e",
"#d73a49",
"#28a745",
"#dbab09",
"#0366d6",
"#5a32a3",
"#1b7c83",
"#6a737d",
"#959da5",
"#cb2431",
"#22863a",
"#b08800",
"#005cc5",
"#5a32a3",
"#3192aa",
"#d1d5da",
"#1F1F21",
"#ff2e3f",
"#0dbe4e",
"#ffca00",
"#009fff",
"#c635e4",
"#08c0ef",
"#c6c6c8",
"#1F1F21",
"#ff2e3f",
"#0dbe4e",
"#ffca00",
"#009fff",
"#c635e4",
"#08c0ef",
"#c6c6c8",
],
};
const GITHUB_DARK_THEME: TerminalTheme = {
background: "#24292e",
foreground: "#d1d5da",
mutedForeground: "#959da5",
border: "rgba(240,246,252,0.12)",
cursorForeground: "#79b8ff",
cursorBackground: "#586069",
const PIERRE_DARK_THEME: TerminalTheme = {
// Pierre terminal palette with the app's shared screen background.
background: "#0a0a0a",
foreground: "#adadb1",
mutedForeground: "#8E8E95",
border: "#2e2e30",
cursorForeground: "#009fff",
cursorBackground: "#0a0a0a",
palette: [
"#586069",
"#ea4a5a",
"#34d058",
"#ffea7f",
"#2188ff",
"#b392f0",
"#39c5cf",
"#d1d5da",
"#959da5",
"#f97583",
"#85e89d",
"#ffea7f",
"#79b8ff",
"#b392f0",
"#56d4dd",
"#fafbfc",
"#141415",
"#ff2e3f",
"#0dbe4e",
"#ffca00",
"#009fff",
"#c635e4",
"#08c0ef",
"#c6c6c8",
"#141415",
"#ff2e3f",
"#0dbe4e",
"#ffca00",
"#009fff",
"#c635e4",
"#08c0ef",
"#c6c6c8",
],
};
export function getGitHubTerminalTheme(scheme: TerminalAppearanceScheme): TerminalTheme {
return scheme === "light" ? GITHUB_LIGHT_THEME : GITHUB_DARK_THEME;
export function getPierreTerminalTheme(scheme: TerminalAppearanceScheme): TerminalTheme {
return scheme === "light" ? PIERRE_LIGHT_THEME : PIERRE_DARK_THEME;
}
export function buildGhosttyThemeConfig(theme: TerminalTheme): string {