feat(mobile): Add terminal powered by libghostty (#2056)
Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
1 parent
d686613e34
commit
da6ea88331
84 files changed
+10510
-66
No files matched your search
@@ -65,6 +65,16 @@ export default function ThreadLayout() {
|
||||
sheetGrabberVisible: true,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="terminal"
|
||||
options={{
|
||||
animation: "slide_from_right",
|
||||
contentStyle: { backgroundColor: "#050505" },
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerShown: true,
|
||||
headerShadowVisible: false,
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { ThreadTerminalRouteScreen } from "../../../../features/threads/ThreadTerminalRouteScreen";
|
||||
|
||||
export default function ThreadTerminalRoute() {
|
||||
return <ThreadTerminalRouteScreen />;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { GitRunStackedActionResult, GitStatusResult } from "@t3tools/contracts";
|
||||
import type { GitRunStackedActionResult, GitStatusResult, ProjectScript } from "@t3tools/contracts";
|
||||
import {
|
||||
type GitActionRequestInput,
|
||||
requiresDefaultBranchConfirmation,
|
||||
@@ -9,6 +9,14 @@ import Stack from "expo-router/stack";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { Alert, Linking } from "react-native";
|
||||
import { buildThreadReviewRoutePath } from "../../lib/routes";
|
||||
import {
|
||||
basename,
|
||||
getTerminalLabel,
|
||||
getTerminalStatusLabel,
|
||||
projectScriptMenuIcon,
|
||||
projectScriptMenuLabel,
|
||||
type TerminalMenuSession,
|
||||
} from "./terminalMenu";
|
||||
|
||||
function truncateMiddle(value: string, maxLength: number): string {
|
||||
if (value.length <= maxLength) {
|
||||
@@ -55,6 +63,12 @@ export function ThreadGitControls(props: {
|
||||
readonly currentBranch: string | null;
|
||||
readonly gitStatus: GitStatusResult | null;
|
||||
readonly gitOperationLabel: string | null;
|
||||
readonly canOpenTerminal: boolean;
|
||||
readonly projectScripts: ReadonlyArray<ProjectScript>;
|
||||
readonly terminalSessions: ReadonlyArray<TerminalMenuSession>;
|
||||
readonly onOpenTerminal: (terminalId?: string | null) => void;
|
||||
readonly onOpenNewTerminal: () => void;
|
||||
readonly onRunProjectScript: (script: ProjectScript) => Promise<void>;
|
||||
readonly onPull: () => Promise<void>;
|
||||
readonly onRunAction: (input: GitActionRequestInput) => Promise<GitRunStackedActionResult | null>;
|
||||
}) {
|
||||
@@ -167,6 +181,54 @@ export function ThreadGitControls(props: {
|
||||
|
||||
return (
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu icon="terminal" disabled={!props.canOpenTerminal} separateBackground>
|
||||
{props.projectScripts.length > 0 ? (
|
||||
<Stack.Toolbar.Menu icon="play" inline title="Project scripts">
|
||||
<Stack.Toolbar.Label>Project scripts</Stack.Toolbar.Label>
|
||||
{props.projectScripts.map((script) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={script.id}
|
||||
icon={projectScriptMenuIcon(script.icon)}
|
||||
onPress={() => void props.onRunProjectScript(script)}
|
||||
subtitle={script.command}
|
||||
>
|
||||
<Stack.Toolbar.Label>{projectScriptMenuLabel(script)}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
</Stack.Toolbar.Menu>
|
||||
) : (
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="play"
|
||||
disabled
|
||||
onPress={() => {}}
|
||||
subtitle="This project has no saved scripts yet"
|
||||
>
|
||||
<Stack.Toolbar.Label>No project scripts</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
)}
|
||||
<Stack.Toolbar.Menu icon="terminal" inline title="Terminals">
|
||||
<Stack.Toolbar.Label>Terminals</Stack.Toolbar.Label>
|
||||
{props.terminalSessions.map((session) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={session.terminalId}
|
||||
icon="terminal"
|
||||
onPress={() => props.onOpenTerminal(session.terminalId)}
|
||||
subtitle={[getTerminalStatusLabel({ status: session.status }), basename(session.cwd)]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
<Stack.Toolbar.Label>{getTerminalLabel(session.terminalId)}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="plus"
|
||||
onPress={props.onOpenNewTerminal}
|
||||
subtitle="Start another shell for this thread"
|
||||
>
|
||||
<Stack.Toolbar.Label>Open new terminal</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar.Menu>
|
||||
<Stack.Toolbar.Menu icon="point.topleft.down.curvedto.point.bottomright.up">
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="point.topleft.down.curvedto.point.bottomright.up"
|
||||
|
||||
@@ -3,6 +3,8 @@ import { useCallback, useMemo, useState } from "react";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Option from "effect/Option";
|
||||
import { pipe } from "effect/Function";
|
||||
import type { ProjectScript } from "@t3tools/contracts";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useGitStatus, gitStatusManager } from "../../state/use-git-status";
|
||||
@@ -10,24 +12,33 @@ import { dismissGitActionResult, useGitActionProgress } from "../../state/use-gi
|
||||
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { LoadingScreen } from "../../components/LoadingScreen";
|
||||
import { buildThreadRoutePath } from "../../lib/routes";
|
||||
import { buildThreadRoutePath, buildThreadTerminalRoutePath } from "../../lib/routes";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
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 { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
|
||||
import {
|
||||
buildTerminalMenuSessions,
|
||||
nextTerminalId,
|
||||
resolveProjectScriptTerminalId,
|
||||
} from "./terminalMenu";
|
||||
import { resolvePreferredThreadWorktreePath } from "./terminalLaunchContext";
|
||||
import { ThreadDetailScreen } from "./ThreadDetailScreen";
|
||||
import { ThreadGitControls } from "./ThreadGitControls";
|
||||
import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
|
||||
import { useSelectedThreadCommands } from "./use-selected-thread-commands";
|
||||
import { useSelectedThreadGitActions } from "./use-selected-thread-git-actions";
|
||||
import { useSelectedThreadGitState } from "./use-selected-thread-git-state";
|
||||
import { useSelectedThreadWorktree } from "./use-selected-thread-worktree";
|
||||
import { useThreadComposerState } from "./use-thread-composer-state";
|
||||
|
||||
function firstRouteParam(value: string | string[] | undefined): string | null {
|
||||
@@ -47,6 +58,7 @@ export function ThreadRouteScreen() {
|
||||
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
|
||||
useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
const composer = useThreadComposerState();
|
||||
const gitState = useSelectedThreadGitState();
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
@@ -80,20 +92,29 @@ export function ThreadRouteScreen() {
|
||||
/* ─── Git status for native header trigger ───────────────────────── */
|
||||
const gitStatus = useGitStatus({
|
||||
environmentId: selectedThread?.environmentId ?? "",
|
||||
cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
|
||||
cwd: selectedThreadCwd,
|
||||
});
|
||||
const knownTerminalSessions = useKnownTerminalSessions({
|
||||
environmentId: selectedThread?.environmentId ?? null,
|
||||
threadId: selectedThread?.id ?? null,
|
||||
});
|
||||
const terminalMenuSessions = useMemo(
|
||||
() =>
|
||||
buildTerminalMenuSessions({
|
||||
knownSessions: knownTerminalSessions,
|
||||
workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
|
||||
}),
|
||||
[knownTerminalSessions, selectedThreadProject?.workspaceRoot],
|
||||
);
|
||||
const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
|
||||
|
||||
/* ─── Git action progress (for overlay banner) ──────────────────── */
|
||||
const gitActionProgressTarget = useMemo(
|
||||
() => ({
|
||||
environmentId: selectedThread?.environmentId ?? null,
|
||||
cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
|
||||
cwd: selectedThreadCwd,
|
||||
}),
|
||||
[
|
||||
selectedThread?.environmentId,
|
||||
selectedThread?.worktreePath,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
],
|
||||
[selectedThread?.environmentId, selectedThreadCwd],
|
||||
);
|
||||
const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
|
||||
|
||||
@@ -101,9 +122,9 @@ export function ThreadRouteScreen() {
|
||||
if (!selectedThread) return;
|
||||
await gitStatusManager.refresh({
|
||||
environmentId: selectedThread.environmentId,
|
||||
cwd: selectedThread.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
|
||||
cwd: selectedThreadCwd,
|
||||
});
|
||||
}, [selectedThread, selectedThreadProject?.workspaceRoot]);
|
||||
}, [selectedThread, selectedThreadCwd]);
|
||||
|
||||
/** Wraps thread refresh + git status refresh for pull-to-refresh */
|
||||
const handleRefreshAll = useCallback(async () => {
|
||||
@@ -119,6 +140,83 @@ export function ThreadRouteScreen() {
|
||||
void router.push("/connections");
|
||||
}, [router]);
|
||||
|
||||
const handleOpenTerminal = useCallback(
|
||||
(nextTerminalId?: string | null) => {
|
||||
if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
|
||||
return;
|
||||
}
|
||||
|
||||
void router.push(buildThreadTerminalRoutePath(selectedThread, nextTerminalId));
|
||||
},
|
||||
[router, selectedThread, selectedThreadProject?.workspaceRoot],
|
||||
);
|
||||
|
||||
const handleOpenNewTerminal = useCallback(() => {
|
||||
if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextId = nextTerminalId(terminalMenuSessions.map((session) => session.terminalId));
|
||||
void router.push(buildThreadTerminalRoutePath(selectedThread, nextId));
|
||||
}, [router, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]);
|
||||
|
||||
const handleRunProjectScript = useCallback(
|
||||
async (script: ProjectScript) => {
|
||||
if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = getEnvironmentClient(selectedThread.environmentId);
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetTerminalId = resolveProjectScriptTerminalId({
|
||||
existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
|
||||
hasRunningTerminal: terminalMenuSessions.some(
|
||||
(session) => session.status === "running" || session.status === "starting",
|
||||
),
|
||||
});
|
||||
const preferredWorktreePath = resolvePreferredThreadWorktreePath({
|
||||
threadShellWorktreePath: selectedThread.worktreePath ?? null,
|
||||
threadDetailWorktreePath: selectedThreadDetailWorktreePath,
|
||||
});
|
||||
const cwd = projectScriptCwd({
|
||||
project: { cwd: selectedThreadProject.workspaceRoot },
|
||||
worktreePath: preferredWorktreePath,
|
||||
});
|
||||
const env = projectScriptRuntimeEnv({
|
||||
project: { cwd: selectedThreadProject.workspaceRoot },
|
||||
worktreePath: preferredWorktreePath,
|
||||
});
|
||||
const snapshot = await client.terminal.open({
|
||||
threadId: selectedThread.id,
|
||||
terminalId: targetTerminalId,
|
||||
cwd,
|
||||
worktreePath: preferredWorktreePath,
|
||||
env,
|
||||
});
|
||||
|
||||
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));
|
||||
},
|
||||
[
|
||||
router,
|
||||
selectedThread,
|
||||
selectedThreadDetailWorktreePath,
|
||||
selectedThreadProject,
|
||||
terminalMenuSessions,
|
||||
],
|
||||
);
|
||||
|
||||
if (!environmentId || !threadId) {
|
||||
return <LoadingScreen message="Opening thread…" />;
|
||||
}
|
||||
@@ -223,6 +321,12 @@ export function ThreadRouteScreen() {
|
||||
currentBranch={selectedThreadDetail.branch}
|
||||
gitStatus={gitStatus.data}
|
||||
gitOperationLabel={gitState.gitOperationLabel}
|
||||
canOpenTerminal={Boolean(selectedThreadProject?.workspaceRoot)}
|
||||
projectScripts={selectedThreadProject?.scripts ?? []}
|
||||
terminalSessions={terminalMenuSessions}
|
||||
onOpenTerminal={handleOpenTerminal}
|
||||
onOpenNewTerminal={handleOpenNewTerminal}
|
||||
onRunProjectScript={handleRunProjectScript}
|
||||
onPull={gitActions.onPullSelectedThreadBranch}
|
||||
onRunAction={gitActions.onRunSelectedThreadGitAction}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { DEFAULT_TERMINAL_ID } from "@t3tools/contracts";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { getEnvironmentClient } from "../../state/use-remote-environment-registry";
|
||||
import { useTerminalSession, useTerminalSessionTarget } from "../../state/use-terminal-session";
|
||||
import { TerminalSurface } from "../../native/terminal/NativeTerminalSurface";
|
||||
import { hasNativeTerminalSurface } from "../../native/terminal/nativeTerminalModule";
|
||||
|
||||
interface ThreadTerminalPanelProps {
|
||||
readonly environmentId: string;
|
||||
readonly threadId: string;
|
||||
readonly cwd: string;
|
||||
readonly worktreePath: string | null;
|
||||
readonly visible: boolean;
|
||||
readonly onClose: () => void;
|
||||
}
|
||||
|
||||
const DEFAULT_TERMINAL_COLS = 80;
|
||||
const DEFAULT_TERMINAL_ROWS = 24;
|
||||
|
||||
export const ThreadTerminalPanel = memo(function ThreadTerminalPanel(
|
||||
props: ThreadTerminalPanelProps,
|
||||
) {
|
||||
const nativeTerminalAvailable = hasNativeTerminalSurface();
|
||||
const terminalId = DEFAULT_TERMINAL_ID;
|
||||
const target = useTerminalSessionTarget({
|
||||
environmentId: props.environmentId,
|
||||
threadId: props.threadId,
|
||||
terminalId,
|
||||
});
|
||||
const terminal = useTerminalSession(target);
|
||||
const [lastGridSize, setLastGridSize] = useState({
|
||||
cols: DEFAULT_TERMINAL_COLS,
|
||||
rows: DEFAULT_TERMINAL_ROWS,
|
||||
});
|
||||
const hasOpenedRef = useRef(false);
|
||||
|
||||
const terminalKey = useMemo(
|
||||
() => `${props.environmentId}:${props.threadId}:${terminalId}`,
|
||||
[props.environmentId, props.threadId, terminalId],
|
||||
);
|
||||
const isRunning = terminal.status === "running" || terminal.status === "starting";
|
||||
|
||||
useEffect(() => {
|
||||
hasOpenedRef.current = false;
|
||||
}, [terminalKey]);
|
||||
|
||||
const openTerminal = useCallback(async () => {
|
||||
const client = getEnvironmentClient(props.environmentId);
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
await client.terminal.open({
|
||||
threadId: props.threadId,
|
||||
terminalId,
|
||||
cwd: props.cwd,
|
||||
worktreePath: props.worktreePath,
|
||||
cols: lastGridSize.cols,
|
||||
rows: lastGridSize.rows,
|
||||
});
|
||||
}, [
|
||||
lastGridSize.cols,
|
||||
lastGridSize.rows,
|
||||
props.cwd,
|
||||
props.environmentId,
|
||||
props.threadId,
|
||||
props.worktreePath,
|
||||
terminalId,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!props.visible || hasOpenedRef.current || terminal.status !== "closed") {
|
||||
return;
|
||||
}
|
||||
|
||||
hasOpenedRef.current = true;
|
||||
void openTerminal().catch(() => {
|
||||
hasOpenedRef.current = false;
|
||||
});
|
||||
}, [openTerminal, props.visible, terminal.status]);
|
||||
|
||||
const handleInput = useCallback(
|
||||
(data: string) => {
|
||||
const client = getEnvironmentClient(props.environmentId);
|
||||
if (!client || !isRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
void client.terminal.write({
|
||||
threadId: props.threadId,
|
||||
terminalId,
|
||||
data,
|
||||
});
|
||||
},
|
||||
[isRunning, props.environmentId, props.threadId, terminalId],
|
||||
);
|
||||
|
||||
const handleResize = useCallback(
|
||||
(size: { readonly cols: number; readonly rows: number }) => {
|
||||
if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) {
|
||||
return;
|
||||
}
|
||||
|
||||
setLastGridSize(size);
|
||||
const client = getEnvironmentClient(props.environmentId);
|
||||
if (!client || !isRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
void client.terminal.resize({
|
||||
threadId: props.threadId,
|
||||
terminalId,
|
||||
cols: size.cols,
|
||||
rows: size.rows,
|
||||
});
|
||||
},
|
||||
[
|
||||
isRunning,
|
||||
lastGridSize.cols,
|
||||
lastGridSize.rows,
|
||||
props.environmentId,
|
||||
props.threadId,
|
||||
terminalId,
|
||||
],
|
||||
);
|
||||
|
||||
if (!props.visible) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="absolute inset-x-3 bottom-28 top-28 overflow-hidden rounded-[8px] border border-white/10 bg-neutral-950 shadow-2xl">
|
||||
<View className="flex-row items-center justify-between border-b border-white/10 px-3 py-2">
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="font-t3-bold text-[13px] text-neutral-100" numberOfLines={1}>
|
||||
Terminal
|
||||
</Text>
|
||||
<Text className="text-[11px] text-neutral-500" numberOfLines={1}>
|
||||
{nativeTerminalAvailable ? "Native Ghostty surface" : "Text fallback active"}
|
||||
</Text>
|
||||
</View>
|
||||
<View className="flex-row items-center gap-2">
|
||||
{terminal.error ? (
|
||||
<Text className="max-w-44 text-right text-[11px] text-red-300" numberOfLines={1}>
|
||||
{terminal.error}
|
||||
</Text>
|
||||
) : null}
|
||||
<Pressable
|
||||
className="h-8 w-8 items-center justify-center rounded-[8px] bg-white/10"
|
||||
onPress={props.onClose}
|
||||
>
|
||||
<SymbolView name="xmark" size={13} tintColor="#e5e5e5" type="monochrome" />
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
<TerminalSurface
|
||||
terminalKey={terminalKey}
|
||||
buffer={terminal.buffer}
|
||||
isRunning={isRunning}
|
||||
onInput={handleInput}
|
||||
onResize={handleResize}
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveTerminalRouteBootstrap } from "./terminalRouteBootstrap";
|
||||
|
||||
describe("resolveTerminalRouteBootstrap", () => {
|
||||
it("redirects bare terminal routes to another already-running terminal for the thread", () => {
|
||||
expect(
|
||||
resolveTerminalRouteBootstrap({
|
||||
hasThread: true,
|
||||
hasWorkspaceRoot: true,
|
||||
hasOpened: false,
|
||||
requestedTerminalId: null,
|
||||
currentTerminalId: "default",
|
||||
runningTerminalId: "term-2",
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "redirect",
|
||||
terminalId: "term-2",
|
||||
});
|
||||
});
|
||||
|
||||
it("hydrates the current running terminal instead of skipping open", () => {
|
||||
expect(
|
||||
resolveTerminalRouteBootstrap({
|
||||
hasThread: true,
|
||||
hasWorkspaceRoot: true,
|
||||
hasOpened: false,
|
||||
requestedTerminalId: null,
|
||||
currentTerminalId: "default",
|
||||
runningTerminalId: "default",
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "open",
|
||||
});
|
||||
});
|
||||
|
||||
it("opens explicit terminal routes once so they replay existing history", () => {
|
||||
expect(
|
||||
resolveTerminalRouteBootstrap({
|
||||
hasThread: true,
|
||||
hasWorkspaceRoot: true,
|
||||
hasOpened: false,
|
||||
requestedTerminalId: "term-2",
|
||||
currentTerminalId: "term-2",
|
||||
runningTerminalId: "term-2",
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "open",
|
||||
});
|
||||
});
|
||||
|
||||
it("stays idle after the route already bootstrapped once", () => {
|
||||
expect(
|
||||
resolveTerminalRouteBootstrap({
|
||||
hasThread: true,
|
||||
hasWorkspaceRoot: true,
|
||||
hasOpened: true,
|
||||
requestedTerminalId: null,
|
||||
currentTerminalId: "default",
|
||||
runningTerminalId: "default",
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "idle",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,734 @@
|
||||
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 { KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import Animated, { useAnimatedKeyboard, useAnimatedStyle } from "react-native-reanimated";
|
||||
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { LoadingScreen } from "../../components/LoadingScreen";
|
||||
import { buildThreadTerminalRoutePath } from "../../lib/routes";
|
||||
import {
|
||||
getEnvironmentClient,
|
||||
useRemoteEnvironmentState,
|
||||
} from "../../state/use-remote-environment-registry";
|
||||
import {
|
||||
terminalSessionManager,
|
||||
useKnownTerminalSessions,
|
||||
useTerminalSession,
|
||||
useTerminalSessionTarget,
|
||||
} from "../../state/use-terminal-session";
|
||||
import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { TerminalSurface } from "../../native/terminal/NativeTerminalSurface";
|
||||
import { loadPreferences, savePreferencesPatch } from "../../lib/storage";
|
||||
import { resolveTerminalRouteBootstrap } from "./terminalRouteBootstrap";
|
||||
import { resolveTerminalOpenLocation } from "./terminalLaunchContext";
|
||||
import {
|
||||
basename,
|
||||
buildTerminalMenuSessions,
|
||||
getTerminalLabel,
|
||||
getTerminalStatusLabel,
|
||||
nextTerminalId,
|
||||
} from "./terminalMenu";
|
||||
import {
|
||||
DEFAULT_TERMINAL_FONT_SIZE,
|
||||
MAX_TERMINAL_FONT_SIZE,
|
||||
MIN_TERMINAL_FONT_SIZE,
|
||||
TERMINAL_FONT_SIZE_STEP,
|
||||
normalizeTerminalFontSize,
|
||||
} from "./terminalPreferences";
|
||||
|
||||
const DEFAULT_TERMINAL_COLS = 80;
|
||||
const DEFAULT_TERMINAL_ROWS = 24;
|
||||
const TERMINAL_ACCESSORY_HEIGHT = 52;
|
||||
|
||||
type PendingModifier = "ctrl" | "meta";
|
||||
type HostPlatform = "mac" | "linux" | "windows" | "unknown";
|
||||
|
||||
type TerminalToolbarAction =
|
||||
| { readonly kind: "send"; readonly key: string; readonly label: string; readonly data: string }
|
||||
| {
|
||||
readonly kind: "modifier";
|
||||
readonly key: string;
|
||||
readonly label: string;
|
||||
readonly modifier: PendingModifier;
|
||||
};
|
||||
|
||||
interface TerminalMenuSession {
|
||||
readonly terminalId: string;
|
||||
readonly cwd: string | null;
|
||||
readonly status: "starting" | "running" | "exited" | "error" | "closed";
|
||||
readonly updatedAt: string | null;
|
||||
}
|
||||
|
||||
function getTerminalStatusTone(input: {
|
||||
readonly status: TerminalMenuSession["status"];
|
||||
readonly hasRunningSubprocess?: boolean;
|
||||
}): {
|
||||
readonly tintColor: string;
|
||||
readonly textColor: string;
|
||||
} {
|
||||
if (input.status === "running") {
|
||||
if (input.hasRunningSubprocess) {
|
||||
return {
|
||||
tintColor: "#fbbf24",
|
||||
textColor: "#a3a3a3",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
tintColor: "#34d399",
|
||||
textColor: "#a3a3a3",
|
||||
};
|
||||
}
|
||||
|
||||
if (input.status === "starting") {
|
||||
return {
|
||||
tintColor: "#f59e0b",
|
||||
textColor: "#a3a3a3",
|
||||
};
|
||||
}
|
||||
|
||||
if (input.status === "error") {
|
||||
return {
|
||||
tintColor: "#ef4444",
|
||||
textColor: "#fca5a5",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
tintColor: "#ef4444",
|
||||
textColor: "#a3a3a3",
|
||||
};
|
||||
}
|
||||
|
||||
function firstRouteParam(value: string | string[] | undefined): string | null {
|
||||
if (Array.isArray(value)) {
|
||||
return value[0] ?? null;
|
||||
}
|
||||
|
||||
return value ?? null;
|
||||
}
|
||||
|
||||
function inferHostPlatform(environmentLabel: string | null): HostPlatform {
|
||||
const value = environmentLabel?.toLowerCase() ?? "";
|
||||
if (
|
||||
value.includes("mac") ||
|
||||
value.includes("macbook") ||
|
||||
value.includes("mac mini") ||
|
||||
value.includes("imac") ||
|
||||
value.includes("darwin")
|
||||
) {
|
||||
return "mac";
|
||||
}
|
||||
if (value.includes("windows") || value.includes("win")) {
|
||||
return "windows";
|
||||
}
|
||||
if (value.includes("linux") || value.includes("ubuntu") || value.includes("debian")) {
|
||||
return "linux";
|
||||
}
|
||||
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function applyCtrlModifier(input: string): string {
|
||||
const firstCharacter = input[0];
|
||||
if (!firstCharacter) {
|
||||
return input;
|
||||
}
|
||||
|
||||
const lowerCharacter = firstCharacter.toLowerCase();
|
||||
if (lowerCharacter >= "a" && lowerCharacter <= "z") {
|
||||
return String.fromCharCode(lowerCharacter.charCodeAt(0) - 96);
|
||||
}
|
||||
|
||||
if (firstCharacter === "@") return "\u0000";
|
||||
if (firstCharacter === "[") return "\u001b";
|
||||
if (firstCharacter === "\\") return "\u001c";
|
||||
if (firstCharacter === "]") return "\u001d";
|
||||
if (firstCharacter === "^") return "\u001e";
|
||||
if (firstCharacter === "_") return "\u001f";
|
||||
if (firstCharacter === "?") return "\u007f";
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
export function ThreadTerminalRouteScreen() {
|
||||
const router = useRouter();
|
||||
const keyboard = useAnimatedKeyboard();
|
||||
const { isLoadingSavedConnection } = useRemoteEnvironmentState();
|
||||
const params = useLocalSearchParams<{
|
||||
environmentId?: string | string[];
|
||||
threadId?: string | string[];
|
||||
terminalId?: string | string[];
|
||||
}>();
|
||||
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
|
||||
useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const requestedTerminalId = firstRouteParam(params.terminalId);
|
||||
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 hasOpenedRef = useRef(false);
|
||||
const hasLoadedFontPreferenceRef = useRef(false);
|
||||
|
||||
const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID;
|
||||
const target = useTerminalSessionTarget({
|
||||
environmentId: selectedThread?.environmentId ?? null,
|
||||
threadId: selectedThread?.id ?? null,
|
||||
terminalId,
|
||||
});
|
||||
const terminal = useTerminalSession(target);
|
||||
const terminalKey = useMemo(
|
||||
() =>
|
||||
selectedThread
|
||||
? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`
|
||||
: terminalId,
|
||||
[selectedThread, terminalId],
|
||||
);
|
||||
const isRunning = terminal.status === "running" || terminal.status === "starting";
|
||||
const cwd = terminal.snapshot?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;
|
||||
const hostPlatform = useMemo(
|
||||
() => inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),
|
||||
[selectedEnvironmentConnection?.environmentLabel],
|
||||
);
|
||||
const runningSession = useMemo(
|
||||
() =>
|
||||
knownSessions.find(
|
||||
(session) => session.state.status === "running" || session.state.status === "starting",
|
||||
) ?? null,
|
||||
[knownSessions],
|
||||
);
|
||||
const activeKnownSession = useMemo(
|
||||
() => knownSessions.find((session) => session.target.terminalId === terminalId) ?? null,
|
||||
[knownSessions, terminalId],
|
||||
);
|
||||
const terminalStatusTone = useMemo(
|
||||
() =>
|
||||
getTerminalStatusTone({
|
||||
status: terminal.status,
|
||||
hasRunningSubprocess: terminal.hasRunningSubprocess,
|
||||
}),
|
||||
[terminal.hasRunningSubprocess, terminal.status],
|
||||
);
|
||||
const headerTitle = useMemo(() => {
|
||||
const topLineParts = [
|
||||
selectedEnvironmentConnection?.environmentLabel ?? null,
|
||||
selectedThreadProject?.title ?? null,
|
||||
].filter((value): value is string => Boolean(value));
|
||||
|
||||
return {
|
||||
topLine: topLineParts.join(" \u00b7 "),
|
||||
bottomLine: cwd ?? selectedThreadProject?.workspaceRoot ?? "",
|
||||
};
|
||||
}, [
|
||||
cwd,
|
||||
selectedEnvironmentConnection?.environmentLabel,
|
||||
selectedThreadProject?.title,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
]);
|
||||
const terminalToolbarActions = useMemo<ReadonlyArray<TerminalToolbarAction>>(() => {
|
||||
const modifierActions: ReadonlyArray<TerminalToolbarAction> =
|
||||
hostPlatform === "mac"
|
||||
? [
|
||||
{ kind: "modifier", key: "cmd", label: "cmd", modifier: "meta" },
|
||||
{ kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
|
||||
]
|
||||
: [
|
||||
{ kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
|
||||
{ kind: "modifier", key: "alt", label: "alt", modifier: "meta" },
|
||||
];
|
||||
|
||||
return [
|
||||
{ kind: "send", key: "esc", label: "esc", data: "\u001b" },
|
||||
...modifierActions,
|
||||
{ kind: "send", key: "tab", label: "tab", data: "\t" },
|
||||
{ kind: "send", key: "up", label: "↑", data: "\u001b[A" },
|
||||
{ kind: "send", key: "down", label: "↓", data: "\u001b[B" },
|
||||
{ kind: "send", key: "left", label: "←", data: "\u001b[D" },
|
||||
{ kind: "send", key: "right", label: "→", data: "\u001b[C" },
|
||||
{ kind: "send", key: "tilde", label: "~", data: "~" },
|
||||
{ kind: "send", key: "pipe", label: "|", data: "|" },
|
||||
{ kind: "send", key: "slash", label: "/", data: "/" },
|
||||
{ kind: "send", key: "dash", label: "-", data: "-" },
|
||||
];
|
||||
}, [hostPlatform]);
|
||||
const terminalBottomInset = TERMINAL_ACCESSORY_HEIGHT;
|
||||
const terminalContainerAnimatedStyle = useAnimatedStyle(() => ({
|
||||
paddingBottom:
|
||||
keyboard.height.value > 0
|
||||
? keyboard.height.value + TERMINAL_ACCESSORY_HEIGHT
|
||||
: terminalBottomInset,
|
||||
}));
|
||||
|
||||
const terminalMenuSessions = useMemo<ReadonlyArray<TerminalMenuSession>>(
|
||||
() =>
|
||||
buildTerminalMenuSessions({
|
||||
knownSessions,
|
||||
workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
|
||||
currentSession: {
|
||||
terminalId,
|
||||
cwd: cwd ?? null,
|
||||
status: terminal.status,
|
||||
updatedAt: terminal.updatedAt,
|
||||
},
|
||||
}),
|
||||
[
|
||||
cwd,
|
||||
knownSessions,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
terminal.status,
|
||||
terminal.updatedAt,
|
||||
terminalId,
|
||||
],
|
||||
);
|
||||
|
||||
const openTerminal = useCallback(async () => {
|
||||
if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = getEnvironmentClient(selectedThread.environmentId);
|
||||
if (!client) {
|
||||
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({
|
||||
threadId: selectedThread.id,
|
||||
terminalId,
|
||||
cwd: launchLocation.cwd,
|
||||
worktreePath: launchLocation.worktreePath,
|
||||
cols: lastGridSize.cols,
|
||||
rows: lastGridSize.rows,
|
||||
});
|
||||
|
||||
terminalSessionManager.syncSnapshot({ environmentId: selectedThread.environmentId }, snapshot);
|
||||
}, [
|
||||
lastGridSize.cols,
|
||||
lastGridSize.rows,
|
||||
activeKnownSession?.state.snapshot,
|
||||
selectedThreadDetail?.worktreePath,
|
||||
selectedThread,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
terminal.snapshot,
|
||||
terminalId,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
hasOpenedRef.current = false;
|
||||
}, [terminalKey]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
void loadPreferences()
|
||||
.then((preferences) => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
setFontSize(normalizeTerminalFontSize(preferences.terminalFontSize));
|
||||
hasLoadedFontPreferenceRef.current = true;
|
||||
})
|
||||
.catch(() => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
hasLoadedFontPreferenceRef.current = true;
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasLoadedFontPreferenceRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
void savePreferencesPatch({
|
||||
terminalFontSize: normalizeTerminalFontSize(fontSize),
|
||||
});
|
||||
}, [fontSize]);
|
||||
|
||||
useEffect(() => {
|
||||
const bootstrapAction = resolveTerminalRouteBootstrap({
|
||||
hasThread: selectedThread !== null,
|
||||
hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
|
||||
hasOpened: hasOpenedRef.current,
|
||||
requestedTerminalId,
|
||||
currentTerminalId: terminalId,
|
||||
runningTerminalId: runningSession?.target.terminalId ?? null,
|
||||
});
|
||||
if (bootstrapAction.kind === "idle" || !selectedThread) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (bootstrapAction.kind === "redirect") {
|
||||
router.replace(buildThreadTerminalRoutePath(selectedThread, bootstrapAction.terminalId));
|
||||
return;
|
||||
}
|
||||
|
||||
hasOpenedRef.current = true;
|
||||
void openTerminal().catch(() => {
|
||||
hasOpenedRef.current = false;
|
||||
});
|
||||
}, [
|
||||
openTerminal,
|
||||
requestedTerminalId,
|
||||
router,
|
||||
runningSession,
|
||||
selectedThread,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
terminalId,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
setPendingModifier(null);
|
||||
}, [terminalId]);
|
||||
|
||||
const writeInput = useCallback(
|
||||
(data: string) => {
|
||||
if (!selectedThread || !isRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = getEnvironmentClient(selectedThread.environmentId);
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
void client.terminal.write({
|
||||
threadId: selectedThread.id,
|
||||
terminalId,
|
||||
data,
|
||||
});
|
||||
},
|
||||
[isRunning, selectedThread, terminalId],
|
||||
);
|
||||
|
||||
const handleInput = useCallback(
|
||||
(data: string) => {
|
||||
if (data.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (pendingModifier === "ctrl") {
|
||||
setPendingModifier(null);
|
||||
writeInput(applyCtrlModifier(data));
|
||||
} else if (pendingModifier === "meta") {
|
||||
setPendingModifier(null);
|
||||
writeInput(`\u001b${data}`);
|
||||
} else {
|
||||
writeInput(data);
|
||||
}
|
||||
},
|
||||
[pendingModifier, writeInput],
|
||||
);
|
||||
|
||||
const handleResize = useCallback(
|
||||
(size: { readonly cols: number; readonly rows: number }) => {
|
||||
if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) {
|
||||
return;
|
||||
}
|
||||
|
||||
setLastGridSize(size);
|
||||
if (!selectedThread || !isRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = getEnvironmentClient(selectedThread.environmentId);
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
void client.terminal.resize({
|
||||
threadId: selectedThread.id,
|
||||
terminalId,
|
||||
cols: size.cols,
|
||||
rows: size.rows,
|
||||
});
|
||||
},
|
||||
[isRunning, lastGridSize.cols, lastGridSize.rows, selectedThread, terminalId],
|
||||
);
|
||||
|
||||
const handleSelectTerminal = useCallback(
|
||||
(nextTerminalId: string) => {
|
||||
if (!selectedThread || nextTerminalId === terminalId) {
|
||||
return;
|
||||
}
|
||||
|
||||
router.replace(buildThreadTerminalRoutePath(selectedThread, nextTerminalId));
|
||||
},
|
||||
[router, selectedThread, terminalId],
|
||||
);
|
||||
|
||||
const handleOpenNewTerminal = useCallback(() => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
|
||||
router.replace(
|
||||
buildThreadTerminalRoutePath(
|
||||
selectedThread,
|
||||
nextTerminalId(terminalMenuSessions.map((session) => session.terminalId)),
|
||||
),
|
||||
);
|
||||
}, [router, selectedThread, terminalMenuSessions]);
|
||||
|
||||
const adjustFontSize = useCallback((delta: number) => {
|
||||
setTimeout(() => {
|
||||
setFontSize((current) => normalizeTerminalFontSize(current + delta));
|
||||
}, 0);
|
||||
}, []);
|
||||
|
||||
const handleDecreaseFontSize = useCallback(() => {
|
||||
adjustFontSize(-TERMINAL_FONT_SIZE_STEP);
|
||||
}, [adjustFontSize]);
|
||||
|
||||
const handleIncreaseFontSize = useCallback(() => {
|
||||
adjustFontSize(TERMINAL_FONT_SIZE_STEP);
|
||||
}, [adjustFontSize]);
|
||||
|
||||
const handleToolbarActionPress = useCallback(
|
||||
(action: TerminalToolbarAction) => {
|
||||
if (action.kind === "modifier") {
|
||||
setPendingModifier((current) => (current === action.modifier ? null : action.modifier));
|
||||
return;
|
||||
}
|
||||
|
||||
setPendingModifier(null);
|
||||
if (pendingModifier === "ctrl") {
|
||||
writeInput(applyCtrlModifier(action.data));
|
||||
} else if (pendingModifier === "meta") {
|
||||
writeInput(`\u001b${action.data}`);
|
||||
} else {
|
||||
writeInput(action.data);
|
||||
}
|
||||
},
|
||||
[pendingModifier, writeInput],
|
||||
);
|
||||
|
||||
if (!selectedThread) {
|
||||
if (isLoadingSavedConnection) {
|
||||
return <LoadingScreen message="Opening terminal…" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<EmptyState
|
||||
title="Thread unavailable"
|
||||
detail="This terminal route needs an active thread and workspace."
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (!selectedThreadProject?.workspaceRoot) {
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<EmptyState
|
||||
title="Terminal unavailable"
|
||||
detail="This thread does not have a workspace root yet, so there is nowhere to open a shell."
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerShown: true,
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: { backgroundColor: "#0a0a0a" },
|
||||
headerTintColor: "#f5f5f5",
|
||||
headerTitleAlign: "center",
|
||||
title: "",
|
||||
headerTitle: () => (
|
||||
<View
|
||||
style={{
|
||||
alignItems: "center",
|
||||
gap: 1,
|
||||
maxWidth: 240,
|
||||
}}
|
||||
>
|
||||
<RNText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: "#f5f5f5",
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 13,
|
||||
lineHeight: 16,
|
||||
}}
|
||||
>
|
||||
{headerTitle.topLine}
|
||||
</RNText>
|
||||
<RNText
|
||||
ellipsizeMode="middle"
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: "#8f8f94",
|
||||
fontFamily: "Menlo",
|
||||
fontSize: 11,
|
||||
lineHeight: 14,
|
||||
}}
|
||||
>
|
||||
{headerTitle.bottomLine}
|
||||
</RNText>
|
||||
</View>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu
|
||||
icon="circle.fill"
|
||||
style={{
|
||||
color: terminalStatusTone.textColor,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
fontWeight: "700",
|
||||
}}
|
||||
tintColor={terminalStatusTone.tintColor}
|
||||
title="Terminal options"
|
||||
>
|
||||
<Stack.Toolbar.Label>
|
||||
{getTerminalStatusLabel({
|
||||
status: terminal.status,
|
||||
hasRunningSubprocess: terminal.hasRunningSubprocess,
|
||||
})}
|
||||
</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.Menu icon="textformat.size" inline title="Text size">
|
||||
<Stack.Toolbar.Label>Text size</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.MenuAction
|
||||
disabled={fontSize <= MIN_TERMINAL_FONT_SIZE}
|
||||
discoverabilityLabel="Decrease terminal text size"
|
||||
onPress={handleDecreaseFontSize}
|
||||
>
|
||||
<Stack.Toolbar.Label>{`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
<Stack.Toolbar.MenuAction
|
||||
disabled={fontSize >= MAX_TERMINAL_FONT_SIZE}
|
||||
discoverabilityLabel="Increase terminal text size"
|
||||
onPress={handleIncreaseFontSize}
|
||||
>
|
||||
<Stack.Toolbar.Label>{`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
{terminalMenuSessions.map((session) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={session.terminalId}
|
||||
icon={session.terminalId === terminalId ? "checkmark" : "terminal"}
|
||||
onPress={() => handleSelectTerminal(session.terminalId)}
|
||||
subtitle={[getTerminalStatusLabel({ status: session.status }), basename(session.cwd)]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
<Stack.Toolbar.Label>{getTerminalLabel(session.terminalId)}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="plus"
|
||||
onPress={handleOpenNewTerminal}
|
||||
subtitle={`Start another shell in ${basename(selectedThreadProject.workspaceRoot) ?? "this workspace"}`}
|
||||
>
|
||||
<Stack.Toolbar.Label>Open new terminal</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar>
|
||||
|
||||
<View style={{ flex: 1, backgroundColor: "#050505" }}>
|
||||
<Animated.View style={[{ flex: 1 }, terminalContainerAnimatedStyle]}>
|
||||
<TerminalSurface
|
||||
buffer={terminal.buffer}
|
||||
fontSize={fontSize}
|
||||
isRunning={isRunning}
|
||||
onInput={handleInput}
|
||||
onResize={handleResize}
|
||||
style={{ flex: 1 }}
|
||||
terminalKey={terminalKey}
|
||||
/>
|
||||
</Animated.View>
|
||||
|
||||
<KeyboardStickyView style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: "#0a0a0a",
|
||||
borderTopColor: "rgba(255,255,255,0.08)",
|
||||
borderTopWidth: 1,
|
||||
minHeight: TERMINAL_ACCESSORY_HEIGHT,
|
||||
paddingBottom: 4,
|
||||
paddingHorizontal: 8,
|
||||
paddingTop: 4,
|
||||
}}
|
||||
>
|
||||
<ScrollView
|
||||
horizontal
|
||||
contentContainerStyle={{ alignItems: "center", gap: 6, paddingRight: 2 }}
|
||||
showsHorizontalScrollIndicator={false}
|
||||
>
|
||||
{terminalToolbarActions.map((action) => {
|
||||
const active = action.kind === "modifier" && pendingModifier === action.modifier;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
key={action.key}
|
||||
onPress={() => handleToolbarActionPress(action)}
|
||||
style={({ pressed }) => ({
|
||||
alignItems: "center",
|
||||
backgroundColor: active
|
||||
? "rgba(74, 222, 128, 0.18)"
|
||||
: 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)",
|
||||
borderRadius: 12,
|
||||
borderWidth: 1,
|
||||
justifyContent: "center",
|
||||
minWidth: action.label.length > 1 ? 46 : 38,
|
||||
paddingHorizontal: 11,
|
||||
paddingVertical: 8,
|
||||
})}
|
||||
>
|
||||
<RNText
|
||||
style={{
|
||||
color: active ? "#bbf7d0" : "#f5f5f5",
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
fontWeight: "700",
|
||||
textTransform: action.kind === "modifier" ? "uppercase" : "none",
|
||||
}}
|
||||
>
|
||||
{action.label}
|
||||
</RNText>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
</View>
|
||||
</KeyboardStickyView>
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -10,12 +10,14 @@ import { useGitStatus } from "../../../state/use-git-status";
|
||||
import { useThreadSelection } from "../../../state/use-thread-selection";
|
||||
import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions";
|
||||
import { useSelectedThreadGitState } from "../use-selected-thread-git-state";
|
||||
import { useSelectedThreadWorktree } from "../use-selected-thread-worktree";
|
||||
import { SheetActionButton } from "./gitSheetComponents";
|
||||
|
||||
export function GitBranchesSheet() {
|
||||
const router = useRouter();
|
||||
const insets = useSafeAreaInsets();
|
||||
const { selectedThread, selectedThreadProject } = useThreadSelection();
|
||||
const { selectedThread } = useThreadSelection();
|
||||
const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree();
|
||||
const gitState = useSelectedThreadGitState();
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
|
||||
@@ -27,11 +29,11 @@ export function GitBranchesSheet() {
|
||||
|
||||
const gitStatus = useGitStatus({
|
||||
environmentId: selectedThread?.environmentId ?? "",
|
||||
cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
|
||||
cwd: selectedThreadCwd,
|
||||
});
|
||||
|
||||
const currentBranchLabel = gitStatus.data?.branch ?? selectedThread?.branch ?? "Detached HEAD";
|
||||
const currentWorktreePath = selectedThread?.worktreePath ?? null;
|
||||
const currentWorktreePath = selectedThreadWorktreePath;
|
||||
const availableBranches = gitState.selectedThreadBranches;
|
||||
const branchesLoading = gitState.selectedThreadBranchesLoading;
|
||||
const busy = gitState.gitOperationLabel !== null;
|
||||
|
||||
@@ -9,13 +9,15 @@ import { useGitStatus } from "../../../state/use-git-status";
|
||||
import { useThreadSelection } from "../../../state/use-thread-selection";
|
||||
import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions";
|
||||
import { useSelectedThreadGitState } from "../use-selected-thread-git-state";
|
||||
import { useSelectedThreadWorktree } from "../use-selected-thread-worktree";
|
||||
import { SheetActionButton } from "./gitSheetComponents";
|
||||
|
||||
export function GitCommitSheet() {
|
||||
const router = useRouter();
|
||||
const insets = useSafeAreaInsets();
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
const { selectedThread, selectedThreadProject } = useThreadSelection();
|
||||
const { selectedThread } = useThreadSelection();
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
const gitState = useSelectedThreadGitState();
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
|
||||
@@ -27,7 +29,7 @@ export function GitCommitSheet() {
|
||||
|
||||
const gitStatus = useGitStatus({
|
||||
environmentId: selectedThread?.environmentId ?? "",
|
||||
cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
|
||||
cwd: selectedThreadCwd,
|
||||
});
|
||||
|
||||
const busy = gitState.gitOperationLabel !== null;
|
||||
|
||||
@@ -17,6 +17,7 @@ import { useGitStatus } from "../../../state/use-git-status";
|
||||
import { useThreadSelection } from "../../../state/use-thread-selection";
|
||||
import { useSelectedThreadGitActions } from "../use-selected-thread-git-actions";
|
||||
import { useSelectedThreadGitState } from "../use-selected-thread-git-state";
|
||||
import { useSelectedThreadWorktree } from "../use-selected-thread-worktree";
|
||||
import { MetaCard, SheetListRow, menuItemIconName, statusSummary } from "./gitSheetComponents";
|
||||
|
||||
export function GitOverviewSheet() {
|
||||
@@ -26,7 +27,8 @@ export function GitOverviewSheet() {
|
||||
environmentId: string;
|
||||
threadId: string;
|
||||
}>();
|
||||
const { selectedThread, selectedThreadProject } = useThreadSelection();
|
||||
const { selectedThread } = useThreadSelection();
|
||||
const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree();
|
||||
const gitState = useSelectedThreadGitState();
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
|
||||
@@ -35,11 +37,11 @@ export function GitOverviewSheet() {
|
||||
|
||||
const gitStatus = useGitStatus({
|
||||
environmentId: selectedThread?.environmentId ?? "",
|
||||
cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
|
||||
cwd: selectedThreadCwd,
|
||||
});
|
||||
|
||||
const currentBranchLabel = gitStatus.data?.branch ?? selectedThread?.branch ?? "Detached HEAD";
|
||||
const currentWorktreePath = selectedThread?.worktreePath ?? null;
|
||||
const currentWorktreePath = selectedThreadWorktreePath;
|
||||
const gitOperationLabel = gitState.gitOperationLabel;
|
||||
const busy = gitOperationLabel !== null;
|
||||
const isRepo = gitStatus.data?.isRepo ?? true;
|
||||
|
||||
@@ -23,8 +23,8 @@ import { cn } from "../../../lib/cn";
|
||||
import { useThemeColor } from "../../../lib/useThemeColor";
|
||||
import { getEnvironmentClient } from "../../../state/use-remote-environment-registry";
|
||||
import { useSelectedThreadDetail } from "../../../state/use-thread-detail";
|
||||
import { useThreadSelection } from "../../../state/use-thread-selection";
|
||||
import { useThreadDraftForThread } from "../use-thread-composer-state";
|
||||
import { useSelectedThreadWorktree } from "../use-selected-thread-worktree";
|
||||
import {
|
||||
getCachedReviewParsedDiff,
|
||||
setReviewGitSections,
|
||||
@@ -445,7 +445,6 @@ export function ReviewSheet() {
|
||||
}>();
|
||||
const { draftMessage } = useThreadDraftForThread({ environmentId, threadId });
|
||||
const reviewCache = useReviewCacheForThread({ environmentId, threadId });
|
||||
const { selectedThreadProject } = useThreadSelection();
|
||||
const selectedThread = useSelectedThreadDetail();
|
||||
const [loadingTurnIds, setLoadingTurnIds] = useState<Record<string, boolean>>({});
|
||||
const [loadingGitDiffs, setLoadingGitDiffs] = useState(false);
|
||||
@@ -464,8 +463,9 @@ export function ReviewSheet() {
|
||||
const highlightQueueActiveRef = useRef(false);
|
||||
const highlightableFilesByIdRef = useRef<ReadonlyMap<string, ReviewRenderableFile>>(new Map());
|
||||
const selectedThemeRef = useRef<ReviewDiffTheme>(selectedTheme);
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
|
||||
const cwd = selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null;
|
||||
const cwd = selectedThreadCwd;
|
||||
const readyCheckpoints = useMemo(
|
||||
() => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []),
|
||||
[selectedThread?.checkpoints],
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
resolvePreferredThreadWorktreePath,
|
||||
resolveTerminalOpenLocation,
|
||||
} from "./terminalLaunchContext";
|
||||
|
||||
describe("resolvePreferredThreadWorktreePath", () => {
|
||||
it("prefers thread detail worktree paths over thread shell paths", () => {
|
||||
expect(
|
||||
resolvePreferredThreadWorktreePath({
|
||||
threadShellWorktreePath: "/repo/root",
|
||||
threadDetailWorktreePath: "/repo/worktrees/feature",
|
||||
}),
|
||||
).toBe("/repo/worktrees/feature");
|
||||
});
|
||||
|
||||
it("falls back to the thread shell worktree path when detail is unavailable", () => {
|
||||
expect(
|
||||
resolvePreferredThreadWorktreePath({
|
||||
threadShellWorktreePath: "/repo/worktrees/feature",
|
||||
threadDetailWorktreePath: null,
|
||||
}),
|
||||
).toBe("/repo/worktrees/feature");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveTerminalOpenLocation", () => {
|
||||
it("uses the thread detail worktree path before the workspace root for a fresh mobile open", () => {
|
||||
expect(
|
||||
resolveTerminalOpenLocation({
|
||||
terminalSnapshot: null,
|
||||
activeSessionSnapshot: null,
|
||||
workspaceRoot: "/repo/root",
|
||||
threadShellWorktreePath: null,
|
||||
threadDetailWorktreePath: "/repo/worktrees/feature",
|
||||
}),
|
||||
).toEqual({
|
||||
cwd: "/repo/worktrees/feature",
|
||||
worktreePath: "/repo/worktrees/feature",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the running terminal snapshot cwd when attaching to an existing session", () => {
|
||||
expect(
|
||||
resolveTerminalOpenLocation({
|
||||
terminalSnapshot: null,
|
||||
activeSessionSnapshot: {
|
||||
cwd: "/repo/worktrees/feature",
|
||||
worktreePath: "/repo/worktrees/feature",
|
||||
},
|
||||
workspaceRoot: "/repo/root",
|
||||
threadShellWorktreePath: null,
|
||||
threadDetailWorktreePath: "/repo/worktrees/other",
|
||||
}),
|
||||
).toEqual({
|
||||
cwd: "/repo/worktrees/feature",
|
||||
worktreePath: "/repo/worktrees/feature",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
interface TerminalSnapshotLike {
|
||||
readonly cwd: string;
|
||||
readonly worktreePath: string | null;
|
||||
}
|
||||
|
||||
export function resolvePreferredThreadWorktreePath(input: {
|
||||
readonly threadShellWorktreePath: string | null;
|
||||
readonly threadDetailWorktreePath: string | null;
|
||||
}): string | null {
|
||||
return input.threadDetailWorktreePath ?? input.threadShellWorktreePath ?? null;
|
||||
}
|
||||
|
||||
export function resolveTerminalOpenLocation(input: {
|
||||
readonly terminalSnapshot: TerminalSnapshotLike | null;
|
||||
readonly activeSessionSnapshot: TerminalSnapshotLike | null;
|
||||
readonly workspaceRoot: string;
|
||||
readonly threadShellWorktreePath: string | null;
|
||||
readonly threadDetailWorktreePath: string | null;
|
||||
}): {
|
||||
readonly cwd: string;
|
||||
readonly worktreePath: string | null;
|
||||
} {
|
||||
const preferredThreadWorktreePath = resolvePreferredThreadWorktreePath({
|
||||
threadShellWorktreePath: input.threadShellWorktreePath,
|
||||
threadDetailWorktreePath: input.threadDetailWorktreePath,
|
||||
});
|
||||
|
||||
return {
|
||||
cwd:
|
||||
input.terminalSnapshot?.cwd ??
|
||||
input.activeSessionSnapshot?.cwd ??
|
||||
preferredThreadWorktreePath ??
|
||||
input.workspaceRoot,
|
||||
worktreePath:
|
||||
input.terminalSnapshot?.worktreePath ??
|
||||
input.activeSessionSnapshot?.worktreePath ??
|
||||
preferredThreadWorktreePath,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { KnownTerminalSession } from "@t3tools/client-runtime";
|
||||
import { DEFAULT_TERMINAL_ID } from "@t3tools/contracts";
|
||||
|
||||
import { buildTerminalMenuSessions, resolveProjectScriptTerminalId } from "./terminalMenu";
|
||||
|
||||
function makeKnownSession(input: {
|
||||
readonly terminalId: string;
|
||||
readonly status: KnownTerminalSession["state"]["status"];
|
||||
readonly cwd?: string | null;
|
||||
readonly updatedAt?: string | null;
|
||||
}): KnownTerminalSession {
|
||||
return {
|
||||
target: {
|
||||
environmentId: "env-1",
|
||||
threadId: "thread-1",
|
||||
terminalId: input.terminalId,
|
||||
},
|
||||
state: {
|
||||
snapshot: input.cwd
|
||||
? {
|
||||
threadId: "thread-1",
|
||||
terminalId: input.terminalId,
|
||||
cwd: input.cwd,
|
||||
worktreePath: input.cwd,
|
||||
status: input.status === "closed" ? "error" : input.status,
|
||||
pid: input.status === "running" ? 123 : null,
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: input.updatedAt ?? "2026-04-15T20:00:00.000Z",
|
||||
}
|
||||
: null,
|
||||
buffer: "",
|
||||
status: input.status,
|
||||
error: null,
|
||||
hasRunningSubprocess: false,
|
||||
updatedAt: input.updatedAt ?? "2026-04-15T20:00:00.000Z",
|
||||
version: 1,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildTerminalMenuSessions", () => {
|
||||
it("keeps the default shell and only includes running sessions by default", () => {
|
||||
expect(
|
||||
buildTerminalMenuSessions({
|
||||
knownSessions: [
|
||||
makeKnownSession({
|
||||
terminalId: "term-3",
|
||||
status: "running",
|
||||
cwd: "/workspace/feature",
|
||||
updatedAt: "2026-04-15T20:05:00.000Z",
|
||||
}),
|
||||
makeKnownSession({
|
||||
terminalId: "term-2",
|
||||
status: "exited",
|
||||
cwd: "/workspace/exited",
|
||||
updatedAt: "2026-04-15T20:06:00.000Z",
|
||||
}),
|
||||
],
|
||||
workspaceRoot: "/workspace/root",
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
cwd: "/workspace/root",
|
||||
status: "closed",
|
||||
updatedAt: null,
|
||||
},
|
||||
{
|
||||
terminalId: "term-3",
|
||||
cwd: "/workspace/feature",
|
||||
status: "running",
|
||||
updatedAt: "2026-04-15T20:05:00.000Z",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the current terminal visible even if it is no longer running", () => {
|
||||
expect(
|
||||
buildTerminalMenuSessions({
|
||||
knownSessions: [],
|
||||
workspaceRoot: "/workspace/root",
|
||||
currentSession: {
|
||||
terminalId: "term-4",
|
||||
cwd: "/workspace/exited",
|
||||
status: "exited",
|
||||
updatedAt: "2026-04-15T20:07:00.000Z",
|
||||
},
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
cwd: "/workspace/root",
|
||||
status: "closed",
|
||||
updatedAt: null,
|
||||
},
|
||||
{
|
||||
terminalId: "term-4",
|
||||
cwd: "/workspace/exited",
|
||||
status: "exited",
|
||||
updatedAt: "2026-04-15T20:07:00.000Z",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveProjectScriptTerminalId", () => {
|
||||
it("reuses the default shell when no terminal is running", () => {
|
||||
expect(
|
||||
resolveProjectScriptTerminalId({
|
||||
existingTerminalIds: [DEFAULT_TERMINAL_ID],
|
||||
hasRunningTerminal: false,
|
||||
}),
|
||||
).toBe(DEFAULT_TERMINAL_ID);
|
||||
});
|
||||
|
||||
it("opens a new terminal when a shell is already running", () => {
|
||||
expect(
|
||||
resolveProjectScriptTerminalId({
|
||||
existingTerminalIds: [DEFAULT_TERMINAL_ID, "term-2", "term-4"],
|
||||
hasRunningTerminal: true,
|
||||
}),
|
||||
).toBe("term-3");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import type { KnownTerminalSession } from "@t3tools/client-runtime";
|
||||
import { DEFAULT_TERMINAL_ID, type ProjectScript } from "@t3tools/contracts";
|
||||
|
||||
export interface TerminalMenuSession {
|
||||
readonly terminalId: string;
|
||||
readonly cwd: string | null;
|
||||
readonly status: "starting" | "running" | "exited" | "error" | "closed";
|
||||
readonly updatedAt: string | null;
|
||||
}
|
||||
|
||||
export function basename(input: string | null): string | null {
|
||||
if (!input) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalized = input.replace(/\/+$/, "");
|
||||
if (normalized.length === 0) {
|
||||
return "/";
|
||||
}
|
||||
|
||||
const segments = normalized.split("/");
|
||||
return segments[segments.length - 1] ?? normalized;
|
||||
}
|
||||
|
||||
export function getTerminalLabel(terminalId: string): string {
|
||||
if (terminalId === DEFAULT_TERMINAL_ID) {
|
||||
return "Main shell";
|
||||
}
|
||||
|
||||
const numericSuffix = /^term(?:inal)?-(\d+)$/i.exec(terminalId)?.[1];
|
||||
if (numericSuffix) {
|
||||
return `Terminal ${numericSuffix}`;
|
||||
}
|
||||
|
||||
return terminalId;
|
||||
}
|
||||
|
||||
export function getTerminalStatusLabel(input: {
|
||||
readonly status: TerminalMenuSession["status"];
|
||||
readonly hasRunningSubprocess?: boolean;
|
||||
}): string {
|
||||
if (input.status === "running") {
|
||||
return input.hasRunningSubprocess ? "Task running" : "Ready";
|
||||
}
|
||||
if (input.status === "starting") {
|
||||
return "Starting";
|
||||
}
|
||||
if (input.status === "exited") {
|
||||
return "Exited";
|
||||
}
|
||||
if (input.status === "error") {
|
||||
return "Error";
|
||||
}
|
||||
|
||||
return "Not started";
|
||||
}
|
||||
|
||||
export function nextTerminalId(existingTerminalIds: ReadonlyArray<string>): string {
|
||||
const usedIds = new Set(existingTerminalIds);
|
||||
let nextIndex = 2;
|
||||
while (usedIds.has(`term-${nextIndex}`)) {
|
||||
nextIndex += 1;
|
||||
}
|
||||
|
||||
return `term-${nextIndex}`;
|
||||
}
|
||||
|
||||
export function buildTerminalMenuSessions(input: {
|
||||
readonly knownSessions: ReadonlyArray<KnownTerminalSession>;
|
||||
readonly workspaceRoot: string | null;
|
||||
readonly currentSession?: TerminalMenuSession | null;
|
||||
}): ReadonlyArray<TerminalMenuSession> {
|
||||
const sessionsById = new Map<string, TerminalMenuSession>();
|
||||
|
||||
sessionsById.set(DEFAULT_TERMINAL_ID, {
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
cwd: input.workspaceRoot,
|
||||
status: "closed",
|
||||
updatedAt: null,
|
||||
});
|
||||
|
||||
for (const session of input.knownSessions) {
|
||||
if (
|
||||
session.state.status !== "running" &&
|
||||
session.state.status !== "starting" &&
|
||||
session.target.terminalId !== input.currentSession?.terminalId
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
sessionsById.set(session.target.terminalId, {
|
||||
terminalId: session.target.terminalId,
|
||||
cwd: session.state.snapshot?.cwd ?? input.workspaceRoot,
|
||||
status: session.state.status,
|
||||
updatedAt: session.state.updatedAt,
|
||||
});
|
||||
}
|
||||
|
||||
if (input.currentSession && !sessionsById.has(input.currentSession.terminalId)) {
|
||||
sessionsById.set(input.currentSession.terminalId, input.currentSession);
|
||||
}
|
||||
|
||||
return Array.from(sessionsById.values()).sort((left, right) => {
|
||||
if (left.terminalId === DEFAULT_TERMINAL_ID) return -1;
|
||||
if (right.terminalId === DEFAULT_TERMINAL_ID) return 1;
|
||||
|
||||
const leftUpdatedAt = left.updatedAt ? Date.parse(left.updatedAt) : 0;
|
||||
const rightUpdatedAt = right.updatedAt ? Date.parse(right.updatedAt) : 0;
|
||||
if (leftUpdatedAt !== rightUpdatedAt) {
|
||||
return rightUpdatedAt - leftUpdatedAt;
|
||||
}
|
||||
|
||||
return left.terminalId.localeCompare(right.terminalId);
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveProjectScriptTerminalId(input: {
|
||||
readonly existingTerminalIds: ReadonlyArray<string>;
|
||||
readonly hasRunningTerminal: boolean;
|
||||
}): string {
|
||||
if (!input.hasRunningTerminal) {
|
||||
return DEFAULT_TERMINAL_ID;
|
||||
}
|
||||
|
||||
return nextTerminalId(input.existingTerminalIds);
|
||||
}
|
||||
|
||||
export function projectScriptMenuLabel(script: ProjectScript): string {
|
||||
return script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name;
|
||||
}
|
||||
|
||||
export function projectScriptMenuIcon(icon: ProjectScript["icon"]) {
|
||||
if (icon === "test") return "flask";
|
||||
if (icon === "lint") return "checklist";
|
||||
if (icon === "configure") return "wrench.and.screwdriver";
|
||||
if (icon === "build") return "hammer";
|
||||
if (icon === "debug") return "ladybug";
|
||||
return "play";
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
DEFAULT_TERMINAL_FONT_SIZE,
|
||||
MAX_TERMINAL_FONT_SIZE,
|
||||
MIN_TERMINAL_FONT_SIZE,
|
||||
normalizeTerminalFontSize,
|
||||
} from "./terminalPreferences";
|
||||
|
||||
describe("normalizeTerminalFontSize", () => {
|
||||
it("returns the default size for missing or invalid values", () => {
|
||||
expect(normalizeTerminalFontSize(undefined)).toBe(DEFAULT_TERMINAL_FONT_SIZE);
|
||||
expect(normalizeTerminalFontSize(null)).toBe(DEFAULT_TERMINAL_FONT_SIZE);
|
||||
expect(normalizeTerminalFontSize(Number.NaN)).toBe(DEFAULT_TERMINAL_FONT_SIZE);
|
||||
});
|
||||
|
||||
it("clamps below the minimum", () => {
|
||||
expect(normalizeTerminalFontSize(MIN_TERMINAL_FONT_SIZE - 4)).toBe(MIN_TERMINAL_FONT_SIZE);
|
||||
});
|
||||
|
||||
it("clamps above the maximum", () => {
|
||||
expect(normalizeTerminalFontSize(MAX_TERMINAL_FONT_SIZE + 4)).toBe(MAX_TERMINAL_FONT_SIZE);
|
||||
});
|
||||
|
||||
it("preserves in-range values", () => {
|
||||
expect(normalizeTerminalFontSize(9.5)).toBe(9.5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
export const DEFAULT_TERMINAL_FONT_SIZE = 10;
|
||||
export const TERMINAL_FONT_SIZE_STEP = 0.5;
|
||||
export const MIN_TERMINAL_FONT_SIZE = 6;
|
||||
export const MAX_TERMINAL_FONT_SIZE = 14;
|
||||
|
||||
export function normalizeTerminalFontSize(value: number | null | undefined): number {
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) {
|
||||
return DEFAULT_TERMINAL_FONT_SIZE;
|
||||
}
|
||||
|
||||
return Math.min(MAX_TERMINAL_FONT_SIZE, Math.max(MIN_TERMINAL_FONT_SIZE, value));
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
export function resolveTerminalRouteBootstrap(input: {
|
||||
readonly hasThread: boolean;
|
||||
readonly hasWorkspaceRoot: boolean;
|
||||
readonly hasOpened: boolean;
|
||||
readonly requestedTerminalId: string | null;
|
||||
readonly currentTerminalId: string;
|
||||
readonly runningTerminalId: string | null;
|
||||
}):
|
||||
| { readonly kind: "idle" }
|
||||
| { readonly kind: "redirect"; readonly terminalId: string }
|
||||
| { readonly kind: "open" } {
|
||||
if (!input.hasThread || !input.hasWorkspaceRoot || input.hasOpened) {
|
||||
return { kind: "idle" };
|
||||
}
|
||||
|
||||
if (
|
||||
input.requestedTerminalId === null &&
|
||||
input.runningTerminalId !== null &&
|
||||
input.runningTerminalId !== input.currentTerminalId
|
||||
) {
|
||||
return { kind: "redirect", terminalId: input.runningTerminalId };
|
||||
}
|
||||
|
||||
return { kind: "open" };
|
||||
}
|
||||
@@ -25,9 +25,11 @@ import { gitActionManager, showGitActionResult } from "../../state/use-git-actio
|
||||
import { gitBranchManager } from "../../state/use-git-branches";
|
||||
import { gitStatusManager } from "../../state/use-git-status";
|
||||
import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { useSelectedThreadWorktree } from "./use-selected-thread-worktree";
|
||||
|
||||
export function useSelectedThreadGitActions() {
|
||||
const { selectedThread, selectedThreadProject } = useThreadSelection();
|
||||
const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree();
|
||||
|
||||
const selectedThreadGitRootCwd = selectedThreadProject?.workspaceRoot ?? null;
|
||||
|
||||
@@ -61,8 +63,7 @@ export function useSelectedThreadGitActions() {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cwd =
|
||||
options?.cwd ?? selectedThread.worktreePath ?? selectedThreadProject.workspaceRoot;
|
||||
const cwd = options?.cwd ?? selectedThreadCwd;
|
||||
if (!cwd) {
|
||||
return null;
|
||||
}
|
||||
@@ -86,7 +87,7 @@ export function useSelectedThreadGitActions() {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
[selectedThread, selectedThreadProject],
|
||||
[selectedThread, selectedThreadCwd, selectedThreadProject],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -109,7 +110,7 @@ export function useSelectedThreadGitActions() {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cwd = selectedThread.worktreePath ?? selectedThreadProject.workspaceRoot;
|
||||
const cwd = selectedThreadCwd;
|
||||
if (!cwd) {
|
||||
return null;
|
||||
}
|
||||
@@ -128,7 +129,7 @@ export function useSelectedThreadGitActions() {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
[selectedThread, selectedThreadProject],
|
||||
[selectedThread, selectedThreadCwd, selectedThreadProject],
|
||||
);
|
||||
|
||||
const refreshSelectedThreadBranches = useCallback(async (): Promise<ReadonlyArray<GitBranch>> => {
|
||||
@@ -204,12 +205,12 @@ export function useSelectedThreadGitActions() {
|
||||
cwd,
|
||||
nextThreadState: {
|
||||
branch: result?.branch ?? thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
worktreePath: selectedThreadWorktreePath,
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
[runSelectedThreadGitMutation, syncSelectedThreadBranchState],
|
||||
[runSelectedThreadGitMutation, selectedThreadWorktreePath, syncSelectedThreadBranchState],
|
||||
);
|
||||
|
||||
const onCreateSelectedThreadBranch = useCallback(
|
||||
@@ -227,12 +228,12 @@ export function useSelectedThreadGitActions() {
|
||||
cwd,
|
||||
nextThreadState: {
|
||||
branch: result?.branch ?? thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
worktreePath: selectedThreadWorktreePath,
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
[runSelectedThreadGitMutation, syncSelectedThreadBranchState],
|
||||
[runSelectedThreadGitMutation, selectedThreadWorktreePath, syncSelectedThreadBranchState],
|
||||
);
|
||||
|
||||
const onCreateSelectedThreadWorktree = useCallback(
|
||||
@@ -316,7 +317,7 @@ export function useSelectedThreadGitActions() {
|
||||
cwd,
|
||||
nextThreadState: {
|
||||
branch: result.branch.name,
|
||||
worktreePath: thread.worktreePath,
|
||||
worktreePath: selectedThreadWorktreePath,
|
||||
},
|
||||
});
|
||||
return result;
|
||||
@@ -326,7 +327,12 @@ export function useSelectedThreadGitActions() {
|
||||
return result;
|
||||
});
|
||||
},
|
||||
[refreshSelectedThreadGitStatus, runSelectedThreadGitMutation, syncSelectedThreadBranchState],
|
||||
[
|
||||
refreshSelectedThreadGitStatus,
|
||||
runSelectedThreadGitMutation,
|
||||
selectedThreadWorktreePath,
|
||||
syncSelectedThreadBranchState,
|
||||
],
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -5,20 +5,18 @@ import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
|
||||
import { useGitActionState } from "../../state/use-git-action-state";
|
||||
import { useGitBranches } from "../../state/use-git-branches";
|
||||
import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { useSelectedThreadWorktree } from "./use-selected-thread-worktree";
|
||||
|
||||
export function useSelectedThreadGitState() {
|
||||
const { selectedThread, selectedThreadProject } = useThreadSelection();
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
|
||||
const selectedThreadGitTarget = useMemo(
|
||||
() => ({
|
||||
environmentId: selectedThread?.environmentId ?? null,
|
||||
cwd: selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
|
||||
cwd: selectedThreadCwd,
|
||||
}),
|
||||
[
|
||||
selectedThread?.environmentId,
|
||||
selectedThread?.worktreePath,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
],
|
||||
[selectedThread?.environmentId, selectedThreadCwd],
|
||||
);
|
||||
const gitActionState = useGitActionState(selectedThreadGitTarget);
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { resolvePreferredThreadWorktreePath } from "./terminalLaunchContext";
|
||||
|
||||
export function useSelectedThreadWorktree() {
|
||||
const { selectedThread, selectedThreadProject } = useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
|
||||
const selectedThreadWorktreePath = useMemo(
|
||||
() =>
|
||||
resolvePreferredThreadWorktreePath({
|
||||
threadShellWorktreePath: selectedThread?.worktreePath ?? null,
|
||||
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
|
||||
}),
|
||||
[selectedThread?.worktreePath, selectedThreadDetail?.worktreePath],
|
||||
);
|
||||
|
||||
return {
|
||||
selectedThreadWorktreePath,
|
||||
selectedThreadCwd: selectedThreadWorktreePath ?? selectedThreadProject?.workspaceRoot ?? null,
|
||||
};
|
||||
}
|
||||
@@ -29,6 +29,18 @@ export function buildThreadReviewRoutePath(
|
||||
return `${buildThreadRoutePath(input)}/review`;
|
||||
}
|
||||
|
||||
export function buildThreadTerminalRoutePath(
|
||||
input: ThreadRouteInput | PlainThreadRouteInput,
|
||||
terminalId?: string | null,
|
||||
): string {
|
||||
const basePath = `${buildThreadRoutePath(input)}/terminal`;
|
||||
if (!terminalId) {
|
||||
return basePath;
|
||||
}
|
||||
|
||||
return `${basePath}?terminalId=${encodeURIComponent(terminalId)}`;
|
||||
}
|
||||
|
||||
export function dismissRoute(router: Router) {
|
||||
if (router.canGoBack()) {
|
||||
router.back();
|
||||
|
||||
@@ -5,6 +5,11 @@ import * as SecureStore from "expo-secure-store";
|
||||
import type { SavedRemoteConnection } from "./connection";
|
||||
|
||||
const CONNECTIONS_KEY = "t3code.connections";
|
||||
const PREFERENCES_KEY = "t3code.preferences";
|
||||
|
||||
export interface MobilePreferences {
|
||||
readonly terminalFontSize?: number;
|
||||
}
|
||||
|
||||
async function readStorageItem(key: string): Promise<string | null> {
|
||||
return await SecureStore.getItemAsync(key);
|
||||
@@ -14,23 +19,31 @@ async function writeStorageItem(key: string, value: string): Promise<void> {
|
||||
await SecureStore.setItemAsync(key, value);
|
||||
}
|
||||
|
||||
export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteConnection>> {
|
||||
const raw = (await readStorageItem(CONNECTIONS_KEY)) ?? "";
|
||||
async function readJsonStorageItem<T>(key: string): Promise<T | null> {
|
||||
const raw = (await readStorageItem(key)) ?? "";
|
||||
if (!raw.trim()) {
|
||||
return [];
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as {
|
||||
readonly connections?: ReadonlyArray<SavedRemoteConnection>;
|
||||
};
|
||||
return pipe(
|
||||
parsed.connections ?? [],
|
||||
Arr.filter((c) => !!c.environmentId && !!c.bearerToken?.trim()),
|
||||
);
|
||||
return JSON.parse(raw) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadSavedConnections(): Promise<ReadonlyArray<SavedRemoteConnection>> {
|
||||
const parsed = await readJsonStorageItem<{
|
||||
readonly connections?: ReadonlyArray<SavedRemoteConnection>;
|
||||
}>(CONNECTIONS_KEY);
|
||||
if (!parsed) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return pipe(
|
||||
parsed.connections ?? [],
|
||||
Arr.filter((c) => !!c.environmentId && !!c.bearerToken?.trim()),
|
||||
);
|
||||
}
|
||||
|
||||
export async function saveConnection(connection: SavedRemoteConnection): Promise<void> {
|
||||
@@ -53,3 +66,28 @@ export async function clearSavedConnection(environmentId: string): Promise<void>
|
||||
);
|
||||
await writeStorageItem(CONNECTIONS_KEY, JSON.stringify({ connections: next }));
|
||||
}
|
||||
|
||||
export async function loadPreferences(): Promise<MobilePreferences> {
|
||||
const parsed = await readJsonStorageItem<MobilePreferences>(PREFERENCES_KEY);
|
||||
if (!parsed || typeof parsed !== "object") {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (typeof parsed.terminalFontSize === "number") {
|
||||
return { terminalFontSize: parsed.terminalFontSize };
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
export async function savePreferencesPatch(
|
||||
patch: Partial<MobilePreferences>,
|
||||
): Promise<MobilePreferences> {
|
||||
const current = await loadPreferences();
|
||||
const next: MobilePreferences = {
|
||||
...current,
|
||||
...patch,
|
||||
};
|
||||
await writeStorageItem(PREFERENCES_KEY, JSON.stringify(next));
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import { memo, useCallback } from "react";
|
||||
import {
|
||||
Pressable,
|
||||
ScrollView,
|
||||
TextInput,
|
||||
View,
|
||||
type LayoutChangeEvent,
|
||||
type NativeSyntheticEvent,
|
||||
type ViewProps,
|
||||
useColorScheme,
|
||||
} from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { resolveNativeTerminalSurfaceView } from "./nativeTerminalModule";
|
||||
import {
|
||||
buildGhosttyThemeConfig,
|
||||
getGitHubTerminalTheme,
|
||||
type TerminalTheme,
|
||||
} from "./terminalTheme";
|
||||
|
||||
interface TerminalInputEvent {
|
||||
readonly data: string;
|
||||
}
|
||||
|
||||
interface TerminalResizeEvent {
|
||||
readonly cols: number;
|
||||
readonly rows: number;
|
||||
}
|
||||
|
||||
interface TerminalSurfaceProps extends ViewProps {
|
||||
readonly terminalKey: string;
|
||||
readonly buffer: string;
|
||||
readonly fontSize?: number;
|
||||
readonly isRunning: boolean;
|
||||
readonly theme?: TerminalTheme;
|
||||
readonly onInput: (data: string) => void;
|
||||
readonly onResize: (size: { readonly cols: number; readonly rows: number }) => void;
|
||||
}
|
||||
|
||||
function estimateGridSize(input: {
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
readonly fontSize: number;
|
||||
}): { readonly cols: number; readonly rows: number } {
|
||||
const cellWidth = input.fontSize * 0.62;
|
||||
const cellHeight = input.fontSize * 1.35;
|
||||
return {
|
||||
cols: Math.max(20, Math.min(400, Math.floor(input.width / cellWidth))),
|
||||
rows: Math.max(5, Math.min(200, Math.floor(input.height / cellHeight))),
|
||||
};
|
||||
}
|
||||
|
||||
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 statusLabel = props.isRunning
|
||||
? "Native terminal unavailable. Using text fallback."
|
||||
: "Open terminal to start a shell.";
|
||||
|
||||
const handleLayout = (event: LayoutChangeEvent) => {
|
||||
const { width, height } = event.nativeEvent.layout;
|
||||
props.onResize(estimateGridSize({ width, height, fontSize }));
|
||||
};
|
||||
|
||||
return (
|
||||
<View
|
||||
style={[
|
||||
{
|
||||
flex: 1,
|
||||
backgroundColor: theme.background,
|
||||
borderRadius: 8,
|
||||
overflow: "hidden",
|
||||
},
|
||||
props.style,
|
||||
]}
|
||||
onLayout={handleLayout}
|
||||
>
|
||||
<View style={{ flex: 1, paddingHorizontal: 10, paddingVertical: 8 }}>
|
||||
<Text
|
||||
style={{
|
||||
color: theme.mutedForeground,
|
||||
fontSize: 11,
|
||||
paddingBottom: 8,
|
||||
}}
|
||||
>
|
||||
{statusLabel}
|
||||
</Text>
|
||||
<ScrollView
|
||||
style={{ flex: 1 }}
|
||||
contentContainerStyle={{ paddingBottom: 12 }}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
<Text
|
||||
selectable
|
||||
style={{
|
||||
color: theme.foreground,
|
||||
fontFamily: "Menlo",
|
||||
fontSize,
|
||||
lineHeight: Math.round(fontSize * 1.35),
|
||||
}}
|
||||
>
|
||||
{props.buffer || "$ "}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
</View>
|
||||
<View
|
||||
style={{
|
||||
borderTopWidth: 1,
|
||||
borderTopColor: theme.border,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
padding: 8,
|
||||
}}
|
||||
>
|
||||
<TextInput
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
blurOnSubmit={false}
|
||||
editable={props.isRunning}
|
||||
placeholder="type and press return"
|
||||
placeholderTextColor={theme.mutedForeground}
|
||||
returnKeyType="send"
|
||||
style={{
|
||||
color: theme.foreground,
|
||||
flex: 1,
|
||||
fontFamily: "Menlo",
|
||||
fontSize: 13,
|
||||
padding: 0,
|
||||
}}
|
||||
onSubmitEditing={(event) => {
|
||||
const text = event.nativeEvent.text;
|
||||
if (text.length > 0) {
|
||||
props.onInput(`${text}\n`);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Pressable
|
||||
disabled={!props.isRunning}
|
||||
style={({ pressed }) => ({
|
||||
opacity: !props.isRunning ? 0.35 : pressed ? 0.65 : 1,
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 6,
|
||||
borderRadius: 8,
|
||||
backgroundColor: theme.border,
|
||||
})}
|
||||
onPress={() => props.onInput("\u0003")}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
color: theme.foreground,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 11,
|
||||
}}
|
||||
>
|
||||
Ctrl-C
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
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 { onInput, onResize } = props;
|
||||
const NativeTerminalSurfaceView = resolveNativeTerminalSurfaceView();
|
||||
const handleNativeInput = useCallback(
|
||||
(event: NativeSyntheticEvent<TerminalInputEvent>) => {
|
||||
onInput(event.nativeEvent.data);
|
||||
},
|
||||
[onInput],
|
||||
);
|
||||
const handleNativeResize = useCallback(
|
||||
(event: NativeSyntheticEvent<TerminalResizeEvent>) => {
|
||||
onResize({
|
||||
cols: event.nativeEvent.cols,
|
||||
rows: event.nativeEvent.rows,
|
||||
});
|
||||
},
|
||||
[onResize],
|
||||
);
|
||||
|
||||
if (NativeTerminalSurfaceView) {
|
||||
return (
|
||||
<NativeTerminalSurfaceView
|
||||
{...props}
|
||||
appearanceScheme={appearanceScheme}
|
||||
backgroundColor={theme.background}
|
||||
foregroundColor={theme.foreground}
|
||||
mutedForegroundColor={theme.mutedForeground}
|
||||
terminalKey={props.terminalKey}
|
||||
initialBuffer={props.buffer}
|
||||
fontSize={fontSize}
|
||||
themeConfig={buildGhosttyThemeConfig(theme)}
|
||||
onInput={handleNativeInput}
|
||||
onResize={handleNativeResize}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <FallbackTerminalSurface {...props} fontSize={fontSize} theme={theme} />;
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const expoModulesCoreMocks = vi.hoisted(() => ({
|
||||
requireNativeViewManager: vi.fn(),
|
||||
}));
|
||||
const nativeView = () => null;
|
||||
const originalExpo = globalThis.expo;
|
||||
|
||||
function setExpoViewConfigAvailable() {
|
||||
globalThis.expo = {
|
||||
getViewConfig: vi.fn().mockReturnValue({ validAttributes: {}, directEventTypes: {} }),
|
||||
} as unknown as typeof globalThis.expo;
|
||||
}
|
||||
|
||||
vi.mock("expo-modules-core", () => ({
|
||||
requireNativeViewManager: expoModulesCoreMocks.requireNativeViewManager,
|
||||
}));
|
||||
|
||||
describe("resolveNativeTerminalSurfaceView", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.resetModules();
|
||||
globalThis.expo = undefined as unknown as typeof globalThis.expo;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.expo = originalExpo;
|
||||
});
|
||||
|
||||
it("returns null when the native terminal view config is unavailable", async () => {
|
||||
const { resolveNativeTerminalSurfaceView } = await import("./nativeTerminalModule");
|
||||
expect(resolveNativeTerminalSurfaceView()).toBeNull();
|
||||
expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns the native terminal view when the view config is installed", async () => {
|
||||
setExpoViewConfigAvailable();
|
||||
expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);
|
||||
const { resolveNativeTerminalSurfaceView } = await import("./nativeTerminalModule");
|
||||
expect(resolveNativeTerminalSurfaceView()).toBe(nativeView);
|
||||
expect(expoModulesCoreMocks.requireNativeViewManager).toHaveBeenCalledWith("T3TerminalSurface");
|
||||
});
|
||||
|
||||
it("returns null when the view manager cannot be required", async () => {
|
||||
setExpoViewConfigAvailable();
|
||||
expoModulesCoreMocks.requireNativeViewManager.mockImplementation(() => {
|
||||
throw new Error("boom");
|
||||
});
|
||||
const { resolveNativeTerminalSurfaceView } = await import("./nativeTerminalModule");
|
||||
expect(resolveNativeTerminalSurfaceView()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { ComponentType } from "react";
|
||||
import type { NativeSyntheticEvent, ViewProps } from "react-native";
|
||||
import { requireNativeViewManager } from "expo-modules-core";
|
||||
|
||||
const NATIVE_TERMINAL_MODULE_NAME = "T3TerminalSurface";
|
||||
|
||||
interface ExpoGlobalWithViewConfig {
|
||||
readonly expo?: {
|
||||
getViewConfig?: (moduleName: string, viewName?: string) => unknown;
|
||||
};
|
||||
}
|
||||
|
||||
interface TerminalInputEvent {
|
||||
readonly data: string;
|
||||
}
|
||||
|
||||
interface TerminalResizeEvent {
|
||||
readonly cols: number;
|
||||
readonly rows: number;
|
||||
}
|
||||
|
||||
export interface NativeTerminalSurfaceProps extends ViewProps {
|
||||
readonly appearanceScheme?: "light" | "dark";
|
||||
readonly themeConfig?: string;
|
||||
readonly backgroundColor?: string;
|
||||
readonly foregroundColor?: string;
|
||||
readonly mutedForegroundColor?: string;
|
||||
readonly terminalKey: string;
|
||||
readonly initialBuffer: string;
|
||||
readonly fontSize: number;
|
||||
readonly onInput?: (event: NativeSyntheticEvent<TerminalInputEvent>) => void;
|
||||
readonly onResize?: (event: NativeSyntheticEvent<TerminalResizeEvent>) => void;
|
||||
}
|
||||
|
||||
let cachedNativeTerminalSurfaceView: ComponentType<NativeTerminalSurfaceProps> | undefined;
|
||||
|
||||
function getExpoViewConfig(moduleName: string) {
|
||||
return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
|
||||
moduleName,
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveNativeTerminalSurfaceView(): ComponentType<NativeTerminalSurfaceProps> | null {
|
||||
if (cachedNativeTerminalSurfaceView) {
|
||||
return cachedNativeTerminalSurfaceView;
|
||||
}
|
||||
|
||||
if (getExpoViewConfig(NATIVE_TERMINAL_MODULE_NAME) == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
cachedNativeTerminalSurfaceView = requireNativeViewManager<NativeTerminalSurfaceProps>(
|
||||
NATIVE_TERMINAL_MODULE_NAME,
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
return cachedNativeTerminalSurfaceView ?? null;
|
||||
}
|
||||
|
||||
export function hasNativeTerminalSurface() {
|
||||
return resolveNativeTerminalSurfaceView() !== null;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildGhosttyThemeConfig, getGitHubTerminalTheme } from "./terminalTheme";
|
||||
|
||||
describe("getGitHubTerminalTheme", () => {
|
||||
it("returns the GitHub light terminal palette", () => {
|
||||
expect(getGitHubTerminalTheme("light")).toMatchObject({
|
||||
background: "#ffffff",
|
||||
foreground: "#586069",
|
||||
cursorForeground: "#005cc5",
|
||||
cursorBackground: "#d1d5da",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns the GitHub dark terminal palette", () => {
|
||||
expect(getGitHubTerminalTheme("dark")).toMatchObject({
|
||||
background: "#24292e",
|
||||
foreground: "#d1d5da",
|
||||
cursorForeground: "#79b8ff",
|
||||
cursorBackground: "#586069",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildGhosttyThemeConfig", () => {
|
||||
it("serializes theme colors into a ghostty config file", () => {
|
||||
const config = buildGhosttyThemeConfig(getGitHubTerminalTheme("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.endsWith("\n")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
export type TerminalAppearanceScheme = "light" | "dark";
|
||||
|
||||
export interface TerminalTheme {
|
||||
readonly background: string;
|
||||
readonly foreground: string;
|
||||
readonly mutedForeground: string;
|
||||
readonly border: string;
|
||||
readonly cursorForeground: string;
|
||||
readonly cursorBackground: string;
|
||||
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",
|
||||
palette: [
|
||||
"#24292e",
|
||||
"#d73a49",
|
||||
"#28a745",
|
||||
"#dbab09",
|
||||
"#0366d6",
|
||||
"#5a32a3",
|
||||
"#1b7c83",
|
||||
"#6a737d",
|
||||
"#959da5",
|
||||
"#cb2431",
|
||||
"#22863a",
|
||||
"#b08800",
|
||||
"#005cc5",
|
||||
"#5a32a3",
|
||||
"#3192aa",
|
||||
"#d1d5da",
|
||||
],
|
||||
};
|
||||
|
||||
const GITHUB_DARK_THEME: TerminalTheme = {
|
||||
background: "#24292e",
|
||||
foreground: "#d1d5da",
|
||||
mutedForeground: "#959da5",
|
||||
border: "rgba(240,246,252,0.12)",
|
||||
cursorForeground: "#79b8ff",
|
||||
cursorBackground: "#586069",
|
||||
palette: [
|
||||
"#586069",
|
||||
"#ea4a5a",
|
||||
"#34d058",
|
||||
"#ffea7f",
|
||||
"#2188ff",
|
||||
"#b392f0",
|
||||
"#39c5cf",
|
||||
"#d1d5da",
|
||||
"#959da5",
|
||||
"#f97583",
|
||||
"#85e89d",
|
||||
"#ffea7f",
|
||||
"#79b8ff",
|
||||
"#b392f0",
|
||||
"#56d4dd",
|
||||
"#fafbfc",
|
||||
],
|
||||
};
|
||||
|
||||
export function getGitHubTerminalTheme(scheme: TerminalAppearanceScheme): TerminalTheme {
|
||||
return scheme === "light" ? GITHUB_LIGHT_THEME : GITHUB_DARK_THEME;
|
||||
}
|
||||
|
||||
export function buildGhosttyThemeConfig(theme: TerminalTheme): string {
|
||||
const lines = [
|
||||
`background = ${theme.background}`,
|
||||
`foreground = ${theme.foreground}`,
|
||||
`cursor-color = ${theme.cursorForeground}`,
|
||||
`cursor-text = ${theme.cursorBackground}`,
|
||||
];
|
||||
|
||||
for (const [index, color] of theme.palette.entries()) {
|
||||
lines.push(`palette = ${index}=${color}`);
|
||||
}
|
||||
|
||||
return `${lines.join("\n")}\n`;
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import { appAtomRegistry } from "./atom-registry";
|
||||
import { type ConnectedEnvironmentSummary, type EnvironmentSession } from "./remote-runtime-types";
|
||||
import { environmentRuntimeManager, useEnvironmentRuntimeStates } from "./use-environment-runtime";
|
||||
import { shellSnapshotManager } from "./use-shell-snapshot";
|
||||
import { terminalSessionManager } from "./use-terminal-session";
|
||||
|
||||
const environmentSessions = new Map<string, EnvironmentSession>();
|
||||
const environmentConnectionListeners = new Set<() => void>();
|
||||
@@ -154,6 +155,7 @@ export async function disconnectEnvironment(
|
||||
notifyEnvironmentConnectionListeners();
|
||||
await session?.connection.dispose();
|
||||
shellSnapshotManager.invalidate({ environmentId });
|
||||
terminalSessionManager.invalidateEnvironment(environmentId);
|
||||
environmentRuntimeManager.invalidate({ environmentId });
|
||||
|
||||
if (options?.removeSaved) {
|
||||
@@ -244,7 +246,9 @@ export async function connectSavedEnvironment(
|
||||
onShellResubscribe: (environmentId) => {
|
||||
shellSnapshotManager.markPending({ environmentId });
|
||||
},
|
||||
applyTerminalEvent: () => undefined,
|
||||
applyTerminalEvent: (event, environmentId) => {
|
||||
terminalSessionManager.applyEvent({ environmentId }, event);
|
||||
},
|
||||
onConfigSnapshot: (serverConfig) => {
|
||||
environmentRuntimeManager.patch({ environmentId: connection.environmentId }, (runtime) => ({
|
||||
...runtime,
|
||||
@@ -333,6 +337,7 @@ export function useRemoteEnvironmentBootstrap() {
|
||||
environmentSessions.clear();
|
||||
environmentRuntimeManager.invalidate();
|
||||
shellSnapshotManager.invalidate();
|
||||
terminalSessionManager.invalidate();
|
||||
notifyEnvironmentConnectionListeners();
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
createTerminalSessionManager,
|
||||
EMPTY_TERMINAL_SESSION_ATOM,
|
||||
EMPTY_TERMINAL_SESSION_STATE,
|
||||
getTerminalSessionTargetKey,
|
||||
knownTerminalSessionsAtom,
|
||||
terminalSessionStateAtom,
|
||||
type TerminalSessionState,
|
||||
} from "@t3tools/client-runtime";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
|
||||
export const terminalSessionManager = createTerminalSessionManager({
|
||||
getRegistry: () => appAtomRegistry,
|
||||
});
|
||||
|
||||
export function useTerminalSession(input: {
|
||||
readonly environmentId: string | null;
|
||||
readonly threadId: string | null;
|
||||
readonly terminalId: string | null;
|
||||
}): TerminalSessionState {
|
||||
const targetKey = getTerminalSessionTargetKey(input);
|
||||
const state = useAtomValue(
|
||||
targetKey !== null ? terminalSessionStateAtom(targetKey) : EMPTY_TERMINAL_SESSION_ATOM,
|
||||
);
|
||||
return targetKey === null ? EMPTY_TERMINAL_SESSION_STATE : state;
|
||||
}
|
||||
|
||||
export function useTerminalSessionTarget(input: {
|
||||
readonly environmentId: string | null;
|
||||
readonly threadId: string | null;
|
||||
readonly terminalId: string | null;
|
||||
}) {
|
||||
return useMemo(
|
||||
() => ({
|
||||
environmentId: input.environmentId,
|
||||
threadId: input.threadId,
|
||||
terminalId: input.terminalId,
|
||||
}),
|
||||
[input.environmentId, input.threadId, input.terminalId],
|
||||
);
|
||||
}
|
||||
|
||||
export function useKnownTerminalSessions(input: {
|
||||
readonly environmentId: string | null;
|
||||
readonly threadId: string | null;
|
||||
}) {
|
||||
const knownSessionsIndex = useAtomValue(knownTerminalSessionsAtom);
|
||||
|
||||
return useMemo(() => {
|
||||
if (input.environmentId === null || input.threadId === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
void knownSessionsIndex;
|
||||
return terminalSessionManager.listSessions({
|
||||
environmentId: input.environmentId,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
}, [input.environmentId, input.threadId, knownSessionsIndex]);
|
||||
}
|
||||
Reference in new issue
Block a user