Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 58 additions & 19 deletions apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { StackActions, useNavigation, type StaticScreenProps } from "@react-navi
import { useAtomMount } from "@effect/atom-react";
import { useMemo, useRef, useState, useSyncExternalStore } from "react";
import { Platform, Pressable, View } from "react-native";
import Animated, { useAnimatedStyle } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/ui/AppText";
import { TerminalContextSheet } from "./TerminalContextSheet";
Expand All @@ -27,6 +28,7 @@ import {
KeyboardController,
KeyboardStickyView,
useKeyboardState,
useReanimatedKeyboardAnimation,
} from "react-native-keyboard-controller";

import {
Expand Down Expand Up @@ -445,6 +447,7 @@ function ThreadTerminal(props: {
terminalId,
},
gridSize: initialAttachGridSize,
resizeSettleDelayMs: Platform.OS === "android" ? 120 : 0,
initialInput: pendingLaunch?.initialInput,
canOperate: () =>
readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope),
Expand Down Expand Up @@ -586,6 +589,24 @@ function ThreadTerminal(props: {
const terminalBottomInset =
(isKeyboardVisible ? keyboardHeight : 0) + (isAccessoryVisible ? TERMINAL_ACCESSORY_HEIGHT : 0);

const [androidBottomBarHeight, setAndroidBottomBarHeight] = useState(56);
const { height: animatedKeyboardHeight, progress: keyboardProgress } =
useReanimatedKeyboardAnimation();
const androidViewportStyle = useAnimatedStyle(() => ({
paddingBottom:
-animatedKeyboardHeight.value +
keyboardProgress.value * (canOperateTerminal ? TERMINAL_ACCESSORY_HEIGHT : 0) +
(1 - keyboardProgress.value) * (androidBottomBarHeight + insets.bottom),
}));
const androidBottomBarStyle = useAnimatedStyle(() => ({
display: keyboardProgress.value === 1 ? "none" : "flex",
opacity: 1 - keyboardProgress.value,
}));
const androidAccessoryStyle = useAnimatedStyle(() => ({
display: keyboardProgress.value === 0 ? "none" : "flex",
opacity: keyboardProgress.value,
}));

const terminalMenuSessions: ReadonlyArray<TerminalMenuSession> = buildTerminalMenuSessions({
knownSessions: knownSessions ?? [],
workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
Expand Down Expand Up @@ -841,7 +862,6 @@ function ThreadTerminal(props: {
: terminalTheme.background,
// Measured top reservation is zero when UIKit already inset the body or moved the bar.
paddingTop: contentTopInset,
paddingBottom: Platform.OS === "android" && !isKeyboardVisible ? insets.bottom : 0,
}}
>
{!isEnvironmentReady ? (
Expand Down Expand Up @@ -897,11 +917,13 @@ function ThreadTerminal(props: {
<EmptyState title="Terminal unavailable" detail={terminal.error} />
) : (
<>
<View
style={{
flex: 1,
paddingBottom: terminalBottomInset,
}}
<Animated.View
style={[
{ flex: 1 },
Platform.OS === "android"
? androidViewportStyle
: { paddingBottom: terminalBottomInset },
]}
>
<View
pointerEvents="none"
Expand Down Expand Up @@ -935,10 +957,22 @@ function ThreadTerminal(props: {
terminalKey={terminalKey}
theme={terminalTheme}
/>
</View>
</Animated.View>

{Platform.OS === "android" && !isKeyboardVisible ? (
<View className="min-h-14 flex-row items-center gap-2 bg-card-alt px-2">
{Platform.OS === "android" ? (
<Animated.View
className="min-h-14 flex-row items-center gap-2 bg-card-alt px-2"
onLayout={(event) => {
const height = event.nativeEvent.layout.height;
if (height > 0) setAndroidBottomBarHeight(height);
}}
pointerEvents={isKeyboardVisible ? "none" : "auto"}
importantForAccessibility={isKeyboardVisible ? "no-hide-descendants" : "auto"}
style={[
{ position: "absolute", bottom: insets.bottom, left: 0, right: 0 },
androidBottomBarStyle,
]}
>
{hasNativeTerminalSurface() ? (
<Button label="Attach output" tone="text" onPress={requestCapture} />
) : null}
Expand All @@ -949,8 +983,8 @@ function ThreadTerminal(props: {
icon="keyboard"
onPress={handleShowKeyboard}
/>
</View>
) : Platform.OS !== "android" && hasNativeTerminalSurface() ? (
</Animated.View>
) : hasNativeTerminalSurface() ? (
<Pressable
accessibilityRole="button"
onPress={() => {
Expand All @@ -969,18 +1003,23 @@ function ThreadTerminal(props: {
<Text style={{ color: terminalTheme.foreground }}>Attach visible output</Text>
</Pressable>
) : null}
{isAccessoryVisible ? (
{(Platform.OS === "android" ? canOperateTerminal : isAccessoryVisible) ? (
<KeyboardStickyView
pointerEvents={isKeyboardVisible ? "auto" : "none"}
importantForAccessibility={isKeyboardVisible ? "auto" : "no-hide-descendants"}
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<View
<Animated.View
className="border-t"
style={{
backgroundColor: terminalTheme.background,
borderTopColor: terminalTheme.border,
minHeight: TERMINAL_ACCESSORY_HEIGHT,
}}
style={[
{
backgroundColor: terminalTheme.background,
borderTopColor: terminalTheme.border,
minHeight: TERMINAL_ACCESSORY_HEIGHT,
},
Platform.OS === "android" ? androidAccessoryStyle : undefined,
]}
>
<ComposerToolbarRow paddingBottom={4} paddingHorizontal={8} paddingTop={4}>
<ComposerToolbarScroller
Expand Down Expand Up @@ -1023,7 +1062,7 @@ function ThreadTerminal(props: {
showChevron={false}
/>
</ComposerToolbarRow>
</View>
</Animated.View>
</KeyboardStickyView>
) : canOperateTerminal && !isKeyboardVisible && Platform.OS !== "android" ? (
<Pressable
Expand Down
59 changes: 57 additions & 2 deletions packages/client-runtime/src/state/terminal.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
import { expect, it } from "vite-plus/test";
import { expect, it, vi } from "vite-plus/test";

import {
createTerminalSession,
Expand Down Expand Up @@ -59,7 +59,9 @@ it("leaves the history a viewer was reading when operate is granted", () => {
const environmentId = EnvironmentId.make("environment");
const threadId = ThreadId.make("thread");

function setup(options: { readonly initialInput?: string } = {}) {
function setup(
options: { readonly initialInput?: string; readonly resizeSettleDelayMs?: number } = {},
) {
// Tests flush the registry's scheduled work to control when driver finalizers run.
const scheduled: Array<() => void> = [];
const registry = AtomRegistry.make({
Expand Down Expand Up @@ -101,6 +103,7 @@ function setup(options: { readonly initialInput?: string } = {}) {
target: { environmentId, threadId, terminalId: "term-1" },
gridSize: { cols: 120, rows: 40 },
initialInput: options.initialInput,
resizeSettleDelayMs: options.resizeSettleDelayMs,
canOperate: () => access.canOperate,
onExit: () => exits.push(true),
onLiveChange: (value) => live.push(value),
Expand Down Expand Up @@ -154,6 +157,58 @@ it("replays the measured grid on every new attachment generation", () => {
]);
});

it("sends only the settled grid and still resizes before launch input", () => {
vi.useFakeTimers();
try {
const { session, attached, emit, mount, calls, of } = setup({
initialInput: "top\r",
resizeSettleDelayMs: 120,
});
mount(attached);
emit({ status: "running", version: 1 });
expect(calls.map((call) => call.command)).toEqual(["resize", "write"]);
session.reportGridSize({ cols: 100, rows: 30 });
vi.advanceTimersByTime(100);
session.reportGridSize({ cols: 100, rows: 20 });
vi.advanceTimersByTime(119);
expect(of("resize")).toHaveLength(1);
vi.advanceTimersByTime(1);
expect(of("resize")).toEqual([
{ threadId, terminalId: "term-1", cols: 120, rows: 40 },
{ threadId, terminalId: "term-1", cols: 100, rows: 20 },
]);
} finally {
vi.useRealTimers();
}
});

it("cancels pending grids on detach or generation change and checks current permission", () => {
vi.useFakeTimers();
try {
const { session, attached, emit, mount, access, flush, of } = setup({
resizeSettleDelayMs: 120,
});
const unmount = mount(attached);
emit({ status: "running", version: 1 });
session.reportGridSize({ cols: 100, rows: 30 });
access.canOperate = false;
vi.advanceTimersByTime(120);
expect(of("resize")).toHaveLength(1);
access.canOperate = true;
session.reportGridSize({ cols: 100, rows: 20 });
emit({ status: "running", version: 2, generation: 2 });
vi.advanceTimersByTime(120);
expect(of("resize")).toHaveLength(2);
session.reportGridSize({ cols: 100, rows: 40 });
unmount();
flush();
vi.advanceTimersByTime(120);
expect(of("resize")).toHaveLength(2);
} finally {
vi.useRealTimers();
}
});

it("writes the launch's initial input once the first snapshot lands", () => {
const { attached, emit, mount, calls, of } = setup({ initialInput: "pnpm dev\r" });
mount(attached);
Expand Down
16 changes: 15 additions & 1 deletion packages/client-runtime/src/state/terminal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ export interface TerminalSessionOptions {
readonly terminalId: string;
};
readonly gridSize: TerminalGridSize;
readonly resizeSettleDelayMs?: number | undefined;
/** Written once, as soon as the first attachment snapshot lands. */
readonly initialInput?: string | undefined;
/** Read right before every command, so revoking operate stops them at once. */
Expand Down Expand Up @@ -262,8 +263,11 @@ export function createTerminalSession(
let lastStatus: TerminalBufferState["status"] | null = null;
let loggedFirstOutput = false;
let resizeRegistry: AtomRegistry.AtomRegistry | null = null;
let pendingResize: ReturnType<typeof setTimeout> | undefined;

const sendResize = () => {
clearTimeout(pendingResize);
pendingResize = undefined;
if (generation === null || resizeRegistry === null || !options.canOperate()) return;
void runAtomCommand(resizeRegistry, atoms.resize, {
environmentId,
Expand Down Expand Up @@ -385,6 +389,9 @@ export function createTerminalSession(
Atom.make((get) => {
const registry = get.registry;
get.addFinalizer(() => {
clearTimeout(pendingResize);
pendingResize = undefined;
resizeRegistry = null;
generation = null;
lastStatus = null;
setLive(null);
Expand All @@ -411,7 +418,14 @@ export function createTerminalSession(
reportGridSize: (size) => {
if (size.cols === gridSize.cols && size.rows === gridSize.rows) return;
gridSize = size;
sendResize();
clearTimeout(pendingResize);
if (generation === null) return;
if (options.resizeSettleDelayMs) {
// @effect-diagnostics-next-line globalTimers:off - Grid reports run outside an Effect runtime.
pendingResize = setTimeout(sendResize, options.resizeSettleDelayMs);
} else {
sendResize();
}
},
};
}
Expand Down
Loading