Skip to content
TypeScript

feat(auth): allow passive terminal observation (#9791)

Julius Marmingecc41482df023
diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt
index c38ca6435f3..cf99f02c028 100644
--- a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt
+++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt
@@ -30,6 +30,10 @@ class T3TerminalModule : Module() {
view.focusRequest = focusRequest
}
+ Prop("readOnly") { view: T3TerminalView, readOnly: Boolean ->
+ view.readOnly = readOnly
+ }
+
Prop("autoFocus") { view: T3TerminalView, autoFocus: Boolean ->
view.autoFocus = autoFocus
}
diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt
index 94e0b38e51d..a622b06d3d1 100644
--- a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt
+++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt
@@ -100,6 +100,16 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
}
}
+ var readOnly: Boolean = false
+ set(value) {
+ field = value
+ inputView.isEnabled = !value
+ if (value) {
+ inputView.clearFocus()
+ hideKeyboard()
+ }
+ }
+
var autoFocus: Boolean = true
set(value) {
field = value
@@ -238,6 +248,7 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
inputView.setPadding(0, 0, 0, 0)
inputView.setOnEditorActionListener { _, actionId, event ->
+ if (readOnly) return@setOnEditorActionListener true
val isKeyUp = event?.action == KeyEvent.ACTION_UP
val isImeSend = actionId == EditorInfo.IME_ACTION_SEND && !isKeyUp
val isHardwareEnter = event?.keyCode == KeyEvent.KEYCODE_ENTER &&
@@ -252,6 +263,7 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
}
}
inputView.setOnKeyListener { _, keyCode, event ->
+ if (readOnly) return@setOnKeyListener true
if (event.action != KeyEvent.ACTION_DOWN) return@setOnKeyListener false
when {
keyCode == KeyEvent.KEYCODE_DEL -> {
@@ -273,11 +285,11 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
+ if (readOnly) return
if (clearingInput || s == null || count <= 0) return
val end = (start + count).coerceAtMost(s.length)
- if (start >= end) return
- val insertedText = s.subSequence(start, end).toString()
- if (insertedText.isNotEmpty()) {
+ if (start < end) {
+ val insertedText = s.subSequence(start, end).toString()
onInput(mapOf("data" to insertedText))
}
}
@@ -390,12 +402,13 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
}
private fun emitResponse(response: ByteArray) {
- if (response.isNotEmpty()) {
+ if (!readOnly && response.isNotEmpty()) {
onInput(mapOf("data" to String(response, Charsets.UTF_8)))
}
}
private fun requestKeyboardFocus() {
+ if (readOnly) return
inputView.requestFocus()
val inputMethodManager = context.getSystemService(
Context.INPUT_METHOD_SERVICE
diff --git a/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift b/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift
index a4cfa0a9239..a3ac8f622c5 100644
--- a/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift
+++ b/apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift
@@ -27,6 +27,10 @@ public class T3TerminalModule: Module {
view.focusRequest = focusRequest
}
+ Prop("readOnly") { (view: T3TerminalView, readOnly: Bool) in
+ view.readOnly = readOnly
+ }
+
Prop("autoFocus") { (view: T3TerminalView, autoFocus: Bool) in
view.autoFocus = autoFocus
}
diff --git a/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift
index 9e382bfcd7e..4a69ff77f9f 100644
--- a/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift
+++ b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift
@@ -274,6 +274,14 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
}
}
+ var readOnly = false {
+ didSet {
+ if readOnly {
+ inputField.resignFirstResponder()
+ }
+ }
+ }
+
var autoFocus = true {
didSet {
guard oldValue != autoFocus else { return }
@@ -610,7 +618,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
guard let input = String(data: bytes, encoding: .utf8), !input.isEmpty else { return }
DispatchQueue.main.async {
- view.onInput(["data": input])
+ view.emitInput(input)
}
}, userdata)
}
@@ -687,13 +695,13 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
}
private func requestKeyboardFocus() {
- guard window != nil else { return }
+ guard window != nil, !readOnly else { return }
inputField.becomeFirstResponder()
textInputModeDidChange()
}
private func emitInput(_ data: String) {
- guard !data.isEmpty else { return }
+ guard !readOnly, !data.isEmpty else { return }
onInput(["data": data])
}
diff --git a/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx b/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx
index 328617bb717..f150dcb3300 100644
--- a/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx
+++ b/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx
@@ -23,6 +23,7 @@ import {
type TerminalTheme,
} from "./terminalTheme";
import { terminalDebugLog } from "./terminalDebugLog";
+import { useTerminalSurfaceBuffer } from "./useTerminalSurfaceBuffer";
interface TerminalInputEvent {
readonly data: string;
@@ -35,9 +36,10 @@ interface TerminalResizeEvent {
interface TerminalSurfaceProps extends ViewProps {
readonly terminalKey: string;
- readonly buffer: string;
+ readonly buffer: string | null;
readonly fontSize?: number;
readonly isRunning: boolean;
+ readonly readOnly?: boolean;
readonly autoFocus?: boolean;
readonly keyboardFocusRequest?: number;
readonly captureRequest?: number;
@@ -47,6 +49,10 @@ interface TerminalSurfaceProps extends ViewProps {
readonly onResize: (size: { readonly cols: number; readonly rows: number }) => void;
}
+type ReadyTerminalSurfaceProps = Omit<TerminalSurfaceProps, "buffer"> & {
+ readonly buffer: string;
+};
+
function estimateGridSize(input: {
readonly width: number;
readonly height: number;
@@ -60,14 +66,18 @@ function estimateGridSize(input: {
};
}
-const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: TerminalSurfaceProps) {
+const FallbackTerminalSurface = memo(function FallbackTerminalSurface(
+ props: ReadyTerminalSurfaceProps,
+) {
const fontSize = props.fontSize ?? MOBILE_TYPOGRAPHY.label.fontSize;
const inputRef = useRef<TextInputInstance>(null);
const { themeAppearance, themeId } = useAppearancePreferences();
const theme = props.theme ?? getMobileTerminalTheme(themeId, themeAppearance);
- const statusLabel = props.isRunning
- ? "Native terminal unavailable. Using text fallback."
- : "Open terminal to start a shell.";
+ const statusLabel = props.readOnly
+ ? "Viewing terminal output."
+ : props.isRunning
+ ? "Native terminal unavailable. Using text fallback."
+ : "Open terminal to start a shell.";
const handleLayout = (event: LayoutChangeEvent) => {
const { width, height } = event.nativeEvent.layout;
@@ -75,14 +85,14 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
};
useEffect(() => {
- if ((props.keyboardFocusRequest ?? 0) > 0) {
+ if (!props.readOnly && (props.keyboardFocusRequest ?? 0) > 0) {
inputRef.current?.blur();
const focusFrame = requestAnimationFrame(() => inputRef.current?.focus());
return () => cancelAnimationFrame(focusFrame);
}
return undefined;
- }, [props.keyboardFocusRequest]);
+ }, [props.keyboardFocusRequest, props.readOnly]);
return (
<View
@@ -135,7 +145,7 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
autoCapitalize="none"
autoCorrect={false}
blurOnSubmit={false}
- editable={props.isRunning}
+ editable={props.isRunning && !props.readOnly}
placeholder="type and press return"
placeholderTextColor={theme.mutedForeground}
returnKeyType="send"
@@ -155,9 +165,9 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
}}
/>
<Pressable
- disabled={!props.isRunning}
+ disabled={!props.isRunning || props.readOnly}
style={({ pressed }) => ({
- opacity: !props.isRunning ? 0.35 : pressed ? 0.65 : 1,
+ opacity: !props.isRunning || props.readOnly ? 0.35 : pressed ? 0.65 : 1,
paddingHorizontal: 10,
paddingVertical: 6,
borderRadius: 8,
@@ -175,6 +185,11 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
});
export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) {
+ const buffer = useTerminalSurfaceBuffer(props);
+ return <ReadyTerminalSurface {...props} buffer={buffer} />;
+});
+
+const ReadyTerminalSurface = memo(function ReadyTerminalSurface(props: ReadyTerminalSurfaceProps) {
const fontSize = props.fontSize ?? MOBILE_TYPOGRAPHY.label.fontSize;
const { themeAppearance, themeId } = useAppearancePreferences();
const theme = props.theme ?? getMobileTerminalTheme(themeId, themeAppearance);
@@ -194,7 +209,7 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf
}, [hasNativeSurface, props.buffer.length, props.isRunning, props.terminalKey]);
const handleNativeInput = useCallback(
(event: NativeSyntheticEvent<TerminalInputEvent>) => {
- if (!props.isRunning) {
+ if (!props.isRunning || props.readOnly) {
return;
}
terminalDebugLog("native:onInput", {
@@ -202,7 +217,7 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf
});
onInput(event.nativeEvent.data);
},
- [onInput, props.isRunning],
+ [onInput, props.isRunning, props.readOnly],
);
const handleNativeResize = useCallback(
(event: NativeSyntheticEvent<TerminalResizeEvent>) => {
@@ -219,9 +234,10 @@ export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurf
<View style={props.style}>
<NativeTerminalSurfaceView
appearanceScheme={themeAppearance}
- autoFocus={props.autoFocus ?? true}
+ autoFocus={!props.readOnly && (props.autoFocus ?? true)}
+ readOnly={props.readOnly ?? false}
backgroundColor={theme.background}
- focusRequest={props.isRunning ? (props.keyboardFocusRequest ?? 0) : 0}
+ focusRequest={props.isRunning && !props.readOnly ? (props.keyboardFocusRequest ?? 0) : 0}
foregroundColor={theme.foreground}
mutedForegroundColor={theme.mutedForeground}
terminalKey={props.terminalKey}
diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
index 6b711d8fec9..255fad6f4ea 100644
--- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
+++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
@@ -1,4 +1,10 @@
-import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts";
+import {
+ AuthTerminalReadScope,
+ AuthTerminalOperateScope,
+ DEFAULT_TERMINAL_ID,
+ EnvironmentId,
+ ThreadId,
+} from "@t3tools/contracts";
import { type KnownTerminalSession } from "@t3tools/client-runtime/state/terminal";
import { SymbolView } from "../../components/AppSymbol";
import { ScreenHeader } from "../../components/ScreenHeader";
@@ -32,7 +38,10 @@ import { MaterialIconButton } from "../../components/MaterialIconButton";
import { environmentCatalog } from "../../connection/catalog";
import { useEnvironmentPresentation } from "../../state/presentation";
import { terminalEnvironment } from "../../state/terminal";
+import { environmentSession, readEnvironmentScope } from "../../state/session";
+import { useEnvironmentQuery } from "../../state/query";
import { useAtomCommand } from "../../state/use-atom-command";
+import { uuidv4 } from "../../lib/uuid";
import { useServerConfigs } from "../../state/entities";
import { useConnectionsReady } from "../../state/workspace";
import {
@@ -79,10 +88,13 @@ import {
} from "./terminalInput";
import { createTerminalPasteSession } from "./terminalPaste";
import { cacheTerminalGridSize, getCachedTerminalGridSize } from "./terminalUiState";
+import { useTerminalGridSync } from "./useTerminalGridSync";
+import { useTerminalLifecycle } from "./useTerminalLifecycle";
function TerminalHeader(props: {
readonly subtitle: string;
readonly isEnvironmentReady: boolean;
+ readonly canOperateTerminal: boolean;
readonly fontSize: number;
readonly terminalId: string;
readonly sessions: ReadonlyArray<TerminalMenuSession>;
@@ -149,6 +161,7 @@ function TerminalHeader(props: {
})),
{
id: "terminal-new",
+ disabled: !props.canOperateTerminal,
title: "Open new terminal",
icon: "plus",
subtitle: `Start another shell in ${basename(props.workspaceRoot) ?? "this workspace"}`,
@@ -260,6 +273,15 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
? EnvironmentId.make(routeEnvironmentIdRaw)
: null;
const routeThreadId = routeThreadIdRaw ? ThreadId.make(routeThreadIdRaw) : null;
+ const terminalSession = useEnvironmentQuery(
+ routeEnvironmentId === null ? null : environmentSession.sessionStateAtom(routeEnvironmentId),
+ );
+ const isAuthenticated =
+ terminalSession.error === null && terminalSession.data?.authenticated === true;
+ const canOperateTerminal =
+ isAuthenticated && terminalSession.data?.scopes?.includes(AuthTerminalOperateScope) === true;
+ const canReadTerminal =
+ isAuthenticated && terminalSession.data?.scopes?.includes(AuthTerminalReadScope) === true;
const environment = useEnvironmentPresentation(routeEnvironmentId);
const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
const requestedTerminalId = firstRouteParam(params.terminalId);
@@ -283,18 +305,25 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
terminalId,
})
: null;
- const knownSessions = useKnownTerminalSessions({
+ const {
+ sessions: knownSessions,
+ isPending: sessionsPending,
+ error: sessionsError,
+ } = useKnownTerminalSessions({
environmentId: selectedThread?.environmentId ?? null,
threadId: selectedThread?.id ?? null,
});
const runningSession = useMemo(
- () => pickRunningTerminalSessionForBootstrap(knownSessions),
- [knownSessions],
+ () =>
+ pickRunningTerminalSessionForBootstrap(knownSessions ?? []) ??
+ (canOperateTerminal ? null : (knownSessions?.[0] ?? null)),
+ [canOperateTerminal, knownSessions],
);
const activeKnownSession = useMemo(
- () => knownSessions.find((session) => session.target.terminalId === terminalId) ?? null,
+ () => knownSessions?.find((session) => session.target.terminalId === terminalId) ?? null,
[knownSessions, terminalId],
);
+ const hasTerminalTarget = requestedTerminalId !== null || activeKnownSession !== null;
const launchTarget = useMemo(
() =>
selectedThread
@@ -418,13 +447,28 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
terminalId,
],
);
+ const observingTerminal =
+ !canOperateTerminal && canReadTerminal && selectedThread !== null && hasTerminalTarget;
const terminal = useAttachedTerminalSession({
environmentId: selectedThread?.environmentId ?? null,
- terminal: terminalAttachInput,
+ terminal: canOperateTerminal
+ ? terminalAttachInput
+ : observingTerminal
+ ? { threadId: selectedThread.id, terminalId }
+ : null,
});
const terminalKey = selectedThread
? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`
: terminalId;
+ useTerminalGridSync({
+ environmentId: selectedThread?.environmentId ?? null,
+ threadId: selectedThread?.id ?? null,
+ terminalId,
+ canOperate: canOperateTerminal,
+ terminal,
+ size: lastGridSize,
+ resize: resizeTerminal,
+ });
const bufferReplayKey = useMemo(
() => getTerminalBufferReplayKey({ terminalKey, fontSize }),
[fontSize, terminalKey],
@@ -439,64 +483,8 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
});
const isRunning = terminal.status === "running" || terminal.status === "starting";
- // When the process ends while this screen is attached (e.g. typing `exit`),
- // close the session and leave the screen, mirroring the web drawer's
- // onSessionExited flow. Only react to a running -> exited transition
- // observed on this screen so already-exited sessions can still be opened
- // (they restart on attach).
- const runningTerminalKeyRef = useRef<string | null>(null);
- const reopenedStaleTerminalKeyRef = useRef<string | null>(null);
const pendingExitNavigationRef = useRef<string | null>(null);
- // Attach subscriptions are cached with an idle TTL, so revisiting a
- // terminal whose session ended while unobserved reuses the stale stream
- // without a new attach RPC — the server never respawns anything. Detect
- // that (dead status with processed events, never seen running here) and
- // issue an explicit open; its snapshot flows into the live subscription.
- useEffect(() => {
- if (isRunning) {
- reopenedStaleTerminalKeyRef.current = null;
- return;
- }
- if (
- terminalAttachInput === null ||
- !selectedThread ||
- (terminal.status !== "closed" && terminal.status !== "exited") ||
- terminal.version === 0 ||
- runningTerminalKeyRef.current === terminalKey ||
- reopenedStaleTerminalKeyRef.current === terminalKey
- ) {
- return;
- }
- reopenedStaleTerminalKeyRef.current = terminalKey;
- void openTerminal({
- environmentId: selectedThread.environmentId,
- input: {
- threadId: selectedThread.id,
- terminalId,
- cwd: terminalAttachInput.cwd,
- worktreePath: terminalAttachInput.worktreePath,
- cols: terminalAttachInput.cols,
- rows: terminalAttachInput.rows,
- ...(terminalAttachInput.env ? { env: terminalAttachInput.env } : {}),
- },
- }).then((result) => {
- // Release the guard on failure so a later render can retry the respawn.
- if (result._tag === "Failure" && reopenedStaleTerminalKeyRef.current === terminalKey) {
- reopenedStaleTerminalKeyRef.current = null;
- }
- });
- }, [
- isRunning,
- openTerminal,
- selectedThread,
- terminal.status,
- terminal.version,
- terminalAttachInput,
- terminalId,
- terminalKey,
- ]);
-
useEffect(() => {
terminalDebugLog("surface:props", {
terminalKey,
@@ -596,7 +584,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
height: state.height,
isVisible: state.isVisible,
}));
- const isAccessoryVisible = keyboardState.isVisible && !isAccessoryDismissed;
+ const isAccessoryVisible = canOperateTerminal && keyboardState.isVisible && !isAccessoryDismissed;
// Android's terminal owns an EditText; turning off autoFocus also clears its native focus.
const terminalAutoFocus =
Platform.OS === "android"
@@ -624,7 +612,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
const terminalMenuSessions = useMemo<ReadonlyArray<TerminalMenuSession>>(
() =>
buildTerminalMenuSessions({
- knownSessions,
+ knownSessions: knownSessions ?? [],
workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
currentSession: {
terminalId,
@@ -707,8 +695,10 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
useEffect(() => {
const initialInput = pendingLaunch?.initialInput;
if (
+ !canOperateTerminal ||
!initialInput ||
!selectedThread ||
+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope) ||
terminal.version === 0 ||
sentInitialInputKeyRef.current === launchTargetKey
) {
@@ -730,6 +720,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
terminal.version,
terminalId,
writeTerminal,
+ canOperateTerminal,
]);
useEffect(() => {
@@ -795,7 +786,11 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
/** Resolves true once the pty accepted the write, false if it was skipped or rejected. */
const writeInput = useCallback(
async (data: string): Promise<boolean> => {
- if (!selectedThread || !isRunning) {
+ if (
+ !selectedThread ||
+ !isRunning ||
+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
+ ) {
return false;
}
@@ -820,11 +815,11 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
// Drop delayed clipboard reads whenever the route or attached pty changes.
useEffect(() => {
- pasteSession.reset(isRunning);
+ pasteSession.reset(canOperateTerminal && isRunning);
return () => {
pasteSession.reset(false);
};
- }, [isRunning, pasteSession, terminal.lifecycleVersion, terminalKey]);
+ }, [canOperateTerminal, isRunning, pasteSession, terminal.lifecycleVersion, terminalKey]);
const pasteFromClipboard = useCallback(async () => {
await pasteSession.paste({
@@ -896,31 +891,15 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
}
setLastGridSize(size);
- if (!selectedThread || !isRunning) {
- return;
- }
-
- void resizeTerminal({
- environmentId: selectedThread.environmentId,
- input: {
- threadId: selectedThread.id,
- terminalId,
- cols: size.cols,
- rows: size.rows,
- },
- });
},
[
- isRunning,
lastGridSize.cols,
lastGridSize.rows,
bufferReplayKey,
readyBufferReplayKey,
routeEnvironmentId,
routeThreadId,
- resizeTerminal,
scheduleBufferReplayReady,
- selectedThread,
terminalId,
terminalKey,
],
@@ -989,59 +968,54 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
}
}, [navigation, selectedThread, terminalId, terminalMenuSessions]);
- useEffect(() => {
- // Detached (hidden surface or environment drop): forget the running
- // marker so a reattach takes the stale-reopen path instead of misreading
- // the dead snapshot as an exit observed on this screen. A pending exit
- // navigation stays armed — it only clears once the session runs again —
- // so refocusing a dead screen still leaves it.
- if (terminalAttachInput === null) {
- runningTerminalKeyRef.current = null;
- return;
- }
- if (isRunning) {
- runningTerminalKeyRef.current = terminalKey;
- // The session came back (e.g. respawned elsewhere) before the user
- // returned; a stale pending exit must not eject a live terminal.
- pendingExitNavigationRef.current = null;
- return;
- }
- // The web drawer treats both exited and closed as session end.
- const sessionEnded = terminal.status === "exited" || terminal.status === "closed";
- if (!sessionEnded || runningTerminalKeyRef.current !== terminalKey) {
- return;
- }
- runningTerminalKeyRef.current = null;
- // Mark this key handled so the stale-attach effect doesn't respawn the
- // session the user just ended.
- reopenedStaleTerminalKeyRef.current = terminalKey;
- if (selectedThread) {
- void closeTerminal({
+ useTerminalLifecycle({
+ terminalKey,
+ canOperate: canOperateTerminal,
+ observing: observingTerminal,
+ attached: terminalAttachInput !== null && selectedThread !== null,
+ terminal,
+ reopen: async () => {
+ if (
+ terminalAttachInput === null ||
+ selectedThread === null ||
+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
+ )
+ return false;
+ const result = await openTerminal({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
terminalId,
+ cwd: terminalAttachInput.cwd,
+ worktreePath: terminalAttachInput.worktreePath,
+ cols: terminalAttachInput.cols,
+ rows: terminalAttachInput.rows,
+ ...(terminalAttachInput.env ? { env: terminalAttachInput.env } : {}),
},
});
- }
- if (navigation.isFocused()) {
- navigateAwayAfterExit();
- return;
- }
- // An unfocused screen can't navigate; leave when the user returns so
- // they never land on the dead session.
- pendingExitNavigationRef.current = terminalKey;
- }, [
- closeTerminal,
- isRunning,
- navigateAwayAfterExit,
- navigation,
- selectedThread,
- terminal.status,
- terminalAttachInput,
- terminalId,
- terminalKey,
- ]);
+ return result._tag === "Success";
+ },
+ onRunning: () => {
+ pendingExitNavigationRef.current = null;
+ },
+ onExit: () => {
+ if (
+ selectedThread === null ||
+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
+ )
+ return;
+ void closeTerminal({
+ environmentId: selectedThread.environmentId,
+ input: { threadId: selectedThread.id, terminalId },
+ });
+ if (navigation.isFocused()) {
+ navigateAwayAfterExit();
+ return;
+ }
+ // Leave a background terminal screen when it is focused again.
+ pendingExitNavigationRef.current = terminalKey;
+ },
+ });
useEffect(
() =>
@@ -1056,7 +1030,10 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
);
const handleOpenNewTerminal = useCallback(() => {
- if (!selectedThread) {
+ if (
+ !selectedThread ||
+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
+ ) {
return;
}
@@ -1067,10 +1044,14 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
terminalId: nextOpenTerminalId({
listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
activeRouteTerminalId: terminalId,
+ ...(knownSessions === null ||
+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
+ ? { uniqueSuffix: uuidv4() }
+ : {}),
}),
}),
);
- }, [navigation, selectedThread, terminalId, terminalMenuSessions]);
+ }, [knownSessions, navigation, selectedThread, terminalId, terminalMenuSessions]);
const handleDecreaseFontSize = useCallback(() => {
setTerminalFontSize(stepTerminalFontSize(fontSize, -1));
@@ -1081,7 +1062,10 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
}, [fontSize, setTerminalFontSize]);
const handleClearTerminal = useCallback(() => {
- if (!selectedThread) {
+ if (
+ !selectedThread ||
+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
+ ) {
return;
}
@@ -1130,9 +1114,10 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
}, []);
const handleShowKeyboard = useCallback(() => {
+ if (!canOperateTerminal) return;
setIsAccessoryDismissed(false);
setKeyboardFocusRequest((current) => current + 1);
- }, []);
+ }, [canOperateTerminal]);
const handleRetryEnvironment = useCallback(() => {
if (routeEnvironmentId !== null) {
void retryEnvironment(routeEnvironmentId);
@@ -1186,6 +1171,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
/>
) : null}
<TerminalHeader
+ canOperateTerminal={canOperateTerminal}
subtitle={headerSubtitle}
isEnvironmentReady={isEnvironmentReady}
fontSize={fontSize}
@@ -1232,6 +1218,34 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
resourceName="terminal"
onRetry={handleRetryEnvironment}
/>
+ ) : terminalSession.data === null && terminalSession.error === null ? (
+ <EmptyState
+ title="Checking terminal access"
+ detail="Waiting for this connection's permissions."
+ />
+ ) : !canReadTerminal && !canOperateTerminal ? (
+ <EmptyState
+ title={
+ terminalSession.error
+ ? "Could not check terminal access"
+ : "Terminal access unavailable"
+ }
+ detail={
+ terminalSession.error ??
+ "This connection does not have permission to view terminals."
+ }
+ />
+ ) : !canOperateTerminal && !hasTerminalTarget && sessionsPending ? (
+ <EmptyState title="Loading terminals" detail="Reading existing terminal sessions." />
+ ) : !canOperateTerminal && !hasTerminalTarget && sessionsError !== null ? (
+ <EmptyState title="Could not load terminals" detail={sessionsError} />
+ ) : !canOperateTerminal && !hasTerminalTarget ? (
+ <EmptyState
+ title="No terminal sessions"
+ detail="Existing terminals will appear here when another client opens one."
+ />
+ ) : !canOperateTerminal && terminal.error !== null ? (
+ <EmptyState title="Terminal unavailable" detail={terminal.error} />
) : (
<>
<View
@@ -1249,8 +1263,9 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
}}
/>
<TerminalSurface
- autoFocus={terminalAutoFocus}
- buffer={terminalSurfaceBuffer}
+ autoFocus={canOperateTerminal && terminalAutoFocus}
+ readOnly={!canOperateTerminal}
+ buffer={terminal.version === 0 ? null : terminalSurfaceBuffer}
fontSize={fontSize}
isRunning={isRunning}
keyboardFocusRequest={keyboardFocusRequest}
@@ -1279,6 +1294,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
<View className="flex-1" />
<MaterialIconButton
accessibilityLabel="Show keyboard"
+ disabled={!canOperateTerminal}
icon="keyboard"
onPress={handleShowKeyboard}
/>
@@ -1345,7 +1361,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
</ComposerToolbarRow>
</View>
</KeyboardStickyView>
- ) : !keyboardState.isVisible && Platform.OS !== "android" ? (
+ ) : canOperateTerminal && !keyboardState.isVisible && Platform.OS !== "android" ? (
<Pressable
accessibilityLabel="Show keyboard"
accessibilityRole="button"
diff --git a/apps/mobile/src/features/terminal/nativeTerminalModule.ts b/apps/mobile/src/features/terminal/nativeTerminalModule.ts
index a061d26d38c..85c7193bcbd 100644
--- a/apps/mobile/src/features/terminal/nativeTerminalModule.ts
+++ b/apps/mobile/src/features/terminal/nativeTerminalModule.ts
@@ -24,6 +24,7 @@ interface TerminalResizeEvent {
export interface NativeTerminalSurfaceProps extends ViewProps {
readonly appearanceScheme?: "light" | "dark";
readonly autoFocus?: boolean;
+ readonly readOnly?: boolean;
readonly focusRequest?: number;
readonly captureRequest?: number;
readonly onCapture?: (event: NativeSyntheticEvent<{ readonly text: string }>) => void;
diff --git a/apps/mobile/src/features/terminal/terminalMenu.test.ts b/apps/mobile/src/features/terminal/terminalMenu.test.ts
index 2f8ce137772..7b924dcbbc4 100644
--- a/apps/mobile/src/features/terminal/terminalMenu.test.ts
+++ b/apps/mobile/src/features/terminal/terminalMenu.test.ts
@@ -129,6 +129,19 @@ describe("buildTerminalMenuSessions", () => {
});
describe("nextOpenTerminalId", () => {
+ it("allocates separate terminals on repeated visits without readable metadata", () => {
+ const first = nextOpenTerminalId({
+ listedTerminalIds: [],
+ uniqueSuffix: "783c91cc-a413-47c7-8312-c2a5a1f05e40",
+ });
+ const nextVisit = nextOpenTerminalId({
+ listedTerminalIds: [],
+ uniqueSuffix: "102315fc-ceef-45c4-b978-c4d4947d3c26",
+ });
+ expect(first).not.toBe(DEFAULT_TERMINAL_ID);
+ expect(nextVisit).not.toBe(first);
+ });
+
it("matches nextTerminalId when not on a terminal route", () => {
expect(nextOpenTerminalId({ listedTerminalIds: [] })).toBe(DEFAULT_TERMINAL_ID);
expect(nextOpenTerminalId({ listedTerminalIds: [DEFAULT_TERMINAL_ID] })).toBe("term-2");
@@ -208,6 +221,16 @@ describe("previousLiveTerminalId", () => {
});
describe("resolveProjectScriptTerminalId", () => {
+ it("never targets an unseen default terminal when metadata is unavailable", () => {
+ const terminalId = resolveProjectScriptTerminalId({
+ existingTerminalIds: [],
+ hasRunningTerminal: false,
+ uniqueSuffix: "783c91cc-a413-47c7-8312-c2a5a1f05e40",
+ });
+ expect(terminalId).not.toBe(DEFAULT_TERMINAL_ID);
+ expect(getTerminalLabel(terminalId)).toBe("Terminal 1");
+ });
+
it("reuses the default shell when no terminal is running", () => {
expect(
resolveProjectScriptTerminalId({
diff --git a/apps/mobile/src/features/terminal/terminalMenu.ts b/apps/mobile/src/features/terminal/terminalMenu.ts
index 06cb74e9467..47f3d08144a 100644
--- a/apps/mobile/src/features/terminal/terminalMenu.ts
+++ b/apps/mobile/src/features/terminal/terminalMenu.ts
@@ -70,15 +70,16 @@ export function getTerminalStatusLabel(input: {
export function nextOpenTerminalId(input: {
readonly listedTerminalIds: ReadonlyArray<string>;
readonly activeRouteTerminalId?: string | null;
+ readonly uniqueSuffix?: string;
}): string {
const listed = input.listedTerminalIds.filter((id) => id.trim().length > 0);
const routeId = input.activeRouteTerminalId?.trim() ? input.activeRouteTerminalId : null;
if (!routeId || listed.includes(routeId)) {
- return nextTerminalId(listed);
+ return nextTerminalId(listed, input.uniqueSuffix);
}
- return nextTerminalId([...listed, routeId]);
+ return nextTerminalId([...listed, routeId], input.uniqueSuffix);
}
export function buildTerminalMenuSessions(input: {
@@ -146,12 +147,13 @@ export function previousLiveTerminalId(input: {
export function resolveProjectScriptTerminalId(input: {
readonly existingTerminalIds: ReadonlyArray<string>;
readonly hasRunningTerminal: boolean;
+ readonly uniqueSuffix?: string;
}): string {
- if (!input.hasRunningTerminal) {
+ if (!input.hasRunningTerminal && input.uniqueSuffix === undefined) {
return DEFAULT_TERMINAL_ID;
}
- return nextTerminalId(input.existingTerminalIds);
+ return nextTerminalId(input.existingTerminalIds, input.uniqueSuffix);
}
export function projectScriptMenuLabel(script: ProjectScript): string {
diff --git a/apps/mobile/src/features/terminal/useTerminalGridSync.test.ts b/apps/mobile/src/features/terminal/useTerminalGridSync.test.ts
new file mode 100644
index 00000000000..827516c6e69
--- /dev/null
+++ b/apps/mobile/src/features/terminal/useTerminalGridSync.test.ts
@@ -0,0 +1,183 @@
+import * as NodeModule from "node:module";
+import { EMPTY_TERMINAL_BUFFER_STATE } from "@t3tools/client-runtime/state/terminal";
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { act, createElement, type ReactNode } from "react";
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
+
+import { useTerminalGridSync } from "./useTerminalGridSync";
+
+const access = vi.hoisted(() => ({ environments: new Set<string>() }));
+vi.mock("../../state/session", () => ({
+ readEnvironmentScope: (environmentId: string, scope: string) =>
+ scope === "terminal:operate" && access.environments.has(environmentId),
+}));
+
+// Mobile already depends on ReactDOM but does not install its browser type declarations.
+const { createRoot } = NodeModule.createRequire(import.meta.url)("react-dom/client") as {
+ createRoot(container: Element): {
+ render(children: ReactNode): void;
+ unmount(): void;
+ };
+};
+
+type Input = Parameters<typeof useTerminalGridSync>[0];
+let root: ReturnType<typeof createRoot>;
+const resize = vi.fn<Input["resize"]>();
+
+function GridProbe(input: Input) {
+ useTerminalGridSync(input);
+ return null;
+}
+
+function session({
+ generation = 1,
+ version = 1,
+ status = "running",
+}: {
+ readonly generation?: number;
+ readonly version?: number;
+ readonly status?: Input["terminal"]["status"];
+} = {}): Input["terminal"] {
+ return { output: { ...EMPTY_TERMINAL_BUFFER_STATE.output, generation }, version, status };
+}
+
+function input(): Input {
+ return {
+ environmentId: EnvironmentId.make("environment"),
+ threadId: ThreadId.make("thread"),
+ terminalId: "term-1",
+ canOperate: true,
+ terminal: session(),
+ size: { cols: 80, rows: 24 },
+ resize,
+ };
+}
+
+function render(value: Input) {
+ return act(() => root.render(createElement(GridProbe, value)));
+}
+
+beforeEach(() => {
+ resize.mockClear();
+ access.environments.clear();
+ access.environments.add("environment");
+ // The probe renders no DOM, but ReactDOM needs an event target to run real effects.
+ const document = {
+ nodeType: 9,
+ addEventListener() {},
+ removeEventListener() {},
+ };
+ const container = {
+ nodeType: 1,
+ tagName: "DIV",
+ namespaceURI: "http://www.w3.org/1999/xhtml",
+ ownerDocument: document,
+ addEventListener() {},
+ removeEventListener() {},
+ };
+ vi.stubGlobal("document", document);
+ vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ root = createRoot(container as unknown as HTMLElement);
+});
+
+it("checks the current target grant before dispatching a delayed resize", async () => {
+ const current = input();
+ await render(current);
+ expect(resize).toHaveBeenCalledOnce();
+
+ access.environments.clear();
+ await render({ ...current, size: { cols: 120, rows: 40 } });
+ expect(resize).toHaveBeenCalledOnce();
+
+ access.environments.add("secondary");
+ await render({ ...current, size: { cols: 120, rows: 41 } });
+ expect(resize).toHaveBeenCalledOnce();
+
+ await render({ ...current, environmentId: EnvironmentId.make("secondary") });
+ expect(resize).toHaveBeenCalledTimes(2);
+ expect(resize).toHaveBeenLastCalledWith({
+ environmentId: "secondary",
+ input: { threadId: "thread", terminalId: "term-1", cols: 80, rows: 24 },
+ });
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ vi.unstubAllGlobals();
+});
+
+it("replays an observer's measured grid once its writable attachment snapshot arrives", async () => {
+ let current = { ...input(), canOperate: false };
+ await render(current);
+ current = { ...current, size: { cols: 120, rows: 40 } };
+ await render(current);
+ expect(resize).not.toHaveBeenCalled();
+
+ current = {
+ ...current,
+ canOperate: true,
+ terminal: session({ generation: 2, version: 0 }),
+ };
+ await render(current);
+ expect(resize).not.toHaveBeenCalled();
+
+ current = { ...current, terminal: session({ generation: 2 }) };
+ await render(current);
+ expect(resize).toHaveBeenCalledExactlyOnceWith({
+ environmentId: "environment",
+ input: { threadId: "thread", terminalId: "term-1", cols: 120, rows: 40 },
+ });
+
+ await render({ ...current, terminal: session({ generation: 2, version: 3 }) });
+ await render({ ...current, size: { ...current.size } });
+ expect(resize).toHaveBeenCalledOnce();
+
+ await render({ ...current, size: { cols: 120, rows: 41 } });
+ expect(resize).toHaveBeenCalledTimes(2);
+ expect(resize).toHaveBeenLastCalledWith({
+ environmentId: "environment",
+ input: { threadId: "thread", terminalId: "term-1", cols: 120, rows: 41 },
+ });
+});
+
+it("replays an unchanged grid after reconnecting with a new attachment generation", async () => {
+ const current = { ...input(), size: { cols: 120, rows: 40 } };
+ await render(current);
+ expect(resize).toHaveBeenCalledOnce();
+
+ await render({ ...current, terminal: session({ generation: 2, version: 0 }) });
+ expect(resize).toHaveBeenCalledOnce();
+
+ await render({ ...current, terminal: session({ generation: 2 }) });
+ expect(resize).toHaveBeenCalledTimes(2);
+ expect(resize).toHaveBeenLastCalledWith({
+ environmentId: "environment",
+ input: { threadId: "thread", terminalId: "term-1", cols: 120, rows: 40 },
+ });
+
+ // React may observe the next snapshot without rendering the empty seed first.
+ await render({ ...current, terminal: session({ generation: 3 }) });
+ expect(resize).toHaveBeenCalledTimes(3);
+});
+
+it.each([
+ { name: "permission is revoked", change: { canOperate: false } },
+ { name: "the attachment is pending", change: { terminal: session({ version: 0 }) } },
+ { name: "the process has exited", change: { terminal: session({ status: "exited" }) } },
+])("retains measurements without resizing while $name", async ({ change }) => {
+ const current = input();
+ await render(current);
+ expect(resize).toHaveBeenCalledOnce();
+
+ await render({ ...current, ...change, size: { cols: 120, rows: 40 } });
+ await render({ ...current, ...change, size: { cols: 120, rows: 41 } });
+ expect(resize).toHaveBeenCalledOnce();
+
+ await render({ ...current, size: { cols: 120, rows: 41 } });
+ expect(resize).toHaveBeenCalledTimes(2);
+ expect(resize).toHaveBeenLastCalledWith({
+ environmentId: "environment",
+ input: { threadId: "thread", terminalId: "term-1", cols: 120, rows: 41 },
+ });
+});
diff --git a/apps/mobile/src/features/terminal/useTerminalGridSync.ts b/apps/mobile/src/features/terminal/useTerminalGridSync.ts
new file mode 100644
index 00000000000..1ad8922fcbe
--- /dev/null
+++ b/apps/mobile/src/features/terminal/useTerminalGridSync.ts
@@ -0,0 +1,52 @@
+import type { TerminalSessionState } from "@t3tools/client-runtime/state/terminal";
+import {
+ AuthTerminalOperateScope,
+ type EnvironmentId,
+ type TerminalResizeInput,
+ type ThreadId,
+} from "@t3tools/contracts";
+import { useEffect } from "react";
+
+import type { TerminalGridSize } from "./terminalUiState";
+import { readEnvironmentScope } from "../../state/session";
+
+/** Replay the measured grid when a writable attachment becomes ready or reconnects. */
+export function useTerminalGridSync({
+ environmentId,
+ threadId,
+ terminalId,
+ canOperate,
+ terminal,
+ size,
+ resize,
+}: {
+ readonly environmentId: EnvironmentId | null;
+ readonly threadId: ThreadId | null;
+ readonly terminalId: string;
+ readonly canOperate: boolean;
+ readonly terminal: Pick<TerminalSessionState, "output" | "status" | "version">;
+ readonly size: TerminalGridSize;
+ readonly resize: (target: {
+ readonly environmentId: EnvironmentId;
+ readonly input: TerminalResizeInput;
+ }) => void;
+}): void {
+ const generation =
+ canOperate && terminal.version > 0 && terminal.status === "running"
+ ? terminal.output.generation
+ : null;
+
+ useEffect(() => {
+ if (
+ generation === null ||
+ environmentId === null ||
+ threadId === null ||
+ !readEnvironmentScope(environmentId, AuthTerminalOperateScope)
+ )
+ return;
+ resize({
+ environmentId,
+ input: { threadId, terminalId, cols: size.cols, rows: size.rows },
+ });
+ }, [environmentId, generation, resize, size.cols, size.rows, terminalId, threadId]);
+}
diff --git a/apps/mobile/src/features/terminal/useTerminalLifecycle.test.ts b/apps/mobile/src/features/terminal/useTerminalLifecycle.test.ts
new file mode 100644
index 00000000000..c3278a0d205
--- /dev/null
+++ b/apps/mobile/src/features/terminal/useTerminalLifecycle.test.ts
@@ -0,0 +1,177 @@
+import * as NodeModule from "node:module";
+import { act, createElement, type ReactNode } from "react";
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
+
+import { useTerminalLifecycle } from "./useTerminalLifecycle";
+
+const { createRoot } = NodeModule.createRequire(import.meta.url)("react-dom/client") as {
+ createRoot(container: Element): {
+ render(children: ReactNode): void;
+ unmount(): void;
+ };
+};
+
+type Input = Parameters<typeof useTerminalLifecycle>[0];
+let root: ReturnType<typeof createRoot>;
+const reopen = vi.fn<Input["reopen"]>();
+const onRunning = vi.fn<Input["onRunning"]>();
+const onExit = vi.fn<Input["onExit"]>();
+
+function LifecycleProbe(input: Input) {
+ useTerminalLifecycle(input);
+ return null;
+}
+
+function input(changes: Partial<Input> = {}): Input {
+ return {
+ terminalKey: "environment:thread:term-1",
+ canOperate: true,
+ observing: false,
+ attached: true,
+ terminal: { status: "running", version: 1 },
+ reopen,
+ onRunning,
+ onExit,
+ ...changes,
+ };
+}
+
+function render(value: Input) {
+ return act(() => root.render(createElement(LifecycleProbe, value)));
+}
+
+beforeEach(() => {
+ reopen.mockReset().mockResolvedValue(true);
+ onRunning.mockClear();
+ onExit.mockClear();
+ const document = {
+ nodeType: 9,
+ addEventListener() {},
+ removeEventListener() {},
+ };
+ const container = {
+ nodeType: 1,
+ tagName: "DIV",
+ namespaceURI: "http://www.w3.org/1999/xhtml",
+ ownerDocument: document,
+ addEventListener() {},
+ removeEventListener() {},
+ };
+ vi.stubGlobal("document", document);
+ vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ root = createRoot(container as unknown as HTMLElement);
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ vi.unstubAllGlobals();
+});
+
+it.each(["running", "closed", "exited"] as const)(
+ "waits for the replacement attachment snapshot before handling %s",
+ async (status) => {
+ await render(input());
+ await render(input({ terminal: { status: "closed", version: 0 } }));
+ expect(onExit).not.toHaveBeenCalled();
+ expect(reopen).not.toHaveBeenCalled();
+
+ await render(input({ terminal: { status, version: 1 } }));
+ expect(onExit).toHaveBeenCalledTimes(status === "running" ? 0 : 1);
+ expect(reopen).not.toHaveBeenCalled();
+ },
+);
+
+it("retains an exited observer's history after gaining operate", async () => {
+ await render(input({ canOperate: false, terminal: { status: "exited", version: 1 } }));
+ await render(input({ terminal: { status: "closed", version: 0 } }));
+ await render(input({ terminal: { status: "exited", version: 1 } }));
+ expect(reopen).not.toHaveBeenCalled();
+ expect(onExit).not.toHaveBeenCalled();
+});
+
+it.each(["closed", "exited"] as const)(
+ "keeps a pending observer passive when its first writable snapshot is %s",
+ async (status) => {
+ await render(
+ input({
+ canOperate: false,
+ observing: true,
+ terminal: { status, version: 0 },
+ }),
+ );
+ await render(input({ terminal: { status: "closed", version: 0 } }));
+ await render(input({ terminal: { status, version: 1 } }));
+ expect(reopen).not.toHaveBeenCalled();
+ expect(onExit).not.toHaveBeenCalled();
+ expect(onRunning).not.toHaveBeenCalled();
+ },
+);
+
+it("reopens an explicit operator visit after permissions finish loading", async () => {
+ await render(
+ input({
+ canOperate: false,
+ observing: false,
+ terminal: { status: "closed", version: 0 },
+ }),
+ );
+ await render(input({ terminal: { status: "closed", version: 0 } }));
+ await render(input({ terminal: { status: "exited", version: 1 } }));
+ expect(reopen).toHaveBeenCalledOnce();
+ expect(onExit).not.toHaveBeenCalled();
+});
+
+it("does not respawn a terminal that exited after operate was revoked", async () => {
+ await render(input());
+ await render(input({ canOperate: false }));
+ await render(input({ canOperate: false, terminal: { status: "exited", version: 2 } }));
+ await render(input({ terminal: { status: "exited", version: 1 } }));
+ expect(reopen).not.toHaveBeenCalled();
+ expect(onExit).not.toHaveBeenCalled();
+});
+
+it("remembers revocation before the observer has received a snapshot", async () => {
+ await render(input());
+ await render(input({ canOperate: false, terminal: { status: "closed", version: 0 } }));
+ await render(input({ terminal: { status: "exited", version: 1 } }));
+ expect(reopen).not.toHaveBeenCalled();
+ expect(onExit).not.toHaveBeenCalled();
+});
+
+it("cleans up an actual exit after an observed running terminal becomes writable", async () => {
+ await render(input({ canOperate: false }));
+ await render(input());
+ await render(input({ terminal: { status: "exited", version: 2 } }));
+ await render(input({ terminal: { status: "closed", version: 3 } }));
+ expect(onExit).toHaveBeenCalledOnce();
+ expect(reopen).not.toHaveBeenCalled();
+});
+
+it("reopens an ended terminal on an explicit new route visit", async () => {
+ await render(input({ canOperate: false, terminal: { status: "exited", version: 1 } }));
+ await render(input({ terminalKey: "environment:thread:term-2" }));
+ await render(input({ terminal: { status: "exited", version: 1 } }));
+ expect(reopen).toHaveBeenCalledOnce();
+
+ await render(input({ terminal: { status: "exited", version: 2 } }));
+ expect(reopen).toHaveBeenCalledOnce();
+ await render(input({ terminal: { status: "running", version: 3 } }));
+ await render(input({ terminal: { status: "exited", version: 4 } }));
+ expect(onExit).toHaveBeenCalledOnce();
+});
+
+it("keeps a detached terminal from being mistaken for a live exit", async () => {
+ await render(input());
+ await render(input({ attached: false, terminal: { status: "closed", version: 0 } }));
+ await render(input({ terminal: { status: "exited", version: 1 } }));
+ expect(onExit).not.toHaveBeenCalled();
+ expect(reopen).toHaveBeenCalledOnce();
+});
+
+it("allows a later snapshot to retry an unsuccessful explicit reopen", async () => {
+ reopen.mockResolvedValueOnce(false);
+ await render(input({ terminal: { status: "exited", version: 1 } }));
+ await render(input({ terminal: { status: "exited", version: 2 } }));
+ expect(reopen).toHaveBeenCalledTimes(2);
+});
diff --git a/apps/mobile/src/features/terminal/useTerminalLifecycle.ts b/apps/mobile/src/features/terminal/useTerminalLifecycle.ts
new file mode 100644
index 00000000000..cb71cf14cf5
--- /dev/null
+++ b/apps/mobile/src/features/terminal/useTerminalLifecycle.ts
@@ -0,0 +1,79 @@
+import type { TerminalSessionState } from "@t3tools/client-runtime/state/terminal";
+import { useEffect, useEffectEvent, useRef } from "react";
+
+/** Keep observed history passive while preserving explicit terminal visits and live exits. */
+export function useTerminalLifecycle({
+ terminalKey,
+ canOperate,
+ observing,
+ attached,
+ terminal,
+ reopen,
+ onRunning,
+ onExit,
+}: {
+ readonly terminalKey: string;
+ readonly canOperate: boolean;
+ readonly observing: boolean;
+ readonly attached: boolean;
+ readonly terminal: Pick<TerminalSessionState, "status" | "version">;
+ readonly reopen: () => Promise<boolean>;
+ readonly onRunning: () => void;
+ readonly onExit: () => void;
+}) {
+ const lifecycle = useRef({
+ key: terminalKey,
+ wasRunning: false,
+ observed: false,
+ reopened: false,
+ });
+ const reopenTerminal = useEffectEvent(reopen);
+ const handleRunning = useEffectEvent(onRunning);
+ const handleExit = useEffectEvent(onExit);
+
+ useEffect(() => {
+ if (lifecycle.current.key !== terminalKey) {
+ lifecycle.current = {
+ key: terminalKey,
+ wasRunning: false,
+ observed: false,
+ reopened: false,
+ };
+ }
+ const current = lifecycle.current;
+ if (!canOperate) {
+ // An observe request stays passive before its first snapshot arrives.
+ if (observing || terminal.version > 0 || current.wasRunning) current.observed = true;
+ current.wasRunning = false;
+ return;
+ }
+ if (!attached) {
+ current.wasRunning = false;
+ return;
+ }
+ // An attachment without its first snapshot has no known process status yet.
+ if (terminal.version === 0) return;
+
+ if (terminal.status === "running" || terminal.status === "starting") {
+ current.wasRunning = true;
+ current.reopened = false;
+ handleRunning();
+ return;
+ }
+ if (terminal.status !== "closed" && terminal.status !== "exited") return;
+
+ if (current.wasRunning) {
+ current.wasRunning = false;
+ current.reopened = true;
+ handleExit();
+ return;
+ }
+ // An explicit visit can reopen a cached ended session. Granting a viewer
+ // operate permission must leave the history they were reading intact.
+ if (current.observed || current.reopened) return;
+ current.reopened = true;
+ void reopenTerminal().then((succeeded) => {
+ if (!succeeded && lifecycle.current === current) current.reopened = false;
+ });
+ }, [attached, canOperate, observing, terminal.status, terminal.version, terminalKey]);
+}
diff --git a/apps/mobile/src/features/terminal/useTerminalSurfaceBuffer.test.ts b/apps/mobile/src/features/terminal/useTerminalSurfaceBuffer.test.ts
new file mode 100644
index 00000000000..7721d647a4f
--- /dev/null
+++ b/apps/mobile/src/features/terminal/useTerminalSurfaceBuffer.test.ts
@@ -0,0 +1,100 @@
+import * as NodeModule from "node:module";
+import { act, createElement, useEffect, type ReactNode } from "react";
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
+
+import { useTerminalSurfaceBuffer } from "./useTerminalSurfaceBuffer";
+
+const { createRoot } = NodeModule.createRequire(import.meta.url)("react-dom/client") as {
+ createRoot(container: Element): {
+ render(children: ReactNode): void;
+ unmount(): void;
+ };
+};
+
+type Input = Parameters<typeof useTerminalSurfaceBuffer>[0] & { readonly readOnly: boolean };
+let root: ReturnType<typeof createRoot>;
+const displayed = vi.fn<(value: { buffer: string; readOnly: boolean }) => void>();
+
+function BufferProbe(input: Input) {
+ const buffer = useTerminalSurfaceBuffer(input);
+ useEffect(() => {
+ displayed({ buffer, readOnly: input.readOnly });
+ }, [buffer, input.readOnly]);
+ return null;
+}
+
+function render(changes: Partial<Input> = {}) {
+ return act(() =>
+ root.render(
+ createElement(BufferProbe, {
+ terminalKey: "environment:thread:term-1",
+ buffer: "host output",
+ readOnly: false,
+ ...changes,
+ }),
+ ),
+ );
+}
+
+beforeEach(() => {
+ displayed.mockClear();
+ const document = { nodeType: 9, addEventListener() {}, removeEventListener() {} };
+ const container = {
+ nodeType: 1,
+ tagName: "DIV",
+ namespaceURI: "http://www.w3.org/1999/xhtml",
+ ownerDocument: document,
+ addEventListener() {},
+ removeEventListener() {},
+ };
+ vi.stubGlobal("document", document);
+ vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ root = createRoot(container as unknown as HTMLElement);
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ vi.unstubAllGlobals();
+});
+
+it("preserves displayed history while permissions change before the next snapshot", async () => {
+ await render();
+ await render({ buffer: null, readOnly: true });
+ expect(displayed).toHaveBeenLastCalledWith({ buffer: "host output", readOnly: true });
+
+ await render({ buffer: "host output\nobserved output", readOnly: true });
+ await render({ buffer: null });
+ expect(displayed).toHaveBeenLastCalledWith({
+ buffer: "host output\nobserved output",
+ readOnly: false,
+ });
+ expect(displayed.mock.calls.every(([value]) => value.buffer.length > 0)).toBe(true);
+});
+
+it("still applies an intentional empty buffer", async () => {
+ await render();
+ await render({ buffer: null });
+ expect(displayed).toHaveBeenCalledTimes(1);
+ await render({ buffer: "" });
+ expect(displayed).toHaveBeenLastCalledWith({ buffer: "", readOnly: false });
+});
+
+it.each([
+ "secondary:thread:term-1",
+ "environment:another-thread:term-1",
+ "environment:thread:term-2",
+])("does not carry history into another terminal target (%s)", async (terminalKey) => {
+ await render();
+ await render({ terminalKey, buffer: null });
+ expect(displayed).toHaveBeenLastCalledWith({ buffer: "", readOnly: false });
+ await render({ terminalKey, buffer: "new target" });
+ expect(displayed).toHaveBeenLastCalledWith({ buffer: "new target", readOnly: false });
+});
+
+it("starts empty until its first snapshot arrives", async () => {
+ await render({ buffer: null });
+ expect(displayed).toHaveBeenLastCalledWith({ buffer: "", readOnly: false });
+ await render();
+ expect(displayed).toHaveBeenLastCalledWith({ buffer: "host output", readOnly: false });
+});
diff --git a/apps/mobile/src/features/terminal/useTerminalSurfaceBuffer.ts b/apps/mobile/src/features/terminal/useTerminalSurfaceBuffer.ts
new file mode 100644
index 00000000000..a4fcfd1bf01
--- /dev/null
+++ b/apps/mobile/src/features/terminal/useTerminalSurfaceBuffer.ts
@@ -0,0 +1,17 @@
+import { useState } from "react";
+
+/** A null buffer means the attachment is waiting for its first snapshot. */
+export function useTerminalSurfaceBuffer({
+ terminalKey,
+ buffer,
+}: {
+ readonly terminalKey: string;
+ readonly buffer: string | null;
+}): string {
+ const [snapshot, setSnapshot] = useState({ terminalKey, buffer: buffer ?? "" });
+ const currentBuffer = buffer ?? (snapshot.terminalKey === terminalKey ? snapshot.buffer : "");
+ if (snapshot.terminalKey !== terminalKey || snapshot.buffer !== currentBuffer) {
+ setSnapshot({ terminalKey, buffer: currentBuffer });
+ }
+ return currentBuffer;
+}
diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx
index ccc1e702d46..737a6906b42 100644
--- a/apps/mobile/src/features/threads/ThreadGitControls.tsx
+++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx
@@ -102,6 +102,7 @@ type ThreadGitControlsProps = ThreadGitMenuProps & {
readonly onPress: () => void;
};
readonly canOpenTerminal: boolean;
+ readonly canOperateTerminal: boolean;
readonly canOpenFiles: boolean;
readonly projectScripts: ReadonlyArray<ProjectScript>;
readonly terminalSessions: ReadonlyArray<TerminalMenuSession>;
@@ -287,6 +288,7 @@ function useThreadGitHeaderActionItems(props: ThreadGitControlsProps): ThreadGit
items: [
...props.projectScripts.map((script) => ({
description: script.command,
+ disabled: !props.canOperateTerminal,
icon: { name: projectScriptMenuIcon(script.icon), type: "sfSymbol" as const },
label: projectScriptMenuLabel(script),
onPress: () => void props.onRunProjectScript(script),
@@ -321,6 +323,7 @@ function useThreadGitHeaderActionItems(props: ThreadGitControlsProps): ThreadGit
})),
{
description: "Start another shell for this thread",
+ disabled: !props.canOperateTerminal,
icon: { name: "plus", type: "sfSymbol" },
label: "Open new terminal",
onPress: props.onOpenNewTerminal,
@@ -417,6 +420,7 @@ function useThreadGitHeaderActionItems(props: ThreadGitControlsProps): ThreadGit
model.runQuickAction,
props.canOpenFiles,
props.canOpenTerminal,
+ props.canOperateTerminal,
props.gitStatus,
props.onMergeBack,
props.onOpenNewTerminal,
@@ -474,6 +478,7 @@ export function ThreadGitControls(props: ThreadGitControlsProps) {
<NativeHeaderToolbar.MenuAction
key={script.id}
icon={projectScriptMenuIcon(script.icon)}
+ disabled={!props.canOperateTerminal}
onPress={() => void props.onRunProjectScript(script)}
subtitle={script.command}
>
@@ -512,6 +517,7 @@ export function ThreadGitControls(props: ThreadGitControlsProps) {
))}
<NativeHeaderToolbar.MenuAction
icon="plus"
+ disabled={!props.canOperateTerminal}
onPress={props.onOpenNewTerminal}
subtitle="Start another shell for this thread"
>
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index 02e8724fd3c..9f1e0a9411e 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -16,12 +16,13 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } fro
import * as Option from "effect/Option";
import {
AuthOrchestrationOperateScope,
+ AuthTerminalOperateScope,
+ AuthTerminalReadScope,
DEFAULT_SERVER_SETTINGS,
EnvironmentId,
ThreadId,
type ProjectScript,
} from "@t3tools/contracts";
-import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
import {
projectScriptCwd,
projectScriptRuntimeEnv,
@@ -48,6 +49,8 @@ import {
useRemoteEnvironmentRuntime,
} from "../../state/use-remote-environment-registry";
import { useKnownTerminalSessions } from "../../state/use-terminal-session";
+import { uuidv4 } from "../../lib/uuid";
+import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
import { useThreadSelection } from "../../state/use-thread-selection";
import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
@@ -119,7 +122,7 @@ function ThreadHeader(
onPress: filesVisible ? toggleAuxiliaryPane : props.onOpenFilesInspector,
});
}
- if (props.hasWorkspaceRoot) {
+ if (props.hasWorkspaceRoot && props.gitControls.canOpenTerminal) {
actions.push({
accessibilityLabel: "Open terminal",
icon: "terminal",
@@ -150,6 +153,7 @@ function ThreadHeader(
props.onReturnToThread,
props.hasThreadCwd,
props.hasWorkspaceRoot,
+ props.gitControls.canOpenTerminal,
]);
return (
@@ -339,6 +343,14 @@ function ThreadRouteContent(
selectedThread?.environmentId ?? null,
AuthOrchestrationOperateScope,
);
+ const canReadTerminal = useEnvironmentScope(
+ selectedThread?.environmentId ?? null,
+ AuthTerminalReadScope,
+ );
+ const canOperateTerminal = useEnvironmentScope(
+ selectedThread?.environmentId ?? null,
+ AuthTerminalOperateScope,
+ );
const selectedThreadDetailState = props.selectedThreadDetailState;
const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
const { selectedThreadCwd } = useSelectedThreadWorktree();
@@ -504,14 +516,14 @@ function ThreadRouteContent(
})
: null,
);
- const knownTerminalSessions = useKnownTerminalSessions({
+ const { sessions: knownTerminalSessions } = useKnownTerminalSessions({
environmentId: selectedThread?.environmentId ?? null,
threadId: selectedThread?.id ?? null,
});
const terminalMenuSessions = useMemo(
() =>
buildTerminalMenuSessions({
- knownSessions: knownTerminalSessions,
+ knownSessions: knownTerminalSessions ?? [],
workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
}),
[knownTerminalSessions, selectedThreadProject?.workspaceRoot],
@@ -703,7 +715,12 @@ function ThreadRouteContent(
hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
});
- if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
+ if (
+ !selectedThread ||
+ !selectedThreadProject?.workspaceRoot ||
+ (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) &&
+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope))
+ ) {
return;
}
@@ -723,19 +740,33 @@ function ThreadRouteContent(
listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
});
- if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
+ if (
+ !selectedThread ||
+ !selectedThreadProject?.workspaceRoot ||
+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
+ ) {
return;
}
const nextId = nextOpenTerminalId({
listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
+ ...(knownTerminalSessions === null ||
+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
+ ? { uniqueSuffix: uuidv4() }
+ : {}),
});
void navigation.navigate("ThreadTerminal", {
environmentId: String(selectedThread.environmentId),
threadId: String(selectedThread.id),
terminalId: nextId,
});
- }, [navigation, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]);
+ }, [
+ knownTerminalSessions,
+ navigation,
+ selectedThread,
+ selectedThreadProject?.workspaceRoot,
+ terminalMenuSessions,
+ ]);
const handleRunProjectScript = useCallback(
async (script: ProjectScript) => {
@@ -746,16 +777,24 @@ function ThreadRouteContent(
hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
});
- if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
+ if (
+ !selectedThread ||
+ !selectedThreadProject?.workspaceRoot ||
+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
+ ) {
terminalDebugLog("project-script:abort", {
scriptId: script.id,
- reason: "no-thread-or-workspace",
+ reason: "no-thread-workspace-or-terminal-access",
});
return;
}
const targetTerminalId = resolveProjectScriptTerminalId({
existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
+ ...(knownTerminalSessions === null ||
+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
+ ? { uniqueSuffix: uuidv4() }
+ : {}),
hasRunningTerminal: terminalMenuSessions.some(
(session) => session.status === "running" || session.status === "starting",
),
@@ -804,6 +843,7 @@ function ThreadRouteContent(
selectedThreadDetailWorktreePath,
selectedThreadProject,
terminalMenuSessions,
+ knownTerminalSessions,
],
);
const threadGitControlProps = {
@@ -826,7 +866,9 @@ function ThreadRouteContent(
currentBranch: selectedThread?.branch ?? null,
gitStatus: gitStatus.data,
gitOperationLabel: gitState.gitOperationLabel,
- canOpenTerminal: Boolean(selectedThreadProject?.workspaceRoot),
+ canOpenTerminal:
+ Boolean(selectedThreadProject?.workspaceRoot) && (canReadTerminal || canOperateTerminal),
+ canOperateTerminal,
canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
projectScripts: selectedThreadProject
? resolveProjectScripts(
diff --git a/apps/mobile/src/state/use-terminal-session.ts b/apps/mobile/src/state/use-terminal-session.ts
index 6be57007a60..39cc971fad1 100644
--- a/apps/mobile/src/state/use-terminal-session.ts
+++ b/apps/mobile/src/state/use-terminal-session.ts
@@ -6,11 +6,18 @@ import {
type KnownTerminalSession,
type TerminalSessionState,
} from "@t3tools/client-runtime/state/terminal";
-import { ThreadId, type EnvironmentId, type TerminalAttachInput } from "@t3tools/contracts";
+import {
+ AuthTerminalReadScope,
+ AuthTerminalOperateScope,
+ ThreadId,
+ type EnvironmentId,
+ type TerminalAttachInput,
+} from "@t3tools/contracts";
import { useMemo } from "react";
import { useEnvironmentQuery } from "./query";
import { terminalEnvironment } from "./terminal";
+import { useEnvironmentScope } from "./session";
type LegacyTerminalSessionState = TerminalSessionState & { readonly buffer: string };
const EMPTY_LEGACY_TERMINAL_SESSION_STATE: LegacyTerminalSessionState = {
@@ -22,16 +29,25 @@ export function useAttachedTerminalSession(input: {
readonly environmentId: EnvironmentId | null;
readonly terminal: TerminalAttachInput | null;
}): LegacyTerminalSessionState {
+ const canRead = useEnvironmentScope(input.environmentId, AuthTerminalReadScope);
+ const canOperate = useEnvironmentScope(input.environmentId, AuthTerminalOperateScope);
const attach = useEnvironmentQuery(
input.environmentId !== null && input.terminal !== null
- ? terminalEnvironment.attach({
- environmentId: input.environmentId,
- input: input.terminal,
- })
+ ? canOperate
+ ? terminalEnvironment.attach({
+ environmentId: input.environmentId,
+ input: input.terminal,
+ })
+ : canRead
+ ? terminalEnvironment.observe({
+ environmentId: input.environmentId,
+ input: { threadId: input.terminal.threadId, terminalId: input.terminal.terminalId },
+ })
+ : null
: null,
);
const metadata = useEnvironmentQuery(
- input.environmentId === null
+ input.environmentId === null || !canRead
? null
: terminalEnvironment.metadata({
environmentId: input.environmentId,
@@ -64,20 +80,21 @@ export function useAttachedTerminalSession(input: {
export function useKnownTerminalSessions(input: {
readonly environmentId: EnvironmentId | null;
readonly threadId: ThreadId | null;
-}): ReadonlyArray<KnownTerminalSession> {
+}) {
+ const canRead = useEnvironmentScope(input.environmentId, AuthTerminalReadScope);
const metadata = useEnvironmentQuery(
- input.environmentId === null
+ input.environmentId === null || !canRead
? null
: terminalEnvironment.metadata({
environmentId: input.environmentId,
input: null,
}),
);
- return useMemo(() => {
- if (input.environmentId === null) {
- return [];
+ const sessions = useMemo((): ReadonlyArray<KnownTerminalSession> | null => {
+ if (input.environmentId === null || metadata.data === null || metadata.error !== null) {
+ return null;
}
- return (metadata.data ?? [])
+ return metadata.data
.filter((summary) => input.threadId === null || summary.threadId === input.threadId)
.map((summary) => ({
target: {
@@ -92,5 +109,6 @@ export function useKnownTerminalSessions(input: {
numeric: true,
}),
);
- }, [input.environmentId, input.threadId, metadata.data]);
+ }, [input.environmentId, input.threadId, metadata.data, metadata.error]);
+ return { sessions, isPending: metadata.isPending, error: metadata.error };
}
diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts
index a40489bea61..70cd809b70a 100644
--- a/apps/server/src/auth/RpcAuthorization.test.ts
+++ b/apps/server/src/auth/RpcAuthorization.test.ts
@@ -13,6 +13,8 @@ import {
AuthPreviewOperateScope,
AuthRelayReadScope,
AuthRelayWriteScope,
+ AuthTerminalReadScope,
+ AuthTerminalOperateScope,
WS_METHODS,
WsRpcGroup,
} from "@t3tools/contracts";
@@ -162,6 +164,27 @@ describe("RPC authorization scopes", () => {
}
});
+ it("separates passive terminal observation from operations that can change a shell", () => {
+ for (const method of [
+ WS_METHODS.terminalObserve,
+ WS_METHODS.subscribeTerminalEvents,
+ WS_METHODS.subscribeTerminalMetadata,
+ ]) {
+ expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalReadScope);
+ }
+ for (const method of [
+ WS_METHODS.terminalAttach,
+ WS_METHODS.terminalOpen,
+ WS_METHODS.terminalWrite,
+ WS_METHODS.terminalResize,
+ WS_METHODS.terminalClear,
+ WS_METHODS.terminalRestart,
+ WS_METHODS.terminalClose,
+ ]) {
+ expect(requiredScopeForRpcMethod(method)).toBe(AuthTerminalOperateScope);
+ }
+ });
+
it("rejects unknown RPC method names", () => {
for (const method of ["server.notRegistered", "toString", "constructor"]) {
expect(() => requiredScopeForRpcMethod(method)).toThrow(
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index 63f282ec9e5..b4b96f2f57c 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -20,6 +20,7 @@ import {
AuthRelayWriteScope,
AuthTerminalOperateScope,
ORCHESTRATION_V2_WS_METHODS,
+ AuthTerminalReadScope,
type AuthEnvironmentScope,
EnvironmentAuthorizationError,
RpcScopeAuthorization,
@@ -164,13 +165,14 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.reviewGetDiffFileContents]: AuthFilesystemReadScope,
[WS_METHODS.terminalOpen]: AuthTerminalOperateScope,
[WS_METHODS.terminalAttach]: AuthTerminalOperateScope,
+ [WS_METHODS.terminalObserve]: AuthTerminalReadScope,
[WS_METHODS.terminalWrite]: AuthTerminalOperateScope,
[WS_METHODS.terminalResize]: AuthTerminalOperateScope,
[WS_METHODS.terminalClear]: AuthTerminalOperateScope,
[WS_METHODS.terminalRestart]: AuthTerminalOperateScope,
[WS_METHODS.terminalClose]: AuthTerminalOperateScope,
- [WS_METHODS.subscribeTerminalEvents]: AuthTerminalOperateScope,
- [WS_METHODS.subscribeTerminalMetadata]: AuthTerminalOperateScope,
+ [WS_METHODS.subscribeTerminalEvents]: AuthTerminalReadScope,
+ [WS_METHODS.subscribeTerminalMetadata]: AuthTerminalReadScope,
[WS_METHODS.previewOpen]: AuthPreviewOperateScope,
[WS_METHODS.previewNavigate]: AuthPreviewOperateScope,
[WS_METHODS.previewResize]: AuthPreviewOperateScope,
diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts
index f38e1aeff1d..f0f51f3d969 100644
--- a/apps/server/src/observability/RpcInstrumentation.ts
+++ b/apps/server/src/observability/RpcInstrumentation.ts
@@ -161,6 +161,7 @@ const RPC_AGGREGATES = {
[WS_METHODS.reviewGetDiffFileContents]: "review",
[WS_METHODS.terminalOpen]: "terminal",
[WS_METHODS.terminalAttach]: "terminal",
+ [WS_METHODS.terminalObserve]: "terminal",
[WS_METHODS.terminalWrite]: "terminal",
[WS_METHODS.terminalResize]: "terminal",
[WS_METHODS.terminalClear]: "terminal",
diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts
index ad763bff2f8..5a493cc2805 100644
--- a/apps/server/src/terminal/Manager.test.ts
+++ b/apps/server/src/terminal/Manager.test.ts
@@ -2693,6 +2693,104 @@ it.layer(
}),
);
+ it.effect("observes terminal history and live output without changing the process", () =>
+ Effect.gen(function* () {
+ const { manager, ptyAdapter } = yield* createManager();
+ const opened = yield* manager.open(openInput({ env: { OBSERVER_TEST: "original" } }));
+ const process = ptyAdapter.processes[0]!;
+ const historyReceived = yield* Deferred.make<void>();
+ const unsubscribeHistory = yield* manager.subscribe((event) =>
+ event.type === "output"
+ ? Deferred.succeed(historyReceived, undefined).pipe(Effect.asVoid)
+ : Effect.void,
+ );
+ process.emitData("existing history\n");
+ yield* Deferred.await(historyReceived);
+ unsubscribeHistory();
+
+ const observed = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
+ const liveReceived = yield* Deferred.make<void>();
+ const unsubscribe = yield* manager.observeStream(
+ { threadId: opened.threadId, terminalId: opened.terminalId },
+ (event) =>
+ Ref.update(observed, (events) => [...events, event]).pipe(
+ Effect.andThen(
+ event.type === "output"
+ ? Deferred.succeed(liveReceived, undefined).pipe(Effect.asVoid)
+ : Effect.void,
+ ),
+ ),
+ );
+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
+ process.emitData("live output\n");
+ yield* Deferred.await(liveReceived);
+
+ expect(yield* Ref.get(observed)).toMatchObject([
+ {
+ type: "snapshot",
+ snapshot: {
+ cwd: opened.cwd,
+ worktreePath: opened.worktreePath,
+ pid: opened.pid,
+ history: "existing history\n",
+ },
+ },
+ { type: "output", data: "live output\n" },
+ ]);
+ expect(ptyAdapter.spawnInputs).toHaveLength(1);
+ expect(ptyAdapter.spawnInputs[0]?.env.OBSERVER_TEST).toBe("original");
+ expect(process.resizeCalls).toEqual([]);
+ expect(process.writes).toEqual([]);
+ expect(process.killSignals).toEqual([]);
+ }),
+ );
+
+ it.effect("observes exited terminals without restarting and rejects missing sessions", () =>
+ Effect.gen(function* () {
+ const { manager, ptyAdapter } = yield* createManager();
+ const missingEvents: TerminalAttachStreamEvent[] = [];
+ const missing = yield* manager
+ .observeStream({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID }, (event) =>
+ Effect.sync(() => {
+ missingEvents.push(event);
+ }),
+ )
+ .pipe(Effect.flip);
+ expect(missing._tag).toBe("TerminalSessionLookupError");
+ expect(ptyAdapter.spawnInputs).toEqual([]);
+
+ yield* manager.open(openInput());
+ const process = ptyAdapter.processes[0]!;
+ const exited = yield* Deferred.make<void>();
+ const unsubscribeExit = yield* manager.subscribe((event) =>
+ event.type === "exited"
+ ? Deferred.succeed(exited, undefined).pipe(Effect.asVoid)
+ : Effect.void,
+ );
+ process.emitExit({ exitCode: 7, signal: 0 });
+ yield* Deferred.await(exited);
+ unsubscribeExit();
+
+ const events: TerminalAttachStreamEvent[] = [];
+ const unsubscribe = yield* manager.observeStream(
+ { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID },
+ (event) =>
+ Effect.sync(() => {
+ events.push(event);
+ }),
+ );
+ unsubscribe();
+ expect(events).toMatchObject([
+ { type: "snapshot", snapshot: { status: "exited", exitCode: 7, pid: null } },
+ ]);
+ expect(ptyAdapter.spawnInputs).toHaveLength(1);
+ expect(process.resizeCalls).toEqual([]);
+ expect(process.writes).toEqual([]);
+ expect(process.killSignals).toEqual([]);
+ expect(missingEvents).toEqual([]);
+ }),
+ );
+
it.effect("buffers attach output delivered during the initial snapshot callback", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager(5, {
diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts
index f1807f2d99d..3c71a884947 100644
--- a/apps/server/src/terminal/Manager.ts
+++ b/apps/server/src/terminal/Manager.ts
@@ -28,6 +28,7 @@ import {
type TerminalEvent,
type TerminalMetadataStreamEvent,
type TerminalOpenInput,
+ type TerminalObserveInput,
type TerminalResizeInput,
type ResourceMonitorProcessTableEntry,
type TerminalRestartInput,
@@ -170,6 +171,12 @@ export class TerminalManager extends Context.Service<
listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
) => Effect.Effect<() => void, TerminalError>;
+ /** Observe an existing session without starting or changing its process. */
+ readonly observeStream: (
+ input: TerminalObserveInput,
+ listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
+ ) => Effect.Effect<() => void, TerminalError>;
+
/**
* Write input bytes to a terminal session.
*/
@@ -2787,7 +2794,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
};
});
- const attachStream: TerminalManager["Service"]["attachStream"] = (input, listener) => {
+ const streamSession = (
+ input: TerminalObserveInput,
+ initial: Effect.Effect<TerminalSessionSnapshot, TerminalError>,
+ listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
+ ) => {
let unsubscribe: (() => void) | null = null;
return Effect.gen(function* () {
@@ -2808,7 +2819,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
return attachEvent ? listener(attachEvent) : Effect.void;
});
- const initialSnapshot = yield* openOrAttachForStream(input);
+ const initialSnapshot = yield* initial;
yield* listener({
type: "snapshot",
@@ -2844,6 +2855,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
);
};
+ const attachStream: TerminalManager["Service"]["attachStream"] = (input, listener) =>
+ streamSession(input, openOrAttachForStream(input), listener);
+
+ const observeStream: TerminalManager["Service"]["observeStream"] = (input, listener) =>
+ streamSession(
+ input,
+ withThreadLock(
+ input.threadId,
+ requireSession(input.threadId, input.terminalId).pipe(Effect.map(snapshot)),
+ ),
+ listener,
+ );
+
const metadataEventFromTerminalEvent = (
event: TerminalEvent,
): Effect.Effect<TerminalMetadataStreamEvent | null> => {
@@ -3153,6 +3177,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
return TerminalManager.of({
open,
attachStream,
+ observeStream,
write,
resize,
clear,
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index ad1b9815acc..4cba3fca019 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -2840,13 +2840,20 @@ const layerWsRpc = (
Effect.acquireRelease(
terminalManager.attachStream(input, (event) => Queue.offer(queue, event)),
(unsubscribe) => Effect.sync(unsubscribe),
- ),
+ ).pipe(Effect.catchCause((cause) => Queue.failCause(queue, cause))),
),
[WS_METHODS.terminalWrite]: (input) => terminalManager.write(input),
[WS_METHODS.terminalResize]: (input) => terminalManager.resize(input),
[WS_METHODS.terminalClear]: (input) => terminalManager.clear(input),
[WS_METHODS.terminalRestart]: (input) => terminalManager.restart(input),
[WS_METHODS.terminalClose]: (input) => terminalManager.close(input),
+ [WS_METHODS.terminalObserve]: (input) =>
+ Stream.callback<TerminalAttachStreamEvent, TerminalError>((queue) =>
+ Effect.acquireRelease(
+ terminalManager.observeStream(input, (event) => Queue.offer(queue, event)),
+ (unsubscribe) => Effect.sync(unsubscribe),
+ ).pipe(Effect.catchCause((cause) => Queue.failCause(queue, cause))),
+ ),
[WS_METHODS.subscribeTerminalEvents]: (_input) =>
Stream.callback<TerminalEvent>((queue) =>
Effect.acquireRelease(
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 0e62851bfc8..7fdc5e98a47 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -52,6 +52,8 @@ import {
AuthSettingsWriteScope,
AuthSourceControlWriteScope,
AuthPreviewOperateScope,
+ AuthTerminalReadScope,
+ AuthTerminalOperateScope,
type AssistantCitation,
type ChatFileAttachment,
CommandId,
@@ -980,6 +982,11 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
keybindings,
onAddTerminalContext,
}: PersistentThreadTerminalDrawerProps) {
+ const canOperateTerminal = useEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope);
+ const hasTerminalWriteAccess = useCallback(
+ () => readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope),
+ [threadRef.environmentId],
+ );
const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");
const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close");
@@ -1013,7 +1020,9 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
);
const drawerTerminalSessions = useMemo(
() =>
- knownTerminalSessions.filter((session) => !panelTerminalIds.has(session.target.terminalId)),
+ knownTerminalSessions?.filter(
+ (session) => !panelTerminalIds.has(session.target.terminalId),
+ ) ?? [],
[knownTerminalSessions, panelTerminalIds],
);
const terminalLabelsById = useMemo(() => {
@@ -1075,6 +1084,17 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
],
[panelTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds],
);
+ const allocateTerminalId = useCallback(
+ () =>
+ nextTerminalId(
+ allocatableTerminalIds,
+ knownTerminalSessions === null ||
+ !readEnvironmentScope(threadRef.environmentId, AuthTerminalReadScope)
+ ? randomUUID()
+ : undefined,
+ ),
+ [allocatableTerminalIds, knownTerminalSessions, threadRef.environmentId],
+ );
const storeSetTerminalHeight = useTerminalUiStateStore((state) => state.setTerminalHeight);
const storeSplitTerminal = useTerminalUiStateStore((state) => state.splitTerminal);
const storeSplitTerminalVertical = useTerminalUiStateStore(
@@ -1141,10 +1161,10 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
);
const splitTerminal = useCallback(() => {
- if (!cwd) {
+ if (!hasTerminalWriteAccess() || !cwd) {
return;
}
- const terminalId = nextTerminalId(allocatableTerminalIds);
+ const terminalId = allocateTerminalId();
storeSplitTerminal(threadRef, terminalId);
bumpFocusRequestId();
void openTerminal({
@@ -1158,7 +1178,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
},
});
}, [
- allocatableTerminalIds,
+ allocateTerminalId,
bumpFocusRequestId,
cwd,
effectiveWorktreePath,
@@ -1167,12 +1187,13 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
threadId,
threadRef,
openTerminal,
+ hasTerminalWriteAccess,
]);
const splitTerminalVertical = useCallback(() => {
- if (!cwd) {
+ if (!hasTerminalWriteAccess() || !cwd) {
return;
}
- const terminalId = nextTerminalId(allocatableTerminalIds);
+ const terminalId = allocateTerminalId();
storeSplitTerminalVertical(threadRef, terminalId);
bumpFocusRequestId();
void openTerminal({
@@ -1186,11 +1207,12 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
},
});
}, [
- allocatableTerminalIds,
+ allocateTerminalId,
bumpFocusRequestId,
cwd,
effectiveWorktreePath,
openTerminal,
+ hasTerminalWriteAccess,
runtimeEnv,
storeSplitTerminalVertical,
threadId,
@@ -1198,10 +1220,10 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
]);
const createNewTerminal = useCallback(() => {
- if (!cwd) {
+ if (!hasTerminalWriteAccess() || !cwd) {
return;
}
- const terminalId = nextTerminalId(allocatableTerminalIds);
+ const terminalId = allocateTerminalId();
storeNewTerminal(threadRef, terminalId);
bumpFocusRequestId();
void openTerminal({
@@ -1218,12 +1240,13 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
bumpFocusRequestId,
cwd,
effectiveWorktreePath,
- allocatableTerminalIds,
+ allocateTerminalId,
runtimeEnv,
storeNewTerminal,
threadId,
threadRef,
openTerminal,
+ hasTerminalWriteAccess,
]);
const activateTerminal = useCallback(
@@ -1236,6 +1259,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
const closeTerminal = useCallback(
(terminalId: string) => {
+ if (!hasTerminalWriteAccess()) return;
const fallbackExitWrite = () =>
writeTerminal({
environmentId: threadRef.environmentId,
@@ -1251,7 +1275,11 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
deleteHistory: true,
},
});
- if (closeResult._tag === "Failure" && !isAtomCommandInterrupted(closeResult)) {
+ if (
+ closeResult._tag === "Failure" &&
+ !isAtomCommandInterrupted(closeResult) &&
+ hasTerminalWriteAccess()
+ ) {
await fallbackExitWrite();
}
})();
@@ -1265,6 +1293,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
threadId,
threadRef,
closeTerminalMutation,
+ hasTerminalWriteAccess,
writeTerminal,
],
);
@@ -1303,7 +1332,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
visible={visible}
height={terminalUiState.terminalHeight}
// Known-session order is MRU and changes on focus; persisted store order keeps sidebar labels stable.
- terminalIds={terminalUiState.terminalIds}
+ terminalIds={canOperateTerminal ? terminalUiState.terminalIds : serverOrderedTerminalIds}
activeTerminalId={terminalUiState.activeTerminalId}
terminalGroups={terminalUiState.terminalGroups}
activeTerminalGroupId={terminalUiState.activeTerminalGroupId}
@@ -1379,7 +1408,7 @@ const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPane
});
const threadWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
const activeSummary =
- knownTerminalSessions.find((session) => session.target.terminalId === surface.activeTerminalId)
+ knownTerminalSessions?.find((session) => session.target.terminalId === surface.activeTerminalId)
?.state.summary ?? null;
const worktreePath =
launchContext?.worktreePath ?? activeSummary?.worktreePath ?? threadWorktreePath;
@@ -1409,7 +1438,7 @@ const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPane
const labels = new Map<string, string>();
for (const terminalId of surface.terminalIds) {
const summary =
- knownTerminalSessions.find((session) => session.target.terminalId === terminalId)?.state
+ knownTerminalSessions?.find((session) => session.target.terminalId === terminalId)?.state
.summary ?? null;
labels.set(terminalId, resolveTerminalSessionLabel(terminalId, summary));
}
@@ -1426,7 +1455,7 @@ const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPane
>();
for (const terminalId of surface.terminalIds) {
const summary =
- knownTerminalSessions.find((session) => session.target.terminalId === terminalId)?.state
+ knownTerminalSessions?.find((session) => session.target.terminalId === terminalId)?.state
.summary ?? null;
const terminalWorktreePath =
launchContext?.worktreePath ?? summary?.worktreePath ?? threadWorktreePath;
@@ -1544,6 +1573,12 @@ export default function ChatView(props: ChatViewProps) {
forceExpandedMobileComposer = false,
} = props;
const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
+ const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
+ const hasTerminalWriteAccess = useCallback(
+ () => readEnvironmentScope(environmentId, AuthTerminalOperateScope),
+ [environmentId],
+ );
+ const canReadTerminal = useEnvironmentScope(environmentId, AuthTerminalReadScope);
const draftId = routeKind === "draft" ? props.draftId : null;
const handleNewThread = useNewThreadHandler();
const { settleThread, pinThread, confirmAndUnpinThread } = useThreadActions();
@@ -2180,7 +2215,7 @@ export default function ChatView(props: ChatViewProps) {
threadId: activeThreadId,
});
const activeThreadKnownSessions = useMemo(() => {
- if (activeThreadId === null) {
+ if (activeThreadId === null || activeThreadKnownSessionsRaw === null) {
return [];
}
return activeThreadKnownSessionsRaw.filter(
@@ -2301,6 +2336,17 @@ export default function ChatView(props: ChatViewProps) {
() => [...new Set([...activeKnownTerminalIds, ...panelTerminalIds])],
[activeKnownTerminalIds, panelTerminalIds],
);
+ const canReuseTerminal = activeThreadKnownSessionsRaw !== null;
+ const allocateTerminalId = useCallback(
+ () =>
+ nextTerminalId(
+ allocatableActiveTerminalIds,
+ canReuseTerminal && readEnvironmentScope(environmentId, AuthTerminalReadScope)
+ ? undefined
+ : randomUUID(),
+ ),
+ [allocatableActiveTerminalIds, canReuseTerminal, environmentId],
+ );
const previewPanelOpen = activeRightPanelKind === "preview" && browserAvailable;
const rightPanelOpen = rightPanelState.isOpen;
const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
@@ -4696,7 +4742,13 @@ export default function ChatView(props: ChatViewProps) {
const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadRef) return;
const nextOpen = !terminalUiState.terminalOpen;
- if (nextOpen && terminalUiState.terminalIds.length === 0) {
+ if (
+ nextOpen &&
+ !readEnvironmentScope(environmentId, AuthTerminalReadScope) &&
+ !hasTerminalWriteAccess()
+ )
+ return;
+ if (nextOpen && hasTerminalWriteAccess() && terminalUiState.terminalIds.length === 0) {
if (!activeThreadId || !activeProject) {
return;
}
@@ -4704,7 +4756,7 @@ export default function ChatView(props: ChatViewProps) {
if (!cwdForOpen) {
return;
}
- const terminalId = nextTerminalId(allocatableActiveTerminalIds);
+ const terminalId = allocateTerminalId();
storeEnsureTerminal(activeThreadRef, terminalId, { open: true });
void openTerminal({
environmentId,
@@ -4727,10 +4779,11 @@ export default function ChatView(props: ChatViewProps) {
activeThreadId,
activeThreadRef,
activeThreadWorktreePath,
- allocatableActiveTerminalIds,
+ allocateTerminalId,
environmentId,
gitCwd,
openTerminal,
+ hasTerminalWriteAccess,
setTerminalOpen,
storeEnsureTerminal,
terminalUiState.terminalIds.length,
@@ -4738,14 +4791,20 @@ export default function ChatView(props: ChatViewProps) {
]);
const splitTerminal = useCallback(
(direction: "horizontal" | "vertical" = "horizontal") => {
- if (!activeThreadRef || hasReachedSplitLimit || !activeThreadId || !activeProject) {
+ if (
+ !hasTerminalWriteAccess() ||
+ !activeThreadRef ||
+ hasReachedSplitLimit ||
+ !activeThreadId ||
+ !activeProject
+ ) {
return;
}
const cwdForOpen = gitCwd ?? activeProject.workspaceRoot;
if (!cwdForOpen) {
return;
}
- const terminalId = nextTerminalId(allocatableActiveTerminalIds);
+ const terminalId = allocateTerminalId();
if (direction === "vertical") {
storeSplitTerminalVertical(activeThreadRef, terminalId);
} else {
@@ -4769,9 +4828,10 @@ export default function ChatView(props: ChatViewProps) {
[
activeProject,
activeThreadId,
- allocatableActiveTerminalIds,
+ allocateTerminalId,
activeThreadRef,
openTerminal,
+ hasTerminalWriteAccess,
activeThreadWorktreePath,
environmentId,
gitCwd,
@@ -4781,14 +4841,14 @@ export default function ChatView(props: ChatViewProps) {
],
);
const createNewTerminal = useCallback(() => {
- if (!activeThreadRef || !activeThreadId || !activeProject) {
+ if (!hasTerminalWriteAccess() || !activeThreadRef || !activeThreadId || !activeProject) {
return;
}
const cwdForOpen = gitCwd ?? activeProject.workspaceRoot;
if (!cwdForOpen) {
return;
}
- const terminalId = nextTerminalId(allocatableActiveTerminalIds);
+ const terminalId = allocateTerminalId();
storeNewTerminal(activeThreadRef, terminalId);
setTerminalFocusRequestId((value) => value + 1);
void openTerminal({
@@ -4807,9 +4867,10 @@ export default function ChatView(props: ChatViewProps) {
}, [
activeProject,
activeThreadId,
- allocatableActiveTerminalIds,
+ allocateTerminalId,
activeThreadRef,
openTerminal,
+ hasTerminalWriteAccess,
activeThreadWorktreePath,
environmentId,
gitCwd,
@@ -4817,7 +4878,7 @@ export default function ChatView(props: ChatViewProps) {
]);
const closeTerminal = useCallback(
(terminalId: string) => {
- if (!activeThreadId || !activeThreadRef) return;
+ if (!hasTerminalWriteAccess() || !activeThreadId || !activeThreadRef) return;
const fallbackExitWrite = () =>
writeTerminal({
environmentId,
@@ -4832,7 +4893,11 @@ export default function ChatView(props: ChatViewProps) {
deleteHistory: true,
},
});
- if (closeResult._tag === "Failure" && !isAtomCommandInterrupted(closeResult)) {
+ if (
+ closeResult._tag === "Failure" &&
+ !isAtomCommandInterrupted(closeResult) &&
+ hasTerminalWriteAccess()
+ ) {
await fallbackExitWrite();
}
})();
@@ -4843,6 +4908,7 @@ export default function ChatView(props: ChatViewProps) {
activeThreadId,
activeThreadRef,
closeTerminalMutation,
+ hasTerminalWriteAccess,
environmentId,
storeCloseTerminal,
writeTerminal,
@@ -4859,7 +4925,7 @@ export default function ChatView(props: ChatViewProps) {
rememberAsLastInvoked?: boolean;
},
) => {
- if (!activeThreadId || !activeProject || !activeThread) return;
+ if (!hasTerminalWriteAccess() || !activeThreadId || !activeProject || !activeThread) return;
if (options?.rememberAsLastInvoked !== false) {
setLastInvokedScriptByProjectId((current) => {
if (current[activeProject.id] === script.id) return current;
@@ -4871,7 +4937,10 @@ export default function ChatView(props: ChatViewProps) {
terminalUiState.activeTerminalId || activeKnownTerminalIds[0] || DEFAULT_THREAD_TERMINAL_ID;
const isBaseTerminalBusy = runningTerminalIds.includes(baseTerminalId);
const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;
- const shouldCreateNewTerminal = wantsNewTerminal;
+ const shouldCreateNewTerminal =
+ wantsNewTerminal ||
+ !canReuseTerminal ||
+ !readEnvironmentScope(environmentId, AuthTerminalReadScope);
const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null;
setTerminalUiLaunchContext({
@@ -4892,9 +4961,7 @@ export default function ChatView(props: ChatViewProps) {
worktreePath: targetWorktreePath,
...(options?.env ? { extraEnv: options.env } : {}),
});
- const targetTerminalId = shouldCreateNewTerminal
- ? nextTerminalId(allocatableActiveTerminalIds)
- : baseTerminalId;
+ const targetTerminalId = shouldCreateNewTerminal ? allocateTerminalId() : baseTerminalId;
const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal
? {
threadId: activeThreadId,
@@ -4931,6 +4998,7 @@ export default function ChatView(props: ChatViewProps) {
return;
}
+ if (!hasTerminalWriteAccess()) return;
const writeResult = await writeTerminal({
environmentId,
input: {
@@ -4981,8 +5049,10 @@ export default function ChatView(props: ChatViewProps) {
environmentId,
openTerminal,
openPreview,
+ hasTerminalWriteAccess,
activeKnownTerminalIds,
- allocatableActiveTerminalIds,
+ canReuseTerminal,
+ allocateTerminalId,
runningTerminalIds,
terminalUiState.activeTerminalId,
writeTerminal,
@@ -5792,9 +5862,9 @@ export default function ChatView(props: ChatViewProps) {
previewPanelOpen,
]);
const addTerminalSurface = useCallback(() => {
- if (!activeThreadRef || !activeThreadId || !activeProject) return;
+ if (!hasTerminalWriteAccess() || !activeThreadRef || !activeThreadId || !activeProject) return;
const cwd = gitCwd ?? activeProject.workspaceRoot;
- const terminalId = nextTerminalId(allocatableActiveTerminalIds);
+ const terminalId = allocateTerminalId();
useRightPanelStore.getState().openTerminal(activeThreadRef, terminalId);
setTerminalFocusRequestId((value) => value + 1);
void openTerminal({
@@ -5815,13 +5885,15 @@ export default function ChatView(props: ChatViewProps) {
activeThreadId,
activeThreadRef,
activeThreadWorktreePath,
- allocatableActiveTerminalIds,
+ allocateTerminalId,
gitCwd,
openTerminal,
+ hasTerminalWriteAccess,
]);
const splitPanelTerminal = useCallback(
(direction: "horizontal" | "vertical" = "horizontal") => {
if (
+ !hasTerminalWriteAccess() ||
!activeThreadRef ||
!activeThreadId ||
!activeProject ||
@@ -5830,7 +5902,7 @@ export default function ChatView(props: ChatViewProps) {
) {
return;
}
- const terminalId = nextTerminalId(allocatableActiveTerminalIds);
+ const terminalId = allocateTerminalId();
const cwd = gitCwd ?? activeProject.workspaceRoot;
useRightPanelStore
.getState()
@@ -5856,9 +5928,10 @@ export default function ChatView(props: ChatViewProps) {
activeThreadId,
activeThreadRef,
activeThreadWorktreePath,
- allocatableActiveTerminalIds,
+ allocateTerminalId,
gitCwd,
openTerminal,
+ hasTerminalWriteAccess,
],
);
const splitPanelTerminalVertical = useCallback(() => {
@@ -5876,7 +5949,12 @@ export default function ChatView(props: ChatViewProps) {
);
const closePanelTerminal = useCallback(
(terminalId: string) => {
- if (!activeThreadRef || activeRightPanelSurface?.kind !== "terminal") return;
+ if (
+ !hasTerminalWriteAccess() ||
+ !activeThreadRef ||
+ activeRightPanelSurface?.kind !== "terminal"
+ )
+ return;
void closeTerminalMutation({
environmentId: activeThreadRef.environmentId,
input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true },
@@ -5887,25 +5965,37 @@ export default function ChatView(props: ChatViewProps) {
.closeTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);
setTerminalFocusRequestId((value) => value + 1);
},
- [activeRightPanelSurface, activeThreadRef, closeTerminalMutation, storeCloseTerminal],
+ [
+ hasTerminalWriteAccess,
+ activeRightPanelSurface,
+ activeThreadRef,
+ closeTerminalMutation,
+ storeCloseTerminal,
+ ],
);
const requestCloseTerminal = useCallback(
(terminalId: string) => {
+ if (!hasTerminalWriteAccess()) return;
const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
void confirmTerminalClose([label]).then((confirmed) => {
- if (confirmed) closeTerminal(terminalId);
+ if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
+ closeTerminal(terminalId);
+ }
});
},
- [activeTerminalLabelsById, closeTerminal],
+ [hasTerminalWriteAccess, activeTerminalLabelsById, closeTerminal, environmentId],
);
const requestClosePanelTerminal = useCallback(
(terminalId: string) => {
+ if (!hasTerminalWriteAccess()) return;
const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
void confirmTerminalClose([label]).then((confirmed) => {
- if (confirmed) closePanelTerminal(terminalId);
+ if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
+ closePanelTerminal(terminalId);
+ }
});
},
- [activeTerminalLabelsById, closePanelTerminal],
+ [hasTerminalWriteAccess, activeTerminalLabelsById, closePanelTerminal, environmentId],
);
const activateRightPanelSurface = useCallback(
(surface: RightPanelSurface) => {
@@ -5956,7 +6046,10 @@ export default function ChatView(props: ChatViewProps) {
threadRef: activeThreadRef,
});
}
- if (surface.kind === "terminal") {
+ if (
+ surface.kind === "terminal" &&
+ readEnvironmentScope(activeThreadRef.environmentId, AuthTerminalOperateScope)
+ ) {
for (const terminalId of surface.terminalIds) {
storeCloseTerminal(activeThreadRef, terminalId);
void closeTerminalMutation({
@@ -6034,7 +6127,10 @@ export default function ChatView(props: ChatViewProps) {
closeAfterAgentBrowserConfirmation([surface], finishClose);
return;
}
- if (surface.kind !== "terminal") {
+ if (
+ surface.kind !== "terminal" ||
+ !readEnvironmentScope(activeThreadRef.environmentId, AuthTerminalOperateScope)
+ ) {
finishClose();
return;
}
@@ -6047,7 +6143,9 @@ export default function ChatView(props: ChatViewProps) {
(terminalId) => activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId),
);
void confirmTerminalClose([activeLabel, ...otherLabels]).then((confirmed) => {
- if (confirmed) finishClose();
+ if (confirmed) {
+ finishClose();
+ }
});
},
[
@@ -7963,6 +8061,7 @@ export default function ChatView(props: ChatViewProps) {
}
if (command === "terminal.toggle") {
+ if (!terminalUiState.terminalOpen && !canReadTerminal && !canOperateTerminal) return;
event.preventDefault();
event.stopPropagation();
toggleTerminalVisibility();
@@ -7994,6 +8093,9 @@ export default function ChatView(props: ChatViewProps) {
}
if (command === "terminal.split") {
+ // Without operate access the key keeps its native meaning, as it
+ // does when nothing is open.
+ if (!canOperateTerminal) return;
event.preventDefault();
event.stopPropagation();
if (terminalFocusOwner === "right-panel") {
@@ -8008,6 +8110,9 @@ export default function ChatView(props: ChatViewProps) {
}
if (command === "terminal.splitVertical") {
+ // Without operate access the key keeps its native meaning, as it
+ // does when nothing is open.
+ if (!canOperateTerminal) return;
event.preventDefault();
event.stopPropagation();
if (terminalFocusOwner === "right-panel") {
@@ -8022,6 +8127,9 @@ export default function ChatView(props: ChatViewProps) {
}
if (command === "terminal.close") {
+ // Without operate access the key keeps its native meaning, as it
+ // does when nothing is open.
+ if (!canOperateTerminal) return;
event.preventDefault();
event.stopPropagation();
if (terminalFocusOwner === "right-panel" && activeRightPanelSurface?.kind === "terminal") {
@@ -8034,6 +8142,9 @@ export default function ChatView(props: ChatViewProps) {
}
if (command === "terminal.new") {
+ // Without operate access the key keeps its native meaning, as it
+ // does when nothing is open.
+ if (!canOperateTerminal) return;
event.preventDefault();
event.stopPropagation();
if (terminalFocusOwner === "right-panel") {
@@ -8132,7 +8243,7 @@ export default function ChatView(props: ChatViewProps) {
}
const scriptId = projectScriptIdFromCommand(command);
- if (!scriptId || !activeProject) return;
+ if (!scriptId || !activeProject || !canOperateTerminal) return;
const script = activeProjectScripts.find((entry) => entry.id === scriptId);
if (!script) return;
event.preventDefault();
@@ -8145,6 +8256,8 @@ export default function ChatView(props: ChatViewProps) {
activeProject,
activeRightPanelSurface,
activeProjectScripts,
+ canReadTerminal,
+ canOperateTerminal,
addTerminalSurface,
activeThreadRef,
activeThreadPinned,
@@ -11769,7 +11882,7 @@ export default function ChatView(props: ChatViewProps) {
onAddPullRequests={addPullRequestsSurface}
onAddDevice={addDeviceSurface}
browserAvailable={canOperatePreview && browserAvailable}
- terminalAvailable={activeProject !== null}
+ terminalAvailable={activeProject !== null && canOperateTerminal}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
pullRequestAvailable={pullRequestSurfaceAvailable}
@@ -11827,7 +11940,7 @@ export default function ChatView(props: ChatViewProps) {
onAddPullRequests={addPullRequestsSurface}
onAddDevice={addDeviceSurface}
browserAvailable={canOperatePreview && browserAvailable}
- terminalAvailable={activeProject !== null}
+ terminalAvailable={activeProject !== null && canOperateTerminal}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
pullRequestAvailable={pullRequestSurfaceAvailable}
diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx
index b1f6bf6d6bd..c51be069434 100644
--- a/apps/web/src/components/ProjectScriptsControl.tsx
+++ b/apps/web/src/components/ProjectScriptsControl.tsx
@@ -66,7 +66,7 @@ interface ProjectScriptsControlProps {
/** Scripts declared in the project's checked-in t3.json, offered for import. */
fileScripts?: ReadonlyArray<T3ProjectFileScript>;
preferredScriptId?: string | null;
- onRunScript: (script: ProjectScript) => void;
+ onRunScript?: ((script: ProjectScript) => void) | undefined;
onAddScript: (input: NewProjectScriptInput) => Promise<ProjectScriptActionResult>;
onUpdateScript: (
scriptId: string,
@@ -198,7 +198,8 @@ export default function ProjectScriptsControl({
density={presentation === "menu" ? "touch" : "default"}
key={script.id}
className="group"
- onClick={() => onRunScript(script)}
+ disabled={!onRunScript}
+ onClick={() => onRunScript?.(script)}
>
<ScriptIcon icon={script.icon} className="size-4" />
<MenuItemLabel>
@@ -255,7 +256,8 @@ export default function ProjectScriptsControl({
{primaryScript && (
<MenuItem
density={presentation === "menu" ? "touch" : "default"}
- onClick={() => onRunScript(primaryScript)}
+ disabled={!onRunScript}
+ onClick={() => onRunScript?.(primaryScript)}
>
<ScriptIcon icon={primaryScript.icon} className="size-4" />
<MenuItemLabel>Run {primaryScript.name}</MenuItemLabel>
@@ -308,7 +310,8 @@ export default function ProjectScriptsControl({
// The tooltip wrapper replaces data-slot="button", so themed
// toolbar styling needs its own hook.
data-toolbar-control=""
- onClick={() => onRunScript(primaryScript)}
+ aria-disabled={!onRunScript || undefined}
+ onClick={() => onRunScript?.(primaryScript)}
/>
}
>
@@ -325,7 +328,11 @@ export default function ProjectScriptsControl({
{primaryScript.name}
</span>
</TooltipTrigger>
- <TooltipPopup side="top">Run {primaryScript.name}</TooltipPopup>
+ <TooltipPopup side="top">
+ {onRunScript
+ ? `Run ${primaryScript.name}`
+ : "Pair this client again with permission to run terminal commands."}
+ </TooltipPopup>
</Tooltip>
{isPanel ? (
<span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
diff --git a/apps/web/src/components/ThreadTerminalDrawer.permissions.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.permissions.test.tsx
new file mode 100644
index 00000000000..9b57677e9f7
--- /dev/null
+++ b/apps/web/src/components/ThreadTerminalDrawer.permissions.test.tsx
@@ -0,0 +1,153 @@
+import {
+ AuthTerminalOperateScope,
+ EnvironmentId,
+ ThreadId,
+ type AuthEnvironmentScope,
+} from "@t3tools/contracts";
+import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
+import { nextTerminalAttachSeedState } from "@t3tools/client-runtime/state/terminal";
+import { AsyncResult } from "effect/reactivity";
+import { act, create, type ReactTestRenderer } from "react-test-renderer";
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
+import type {
+ GhosttyTerminalSurface,
+ GhosttyTerminalSurfaceOptions,
+} from "~/terminal/ghostty/surface";
+
+const state = vi.hoisted(() => ({
+ allowed: true,
+ listeners: new Set<() => void>(),
+ resize: vi.fn(),
+ otherCommand: vi.fn(),
+ createSurface:
+ vi.fn<
+ (
+ mount: HTMLElement,
+ options: GhosttyTerminalSurfaceOptions,
+ ) => Promise<GhosttyTerminalSurface>
+ >(),
+}));
+
+vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
+vi.mock("../hooks/useSettings", () => ({
+ getClientSettings: () => DEFAULT_CLIENT_SETTINGS,
+ useClientSettings: (select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
+ select(DEFAULT_CLIENT_SETTINGS),
+}));
+vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => state.otherCommand }));
+vi.mock("../localApi", () => ({ readLocalApi: () => null }));
+vi.mock("../state/server", () => ({
+ serverEnvironment: { configValueAtom: () => "config" },
+}));
+vi.mock("../state/preview", () => ({ previewEnvironment: { open: "open" } }));
+vi.mock("../state/terminal", () => ({ terminalEnvironment: { resize: "resize", write: "write" } }));
+vi.mock("../state/use-atom-command", () => ({
+ useAtomCommand: (command: string) => (command === "resize" ? state.resize : state.otherCommand),
+}));
+vi.mock("../state/terminalSessions", () => ({
+ useAttachedTerminalSession: () => session,
+}));
+vi.mock("~/terminal/ghostty/surface", () => ({
+ GhosttyTerminalSurface: { create: state.createSurface },
+}));
+vi.mock("../state/session", async () => {
+ const { useSyncExternalStore } = await import("react");
+ const readEnvironmentScope = (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
+ id !== null &&
+ (scope !== AuthTerminalOperateScope || id !== threadRef.environmentId || state.allowed);
+ return {
+ readEnvironmentScope,
+ useEnvironmentScope: (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
+ useSyncExternalStore(
+ (listener) => {
+ state.listeners.add(listener);
+ return () => state.listeners.delete(listener);
+ },
+ () => readEnvironmentScope(id, scope),
+ ),
+ };
+});
+
+import { TerminalViewport } from "./ThreadTerminalDrawer";
+
+const threadRef = {
+ environmentId: EnvironmentId.make("secondary-terminal"),
+ threadId: ThreadId.make("thread"),
+};
+const session = { ...nextTerminalAttachSeedState(), status: "running" as const, version: 1 };
+let renderer: ReactTestRenderer | undefined;
+
+beforeEach(() => {
+ state.allowed = true;
+ state.listeners.clear();
+ state.resize.mockReset().mockResolvedValue(AsyncResult.success(undefined));
+ state.otherCommand.mockReset().mockResolvedValue(AsyncResult.success(undefined));
+ // A surface can report its initial grid while asynchronous WASM setup is
+ // pending. Keep that unrelated setup pending while exercising its callback.
+ state.createSurface.mockReset().mockReturnValue(new Promise(() => undefined));
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ vi.stubGlobal("document", {
+ body: {},
+ documentElement: { classList: { contains: () => false } },
+ querySelector: () => null,
+ createElement: () => ({ getContext: () => null }),
+ });
+ vi.stubGlobal("getComputedStyle", () => ({
+ colorScheme: "light",
+ backgroundColor: "",
+ color: "",
+ getPropertyValue: () => "",
+ }));
+});
+
+afterEach(async () => {
+ await act(async () => renderer?.unmount());
+ renderer = undefined;
+ vi.unstubAllGlobals();
+});
+
+it("rechecks the target terminal grant when a retained surface callback reports a resize", async () => {
+ await act(async () => {
+ renderer = create(
+ <TerminalViewport
+ advancedTypography={false}
+ threadRef={threadRef}
+ threadId={threadRef.threadId}
+ terminalId="terminal-1"
+ terminalLabel="Terminal 1"
+ cwd="/repo"
+ onSessionExited={state.otherCommand}
+ focusRequestId={0}
+ autoFocus={false}
+ visible={true}
+ resizeEpoch={0}
+ drawerHeight={200}
+ keybindings={[]}
+ />,
+ { createNodeMock: () => ({ closest: () => null, contains: () => false }) },
+ );
+ });
+ expect(state.createSurface).toHaveBeenCalledOnce();
+ const onResize = state.createSurface.mock.calls[0]![1].onResize;
+ if (!onResize) throw new Error("The terminal did not register its resize callback.");
+
+ onResize(80, 24);
+ expect(state.resize).toHaveBeenCalledExactlyOnceWith({
+ environmentId: threadRef.environmentId,
+ input: { threadId: threadRef.threadId, terminalId: "terminal-1", cols: 80, rows: 24 },
+ });
+
+ // The connection updates before React commits its external-store update.
+ // Other environments retain access; only this terminal's target is revoked.
+ state.allowed = false;
+ onResize(120, 40);
+ expect(state.resize).toHaveBeenCalledTimes(1);
+
+ state.allowed = true;
+ onResize(100, 30);
+ expect(state.resize).toHaveBeenCalledTimes(2);
+ expect(state.resize).toHaveBeenLastCalledWith({
+ environmentId: threadRef.environmentId,
+ input: { threadId: threadRef.threadId, terminalId: "terminal-1", cols: 100, rows: 30 },
+ });
+});
diff --git a/apps/web/src/components/ThreadTerminalDrawer.test.ts b/apps/web/src/components/ThreadTerminalDrawer.test.ts
index 1624a739bb1..33966b96890 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.test.ts
+++ b/apps/web/src/components/ThreadTerminalDrawer.test.ts
@@ -1,9 +1,17 @@
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+import {
+ applyTerminalAttachStreamEvent,
+ combineTerminalSessionState,
+ EMPTY_TERMINAL_BUFFER_STATE,
+ INITIAL_TERMINAL_OUTPUT_CURSOR,
+ nextTerminalAttachSeedState,
+} from "@t3tools/client-runtime/state/terminal";
import {
shouldClearTerminalSelectionAction,
shouldHandleTerminalExit,
terminalContextMenuItems,
+ synchronizeTerminalOutput,
terminalSelectionLineRange,
terminalSelectionMenuItems,
terminalThemeFromApp,
@@ -138,8 +146,63 @@ describe("terminal selection actions", () => {
});
it("handles an exit that lands while the terminal surface is still loading", () => {
- expect(shouldHandleTerminalExit("exited", "running", false)).toBe(true);
- expect(shouldHandleTerminalExit("exited", "exited", false)).toBe(false);
- expect(shouldHandleTerminalExit("closed", "running", true)).toBe(false);
+ expect(shouldHandleTerminalExit("exited", "running", false, 1)).toBe(true);
+ expect(shouldHandleTerminalExit("exited", "exited", false, 1)).toBe(false);
+ expect(shouldHandleTerminalExit("closed", "running", true, 1)).toBe(false);
+ });
+
+ it.each(["closed", "exited"] as const)("ignores an unsynchronized %s seed", (status) => {
+ expect(shouldHandleTerminalExit(status, "running", false, 0)).toBe(false);
+ expect(shouldHandleTerminalExit(status, "running", false, 1)).toBe(true);
+ });
+});
+
+it("retains visible output and selection until a replacement subscription receives its snapshot", () => {
+ const terminal = { resetAndWrite: vi.fn(), write: vi.fn(), clearSelection: vi.fn() };
+ const snapshot = {
+ threadId: "thread",
+ terminalId: "term-1",
+ cwd: "/repo",
+ worktreePath: null,
+ status: "running" as const,
+ pid: 123,
+ history: "host output",
+ exitCode: null,
+ exitSignal: null,
+ label: "Terminal 1",
+ updatedAt: "2026-09-05T00:00:00.000Z",
+ };
+ const attached = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
+ type: "snapshot",
+ snapshot,
+ });
+ const cursor = synchronizeTerminalOutput(terminal, attached, INITIAL_TERMINAL_OUTPUT_CURSOR);
+ expect(terminal.resetAndWrite).toHaveBeenLastCalledWith("host output");
+ terminal.resetAndWrite.mockClear();
+ terminal.clearSelection.mockClear();
+
+ const pending = combineTerminalSessionState(
+ { ...snapshot, hasRunningSubprocess: false },
+ EMPTY_TERMINAL_BUFFER_STATE,
+ );
+ expect(pending.status).toBe("running");
+ expect(synchronizeTerminalOutput(terminal, pending, cursor)).toBe(cursor);
+ expect(terminal.resetAndWrite).not.toHaveBeenCalled();
+ expect(terminal.write).not.toHaveBeenCalled();
+ expect(terminal.clearSelection).not.toHaveBeenCalled();
+
+ const observed = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
+ type: "snapshot",
+ snapshot: { ...snapshot, history: "host output\nobserved output" },
+ });
+ const observedCursor = synchronizeTerminalOutput(terminal, observed, cursor);
+ expect(terminal.resetAndWrite).toHaveBeenLastCalledWith("host output\nobserved output");
+
+ const cleared = applyTerminalAttachStreamEvent(observed, {
+ type: "cleared",
+ threadId: "thread",
+ terminalId: "term-1",
});
+ synchronizeTerminalOutput(terminal, cleared, observedCursor);
+ expect(terminal.resetAndWrite).toHaveBeenLastCalledWith("");
});
diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx
index 58cbceaec17..bd40a441795 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.tsx
+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx
@@ -20,6 +20,8 @@ import {
} from "lucide-react";
import {
AuthPreviewOperateScope,
+ AuthOrchestrationOperateScope,
+ AuthTerminalOperateScope,
type ContextMenuItem,
type ProviderInstanceId,
type ResolvedKeybindingsConfig,
@@ -83,6 +85,7 @@ import { serverEnvironment } from "../state/server";
import { previewEnvironment } from "../state/preview";
import { readEnvironmentScope } from "../state/session";
import { terminalEnvironment } from "../state/terminal";
+import { useEnvironmentScope } from "../state/session";
import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
import { useAtomCommand } from "../state/use-atom-command";
import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
@@ -121,6 +124,18 @@ export function writeTerminalOutputUpdate(
}
}
+export function synchronizeTerminalOutput(
+ terminal: Pick<GhosttyTerminalSurface, "resetAndWrite" | "write" | "clearSelection">,
+ session: Pick<TerminalSessionState, "output" | "version">,
+ cursor: TerminalOutputCursor,
+): TerminalOutputCursor {
+ if (session.version === 0) return cursor;
+ const update = readTerminalOutputUpdate(session.output, cursor);
+ writeTerminalOutputUpdate(terminal, update);
+ terminal.clearSelection();
+ return update.cursor;
+}
+
function parseTerminalColor(value: string, fallback: GhosttyColor): GhosttyColor {
if (typeof document === "undefined") return fallback;
@@ -272,6 +287,7 @@ export function terminalSelectionMenuItems(options?: {
export function terminalContextMenuItems(options: {
hasSelection: boolean;
canAddToChat?: boolean;
+ readOnly?: boolean;
}): ContextMenuItem<TerminalContextMenuAction>[] {
const { hasSelection, canAddToChat = true } = options;
return [
@@ -279,7 +295,7 @@ export function terminalContextMenuItems(options: {
...item,
disabled: !hasSelection,
})),
- { id: "paste", label: "Paste" },
+ { id: "paste", label: "Paste", ...(options.readOnly ? { disabled: true } : {}) },
];
}
@@ -302,9 +318,13 @@ export function shouldHandleTerminalExit(
current: TerminalSessionState["status"],
synchronized: TerminalSessionState["status"],
alreadyHandled: boolean,
+ version: number,
): boolean {
return (
- (current === "closed" || current === "exited") && current !== synchronized && !alreadyHandled
+ version > 0 &&
+ (current === "closed" || current === "exited") &&
+ current !== synchronized &&
+ !alreadyHandled
);
}
@@ -357,6 +377,15 @@ export function TerminalViewport({
const terminalRef = useRef<GhosttyTerminalSurface | null>(null);
const visibleRef = useRef(visible);
const environmentId = threadRef.environmentId;
+ const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
+ const hasTerminalWriteAccess = useEffectEvent(() =>
+ readEnvironmentScope(environmentId, AuthTerminalOperateScope),
+ );
+ const canOpenHostEditor = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
+ const canActivateTerminalLink = useEffectEvent(
+ (text: string) =>
+ isTerminalUrl(text) || readEnvironmentScope(environmentId, AuthOrchestrationOperateScope),
+ );
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
const openInPreferredEditor = useOpenInPreferredEditor(
environmentId,
@@ -381,7 +410,7 @@ export function TerminalViewport({
const keybindingsRef = useRef(keybindings);
const runtimeEnvKey = useMemo(() => runtimeEnvSignature(runtimeEnv), [runtimeEnv]);
const handleSessionExited = useEffectEvent(() => {
- onSessionExited();
+ if (hasTerminalWriteAccess()) onSessionExited();
});
const handleAddTerminalContext = useEffectEvent((selection: TerminalContextSelection) => {
onAddTerminalContext?.(selection);
@@ -414,29 +443,35 @@ export function TerminalViewport({
...(providerInstanceId ? { providerInstanceId } : {}),
},
});
+ const canResizeTerminal =
+ canOperateTerminal && terminalSession.version > 0 && terminalSession.status === "running";
+ const resizeSessionGeneration = canResizeTerminal ? terminalSession.output.generation : null;
const writeTerminal = useEffectEvent((data: string) =>
runTerminalWrite({
environmentId,
input: { threadId, terminalId, data },
}),
);
- const resizeTerminal = useEffectEvent((cols: number, rows: number) =>
- runTerminalResize({
+ const resizeTerminal = useEffectEvent((cols: number, rows: number) => {
+ if (!canResizeTerminal || !hasTerminalWriteAccess()) return;
+ return runTerminalResize({
environmentId,
input: { threadId, terminalId, cols, rows },
- }),
- );
+ });
+ });
const terminalOutput = terminalSession.output;
const terminalError = terminalSession.error;
const terminalStatus = terminalSession.status;
const outputCursorRef = useRef<TerminalOutputCursor>(INITIAL_TERMINAL_OUTPUT_CURSOR);
const synchronizedStatusRef = useRef<TerminalSessionState["status"]>("closed");
const synchronizeTerminalStatus = useEffectEvent(
- (terminal: GhosttyTerminalSurface, status: TerminalSessionState["status"]) => {
+ (terminal: GhosttyTerminalSurface, status: TerminalSessionState["status"], version: number) => {
const synchronized = synchronizedStatusRef.current;
- if (status === "running") {
+ if (version > 0 && status === "running") {
hasHandledExitRef.current = false;
- } else if (shouldHandleTerminalExit(status, synchronized, hasHandledExitRef.current)) {
+ } else if (
+ shouldHandleTerminalExit(status, synchronized, hasHandledExitRef.current, version)
+ ) {
hasHandledExitRef.current = true;
writeSystemMessage(terminal, status === "closed" ? "Terminal closed" : "Process exited");
window.setTimeout(() => {
@@ -445,7 +480,7 @@ export function TerminalViewport({
}
}, 0);
}
- synchronizedStatusRef.current = status;
+ if (version > 0) synchronizedStatusRef.current = status;
},
);
const terminalVersion = terminalSession.version;
@@ -467,6 +502,22 @@ export function TerminalViewport({
keybindingsRef.current = keybindings;
}, [keybindings]);
+ useLayoutEffect(() => {
+ if (terminalRef.current) terminalRef.current.input.readOnly = !canOperateTerminal;
+ }, [canOperateTerminal]);
+
+ // A grant can change while the pointer remains over a link.
+ useEffect(() => {
+ terminalRef.current?.refreshLinkActivation();
+ }, [canOpenHostEditor]);
+
+ useEffect(() => {
+ if (resizeSessionGeneration === null) return;
+ // The first fit can finish before authorization or the attach snapshot.
+ // Replay its grid once this writable session exists, including reconnects.
+ terminalRef.current?.resendSize();
+ }, [resizeSessionGeneration]);
+
useLayoutEffect(() => {
visibleRef.current = visible;
terminalRef.current?.setVisible(visible);
@@ -503,6 +554,7 @@ export function TerminalViewport({
onSelectionChange: () => handleSelectionChange(),
beforeKey: (event) => handleBeforeKey(event),
onLinkActivate: (text, event) => handleLinkActivate(text, event),
+ canActivateLink: (text) => canActivateTerminalLink(text),
// The surface listens from construction, so a right-click can land
// while `create` is still awaiting WASM — before the handler below it
// exists. The ref is only assigned once that setup has run.
@@ -521,6 +573,7 @@ export function TerminalViewport({
terminal.setTheme(terminalThemeFromApp(mount));
setupTerminal = terminal;
terminalRef.current = terminal;
+ terminal.input.readOnly = !hasTerminalWriteAccess();
// Client settings hydrate asynchronously; a font preference that landed
// while the surface was loading found terminalRef null, so its setFont
// was dropped. Re-apply whatever is current once the terminal exists.
@@ -544,9 +597,13 @@ export function TerminalViewport({
// (A session that is "closed" at mount is indistinguishable from one that
// never started, so only "exited" triggers the message — as with xterm.)
synchronizedStatusRef.current = "closed";
- synchronizeTerminalStatus(terminal, latestSession.status);
+ synchronizeTerminalStatus(terminal, latestSession.status, latestSession.version);
// Startup may finish after the user has returned to the composer.
- if (visibleRef.current && mount.contains(document.activeElement)) {
+ if (
+ hasTerminalWriteAccess() &&
+ visibleRef.current &&
+ mount.contains(document.activeElement)
+ ) {
terminal.focus();
}
@@ -634,6 +691,7 @@ export function TerminalViewport({
};
const pasteFromClipboard = async (requestId: number) => {
+ if (!hasTerminalWriteAccess()) return;
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
try {
@@ -667,6 +725,7 @@ export function TerminalViewport({
terminalContextMenuItems({
hasSelection: selectionAction !== null,
canAddToChat: canAddSelectionToChat(),
+ readOnly: !hasTerminalWriteAccess(),
}),
{ x: event.clientX, y: event.clientY },
);
@@ -732,6 +791,7 @@ export function TerminalViewport({
};
const sendTerminalInput = async (data: string, fallbackError: string) => {
+ if (!hasTerminalWriteAccess()) return;
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
const result = await writeTerminal(data);
@@ -784,6 +844,7 @@ export function TerminalViewport({
}
function handleLinkActivate(text: string, event: MouseEvent): void {
+ if (!canActivateTerminalLink(text)) return;
const latestTerminal = terminalRef.current;
if (!latestTerminal) return;
if (isTerminalUrl(text)) {
@@ -835,6 +896,7 @@ export function TerminalViewport({
}
function handleData(data: string): void {
+ if (!hasTerminalWriteAccess()) return;
void (async () => {
const result = await writeTerminal(data);
if (result._tag === "Success" || isAtomCommandInterrupted(result)) return;
@@ -924,7 +986,9 @@ export function TerminalViewport({
cancelled = true;
const hadFocus = mount.contains(document.activeElement);
teardown?.();
- if (hadFocus && mount.isConnected) mount.focus({ preventScroll: true });
+ if (hasTerminalWriteAccess() && hadFocus && mount.isConnected) {
+ mount.focus({ preventScroll: true });
+ }
};
}, [cwd, environmentId, runtimeEnvKey, terminalId, threadId, worktreePath]);
@@ -942,15 +1006,12 @@ export function TerminalViewport({
}
const previous = previousSessionRef.current;
- synchronizeTerminalStatus(terminal, current.status);
+ synchronizeTerminalStatus(terminal, current.status, current.version);
if (current.version === previous.version && current.output === previous.output) {
return;
}
- const outputUpdate = readTerminalOutputUpdate(current.output, outputCursorRef.current);
- writeTerminalOutputUpdate(terminal, outputUpdate);
- outputCursorRef.current = outputUpdate.cursor;
- terminal.clearSelection();
+ outputCursorRef.current = synchronizeTerminalOutput(terminal, current, outputCursorRef.current);
if (current.error !== null && current.error !== previous.error) {
writeSystemMessage(terminal, current.error);
@@ -960,11 +1021,11 @@ export function TerminalViewport({
}, [terminalOutput, terminalError, terminalStatus, terminalVersion]);
useEffect(() => {
- if (!autoFocus || !visible) return;
+ if (!autoFocus || !canOperateTerminal || !visible) return;
// Claim focus when requested, then hand it to the terminal once ready only
// if the user has not focused something else in the meantime.
(terminalRef.current ?? containerRef.current)?.focus();
- }, [autoFocus, focusRequestId, visible]);
+ }, [autoFocus, canOperateTerminal, focusRequestId, visible]);
useEffect(() => {
const terminal = terminalRef.current;
@@ -1029,14 +1090,29 @@ interface TerminalActionButtonProps {
className: string;
onClick: () => void;
children: ReactNode;
+ disabled?: boolean;
}
-function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
+function TerminalActionButton({
+ label,
+ className,
+ onClick,
+ children,
+ disabled,
+}: TerminalActionButtonProps) {
return (
<Popover>
<PopoverTrigger
openOnHover
- render={<button type="button" className={className} onClick={onClick} aria-label={label} />}
+ render={
+ <button
+ type="button"
+ className={cn(className, disabled && "opacity-45 cursor-not-allowed")}
+ onClick={disabled ? undefined : onClick}
+ aria-label={label}
+ aria-disabled={disabled}
+ />
+ }
>
{children}
</PopoverTrigger>
@@ -1082,6 +1158,7 @@ export default function ThreadTerminalDrawer({
terminalLabelsById,
terminalLaunchLocationsById,
}: ThreadTerminalDrawerProps) {
+ const canOperateTerminal = useEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope);
const isPanel = mode === "panel";
const [advancedTypography] = useLocalStorage(
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
@@ -1273,24 +1350,28 @@ export default function ThreadTerminalDrawer({
? `Close Terminal (${closeShortcutLabel})`
: "Close Terminal";
const onSplitTerminalAction = useCallback(() => {
- if (hasReachedSplitLimit) return;
+ if (!canOperateTerminal || hasReachedSplitLimit) return;
onSplitTerminal();
- }, [hasReachedSplitLimit, onSplitTerminal]);
+ }, [canOperateTerminal, hasReachedSplitLimit, onSplitTerminal]);
const onSplitTerminalVerticalAction = useCallback(() => {
- if (hasReachedSplitLimit) return;
+ if (!canOperateTerminal || hasReachedSplitLimit) return;
onSplitTerminalVertical();
- }, [hasReachedSplitLimit, onSplitTerminalVertical]);
+ }, [canOperateTerminal, hasReachedSplitLimit, onSplitTerminalVertical]);
const onNewTerminalAction = useCallback(() => {
+ if (!canOperateTerminal) return;
onNewTerminal();
- }, [onNewTerminal]);
+ }, [canOperateTerminal, onNewTerminal]);
const confirmCloseTerminal = useCallback(
(terminalId: string) => {
+ if (!canOperateTerminal) return;
const label = terminalLabelById.get(terminalId) ?? getTerminalLabel(terminalId);
void confirmTerminalClose([label]).then((confirmed) => {
- if (confirmed) onCloseTerminal(terminalId);
+ if (confirmed && readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope)) {
+ onCloseTerminal(terminalId);
+ }
});
},
- [onCloseTerminal, terminalLabelById],
+ [canOperateTerminal, onCloseTerminal, terminalLabelById, threadRef.environmentId],
);
useEffect(() => {
@@ -1417,7 +1498,12 @@ export default function ThreadTerminalDrawer({
) : null}
<div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 px-4 py-6 text-center text-sm text-muted-foreground">
<p>No terminal sessions for this thread yet.</p>
- <Button size="xs" variant="outline" onClick={onNewTerminalAction}>
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={onNewTerminalAction}
+ disabled={!canOperateTerminal}
+ >
{newTerminalActionLabel}
</Button>
</div>
@@ -1451,6 +1537,7 @@ export default function ThreadTerminalDrawer({
<div className="pointer-events-none absolute right-2 top-2 z-20">
<div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background shadow-xs">
<TerminalActionButton
+ disabled={!canOperateTerminal}
className={`p-1 text-foreground/90 transition-colors ${
hasReachedSplitLimit
? "cursor-not-allowed opacity-64 hover:bg-transparent"
@@ -1463,6 +1550,7 @@ export default function ThreadTerminalDrawer({
</TerminalActionButton>
<div className="h-4 w-px bg-border/80" />
<TerminalActionButton
+ disabled={!canOperateTerminal}
className={`p-1 text-foreground/90 transition-colors ${
hasReachedSplitLimit
? "cursor-not-allowed opacity-64 hover:bg-transparent"
@@ -1475,6 +1563,7 @@ export default function ThreadTerminalDrawer({
</TerminalActionButton>
<div className="h-4 w-px bg-border/80" />
<TerminalActionButton
+ disabled={!canOperateTerminal}
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onNewTerminalAction}
label={newTerminalActionLabel}
@@ -1483,6 +1572,7 @@ export default function ThreadTerminalDrawer({
</TerminalActionButton>
<div className="h-4 w-px bg-border/80" />
<TerminalActionButton
+ disabled={!canOperateTerminal}
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={() => confirmCloseTerminal(resolvedActiveTerminalId)}
label={closeTerminalActionLabel}
@@ -1596,6 +1686,7 @@ export default function ThreadTerminalDrawer({
<div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
<div className="inline-flex h-full items-stretch">
<TerminalActionButton
+ disabled={!canOperateTerminal}
className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
hasReachedSplitLimit
? "cursor-not-allowed opacity-64 hover:bg-transparent"
@@ -1607,6 +1698,7 @@ export default function ThreadTerminalDrawer({
<SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton>
<TerminalActionButton
+ disabled={!canOperateTerminal}
className={`inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors ${
hasReachedSplitLimit
? "cursor-not-allowed opacity-64 hover:bg-transparent"
@@ -1618,6 +1710,7 @@ export default function ThreadTerminalDrawer({
<SquareSplitVertical className="size-3.25" />
</TerminalActionButton>
<TerminalActionButton
+ disabled={!canOperateTerminal}
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onNewTerminalAction}
label={newTerminalActionLabel}
@@ -1625,6 +1718,7 @@ export default function ThreadTerminalDrawer({
<Plus className="size-3.25" />
</TerminalActionButton>
<TerminalActionButton
+ disabled={!canOperateTerminal}
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={() => confirmCloseTerminal(resolvedActiveTerminalId)}
label={closeTerminalActionLabel}
@@ -1691,13 +1785,17 @@ export default function ThreadTerminalDrawer({
: "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
)}
>
- <PanelTabCloseButton
- label={closeTerminalLabel}
- onClick={() => confirmCloseTerminal(terminalId)}
- tooltip={closeTerminalLabel}
- >
+ {canOperateTerminal ? (
+ <PanelTabCloseButton
+ label={closeTerminalLabel}
+ onClick={() => confirmCloseTerminal(terminalId)}
+ tooltip={closeTerminalLabel}
+ >
+ <TerminalSquare className="size-3 shrink-0" />
+ </PanelTabCloseButton>
+ ) : (
<TerminalSquare className="size-3 shrink-0" />
- </PanelTabCloseButton>
+ )}
<button
type="button"
className="flex min-w-0 flex-1 cursor-pointer items-center gap-1 text-left"
diff --git a/apps/web/src/components/onboarding/WelcomeWizard.terminal.test.tsx b/apps/web/src/components/onboarding/WelcomeWizard.terminal.test.tsx
new file mode 100644
index 00000000000..e59a837d9ad
--- /dev/null
+++ b/apps/web/src/components/onboarding/WelcomeWizard.terminal.test.tsx
@@ -0,0 +1,470 @@
+import { RegistryContext } from "@effect/atom-react";
+import {
+ BearerConnectionTarget,
+ PrimaryConnectionTarget,
+} from "@t3tools/client-runtime/connection";
+import {
+ AuthTerminalOperateScope,
+ DEFAULT_SERVER_SETTINGS,
+ EnvironmentId,
+ ProviderDriverKind,
+ ProviderInstanceId,
+ type AuthEnvironmentScope,
+ type AuthSessionState,
+ type ResolvedKeybindingsConfig,
+ type ServerProvider,
+ type ServerSettings,
+ type TerminalCloseInput,
+ type TerminalOpenInput,
+ type TerminalWriteInput,
+} from "@t3tools/contracts";
+import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
+import * as Cause from "effect/Cause";
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
+import { act, create, type ReactTestInstance, type ReactTestRenderer } from "react-test-renderer";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
+type CommandResult = AsyncResult.AsyncResult<void, Error>;
+type Request<Input> = { environmentId: EnvironmentId; input: Input };
+type SetupConfig = {
+ cwd: string;
+ settings: ServerSettings;
+ environment: { platform: { os: "darwin" } };
+ keybindings: ResolvedKeybindingsConfig;
+};
+const state = vi.hoisted(() => ({
+ registry: null as AtomRegistry.AtomRegistry | null,
+ sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),
+ providers: new Map<EnvironmentId, Atom.Writable<ReadonlyArray<ServerProvider>>>(),
+ configs: new Map<EnvironmentId, Atom.Atom<SetupConfig>>(),
+ open: vi.fn<(request: Request<TerminalOpenInput>) => Promise<CommandResult>>(),
+ write: vi.fn<(request: Request<TerminalWriteInput>) => Promise<CommandResult>>(),
+ close: vi.fn<(request: Request<TerminalCloseInput>) => Promise<CommandResult>>(),
+ refresh: vi.fn(),
+ pair: vi.fn(),
+ createProject: vi.fn(),
+ importThreads: vi.fn(),
+ complete: vi.fn<() => Promise<void>>(),
+ done: vi.fn(),
+}));
+
+vi.mock("../../connection/runtime", () => ({ connectionAtomRuntime: undefined }));
+vi.mock("@t3tools/client-runtime/state/session", () => ({
+ createEnvironmentSessionAtoms: () => ({
+ sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,
+ }),
+}));
+vi.mock("../../rpc/atomRegistry", () => ({
+ get appAtomRegistry() {
+ return state.registry;
+ },
+}));
+vi.mock("../../state/environments", () => ({
+ useEnvironments: () => ({ environments: [remoteEnvironment] }),
+ usePrimaryEnvironment: () => primaryEnvironment,
+}));
+vi.mock("../../state/server", () => ({
+ serverEnvironment: {
+ providersValueAtom: (id: EnvironmentId) => state.providers.get(id)!,
+ configValueAtom: (id: EnvironmentId) => state.configs.get(id)!,
+ refreshProviders: "refresh",
+ },
+}));
+vi.mock("../../state/terminal", () => ({
+ terminalEnvironment: { open: "open", write: "write", close: "close" },
+}));
+vi.mock("../../state/use-atom-command", () => ({
+ useAtomCommand: (
+ command: "open" | "write" | "close" | "refresh" | "pair" | "createProject" | "importThreads",
+ ) => state[command],
+}));
+vi.mock("../../connection/onboarding", () => ({ connectPairing: "pair" }));
+vi.mock("../../state/agentSessions", () => ({
+ agentSessionImport: "importThreads",
+ agentSessionScan: vi.fn(),
+}));
+vi.mock("../../state/projects", () => ({ projectEnvironment: { create: "createProject" } }));
+vi.mock("../../state/entities", () => ({ readProjects: () => [], useProjects: () => [] }));
+vi.mock("../../onboarding/useProjectScans", () => ({ useProjectScans: () => [] }));
+vi.mock("../ui/dialog", () => ({
+ Dialog: "div",
+ DialogPopup: "div",
+ DialogTitle: "div",
+ DialogHeader: "div",
+}));
+vi.mock("../ui/wizard", () => ({
+ WizardPanel: "div",
+ WizardPopup: "div",
+ WizardHeader: "div",
+ WizardSteps: ({ onStepChange }: { onStepChange: (step: number) => void }) => (
+ <button onClick={() => onStepChange(0)}>Back</button>
+ ),
+}));
+vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));
+vi.mock("../../onboarding/firstRun", () => ({ useCompleteOnboarding: () => state.complete }));
+vi.mock("../../hooks/useTheme", () => ({ mountOnboardingTheme: () => undefined }));
+vi.mock("../../hooks/useLocalStorage", () => ({ useLocalStorage: () => [false, vi.fn()] }));
+vi.mock("../../hooks/useCopyToClipboard", () => ({
+ useCopyToClipboard: () => ({ copyToClipboard: vi.fn(), isCopied: false }),
+}));
+vi.mock("../../cloud/publicConfig", () => ({ hasCloudPublicConfig: () => false }));
+vi.mock("../clerk/useT3ConnectAuthPrompt", () => ({ useT3ConnectAuthPrompt: vi.fn() }));
+vi.mock("@clerk/react", () => ({ useAuth: vi.fn() }));
+vi.mock("../../env", () => ({ isElectron: false }));
+vi.mock("../../providerInstances", () => ({ resolveDefaultProviderModelSelection: vi.fn() }));
+vi.mock("../settings/ChatGptWelcomeCoordinator", () => ({ ChatGptWelcomeCoordinator: () => null }));
+vi.mock("../settings/CodexSetupSection", () => ({
+ CodexSetupSection: () => null,
+ AddManagedCodexAccountDialog: () => null,
+}));
+vi.mock("../settings/providerDriverMeta", () => ({
+ getDriverOption: (driver: string) => ({ label: driver }),
+}));
+vi.mock("../settings/providerStatus", () => ({
+ getProviderSummary: () => ({ headline: "Setup required" }),
+}));
+vi.mock("../cloud/CloudEnvironmentConnectList", () => ({
+ CloudEnvironmentConnectRows: () => null,
+}));
+vi.mock("../ThreadTerminalDrawer", () => ({
+ TerminalViewport: () => <div data-terminal-viewport />,
+}));
+vi.mock("../ui/button", () => ({ Button: "button" }));
+vi.mock("../ui/input", () => ({ Input: "input" }));
+vi.mock("../ui/checkbox", () => ({ Checkbox: "input" }));
+vi.mock("../ui/collapsible", () => ({
+ Collapsible: "div",
+ CollapsiblePanel: "div",
+ CollapsibleTrigger: "button",
+}));
+vi.mock("../ui/toast", () => ({
+ toastManager: { add: vi.fn(), update: vi.fn(), close: vi.fn() },
+}));
+
+import { WelcomeWizard } from "./WelcomeWizard";
+
+const primaryId = EnvironmentId.make("primary");
+const remoteId = EnvironmentId.make("paired-remote");
+const primaryEnvironment = {
+ environmentId: primaryId,
+ label: "This computer",
+ connection: { phase: "connected" },
+ entry: {
+ target: new PrimaryConnectionTarget({
+ environmentId: primaryId,
+ label: "This computer",
+ httpBaseUrl: "http://127.0.0.1:3773",
+ wsBaseUrl: "ws://127.0.0.1:3773",
+ }),
+ },
+} as const;
+const remoteEnvironment = {
+ environmentId: remoteId,
+ label: "Paired computer",
+ connection: { phase: "connected" },
+ entry: {
+ target: new BearerConnectionTarget({
+ environmentId: remoteId,
+ label: "Paired computer",
+ connectionId: "paired-remote",
+ }),
+ },
+} as const;
+const missingClaude: ServerProvider = {
+ instanceId: ProviderInstanceId.make("claude-work"),
+ driver: ProviderDriverKind.make("claudeAgent"),
+ enabled: true,
+ installed: false,
+ version: null,
+ status: "error",
+ auth: { status: "unknown" },
+ checkedAt: "2026-09-05T00:00:00.000Z",
+ models: [],
+ slashCommands: [],
+ skills: [],
+};
+const signedOutCodex: ServerProvider = {
+ ...missingClaude,
+ instanceId: ProviderInstanceId.make("codex-work"),
+ driver: ProviderDriverKind.make("codex"),
+ installed: true,
+ auth: { status: "unauthenticated" },
+};
+const session = (scopes: readonly AuthEnvironmentScope[]): AuthSessionState => ({
+ authenticated: true,
+ scopes,
+ auth: {
+ policy: "remote-reachable",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["bearer-access-token"],
+ sessionCookieName: "t3_session",
+ },
+});
+function setAccess(environmentId: EnvironmentId, allowed: boolean) {
+ state.registry!.set(
+ state.sessions.get(environmentId)!,
+ AsyncResult.success(session(allowed ? [AuthTerminalOperateScope] : [])),
+ );
+}
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((complete) => {
+ resolve = complete;
+ });
+ return { promise, resolve };
+}
+function text(node: ReactTestInstance | string): string {
+ return typeof node === "string" ? node : node.children.map(text).join("");
+}
+let renderer: ReactTestRenderer | undefined;
+function button(label: string) {
+ return renderer!.root.findAllByType("button").find((node) => text(node) === label)!;
+}
+async function click(label: string) {
+ const node = button(label);
+ expect(node).toBeDefined();
+ expect(node.props.disabled).not.toBe(true);
+ await act(async () => node.props.onClick());
+}
+function hasViewport() {
+ return renderer!.root.findAllByProps({ "data-terminal-viewport": true }).length > 0;
+}
+async function enterRemoteAgents() {
+ await act(async () => {
+ renderer = create(
+ <RegistryContext.Provider value={state.registry!}>
+ <WelcomeWizard localAvailable onDone={state.done} />
+ </RegistryContext.Provider>,
+ );
+ });
+ await click("Continue");
+ expect(text(renderer!.root)).toContain("Paired computer");
+}
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ vi.stubGlobal("document", { activeElement: null, body: {}, getElementById: () => null });
+ state.registry = AtomRegistry.make();
+ for (const id of [primaryId, remoteId]) {
+ state.sessions.set(
+ id,
+ Atom.make<SessionResult>(AsyncResult.success(session([AuthTerminalOperateScope]))).pipe(
+ Atom.keepAlive,
+ ),
+ );
+ state.providers.set(
+ id,
+ Atom.make<ReadonlyArray<ServerProvider>>([missingClaude, signedOutCodex]).pipe(
+ Atom.keepAlive,
+ ),
+ );
+ state.configs.set(
+ id,
+ Atom.make<SetupConfig>({
+ cwd: `/fixtures/${id}`,
+ settings: {
+ ...DEFAULT_SERVER_SETTINGS,
+ providerInstances: {
+ [signedOutCodex.instanceId]: {
+ driver: signedOutCodex.driver,
+ config: { binaryPath: "/opt/codex-work", setupMode: "existing" },
+ },
+ },
+ },
+ environment: { platform: { os: "darwin" } },
+ keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
+ }),
+ );
+ }
+ state.open.mockReset().mockResolvedValue(AsyncResult.success(undefined));
+ state.write.mockReset().mockResolvedValue(AsyncResult.success(undefined));
+ state.close.mockReset().mockResolvedValue(AsyncResult.success(undefined));
+ state.refresh.mockReset().mockResolvedValue(AsyncResult.success(undefined));
+ state.pair.mockReset().mockResolvedValue(AsyncResult.success(remoteId));
+ state.complete.mockReset().mockResolvedValue(undefined);
+ state.done.mockReset();
+});
+
+afterEach(async () => {
+ await act(async () => renderer?.unmount());
+ renderer = undefined;
+ state.registry?.dispose();
+ state.sessions.clear();
+ state.providers.clear();
+ state.configs.clear();
+ vi.unstubAllGlobals();
+});
+
+describe("welcome agent terminal setup", () => {
+ it("disables both setup actions for the paired read-only connection and preserves local completion", async () => {
+ setAccess(remoteId, false);
+ await enterRemoteAgents();
+ expect(button("Install").props.disabled).toBe(true);
+ expect(button("Sign in").props.disabled).toBe(true);
+ expect(text(renderer!.root)).toContain("This connection cannot control terminals.");
+ await act(async () => {
+ button("Install").props.onClick();
+ button("Sign in").props.onClick();
+ });
+ expect(state.open).not.toHaveBeenCalled();
+ expect(state.write).not.toHaveBeenCalled();
+ expect(state.close).not.toHaveBeenCalled();
+ await click("Continue");
+ await click("Do not import projects");
+ expect(state.complete).toHaveBeenCalledOnce();
+ expect(state.done).toHaveBeenCalledExactlyOnceWith(undefined);
+ });
+
+ it("rejects a retained install action after revocation and allows a terminal-only regrant", async () => {
+ setAccess(primaryId, false);
+ await enterRemoteAgents();
+ const install = button("Install").props.onClick;
+ await act(async () => {
+ setAccess(remoteId, false);
+ install();
+ });
+ expect(state.open).not.toHaveBeenCalled();
+ expect(button("Install").props.disabled).toBe(true);
+ await act(async () => setAccess(remoteId, true));
+ expect(button("Install").props.disabled).toBe(false);
+ await act(async () => install());
+ expect(state.open).toHaveBeenCalledExactlyOnceWith({
+ environmentId: remoteId,
+ input: {
+ threadId: "onboarding-agent-setup",
+ terminalId: expect.any(String),
+ cwd: "/fixtures/paired-remote",
+ providerInstanceId: missingClaude.instanceId,
+ },
+ });
+ expect(state.write).toHaveBeenCalledExactlyOnceWith({
+ environmentId: remoteId,
+ input: {
+ threadId: "onboarding-agent-setup",
+ terminalId: state.open.mock.calls[0]![0].input.terminalId,
+ data: "curl -fsSL https://claude.ai/install.sh | bash",
+ },
+ });
+ expect(hasViewport()).toBe(true);
+ await click("Close");
+ expect(state.close).toHaveBeenCalledExactlyOnceWith({
+ environmentId: remoteId,
+ input: {
+ threadId: "onboarding-agent-setup",
+ terminalId: state.open.mock.calls[0]![0].input.terminalId,
+ deleteHistory: true,
+ },
+ });
+ });
+
+ it("pretypes the selected provider's sign-in command without executing it", async () => {
+ setAccess(primaryId, false);
+ await enterRemoteAgents();
+ await click("Sign in");
+ expect(state.open).toHaveBeenCalledExactlyOnceWith({
+ environmentId: remoteId,
+ input: {
+ threadId: "onboarding-agent-setup",
+ terminalId: expect.any(String),
+ cwd: "/fixtures/paired-remote",
+ providerInstanceId: signedOutCodex.instanceId,
+ },
+ });
+ expect(state.write).toHaveBeenCalledExactlyOnceWith({
+ environmentId: remoteId,
+ input: {
+ threadId: "onboarding-agent-setup",
+ terminalId: state.open.mock.calls[0]![0].input.terminalId,
+ data: "/opt/codex-work login",
+ },
+ });
+ expect(text(renderer!.root)).toContain("Review the command, then press Enter to run it.");
+ });
+
+ it("checks access when a queued retry starts and recovers after regrant", async () => {
+ state.open.mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Could not open"))));
+ await enterRemoteAgents();
+ await click("Install");
+ const closing = deferred<CommandResult>();
+ state.close.mockReturnValueOnce(closing.promise);
+ await click("Retry");
+ expect(state.close).toHaveBeenCalledOnce();
+ expect(state.open).toHaveBeenCalledOnce();
+ await act(async () => {
+ setAccess(remoteId, false);
+ closing.resolve(AsyncResult.success(undefined));
+ });
+ expect(state.open).toHaveBeenCalledOnce();
+ expect(button("Retry").props.disabled).toBe(true);
+ expect(state.write).not.toHaveBeenCalled();
+ await act(async () => setAccess(remoteId, true));
+ await click("Retry");
+ expect(state.open).toHaveBeenCalledTimes(2);
+ expect(state.write).toHaveBeenCalledOnce();
+ expect(hasViewport()).toBe(true);
+ });
+
+ it("keeps an accepted terminal visible without pretyping when access is revoked during open", async () => {
+ const opening = deferred<CommandResult>();
+ state.open.mockReturnValueOnce(opening.promise);
+ await enterRemoteAgents();
+ await click("Install");
+ await act(async () => {
+ setAccess(remoteId, false);
+ opening.resolve(AsyncResult.success(undefined));
+ });
+ expect(state.write).not.toHaveBeenCalled();
+ expect(state.close).not.toHaveBeenCalled();
+ expect(hasViewport()).toBe(true);
+ expect(text(renderer!.root)).toContain("This connection cannot control terminals.");
+ await act(async () => setAccess(remoteId, true));
+ expect(state.open).toHaveBeenCalledOnce();
+ expect(state.write).not.toHaveBeenCalled();
+ expect(text(renderer!.root)).toContain(
+ "Run curl -fsSL https://claude.ai/install.sh | bash in this",
+ );
+ await act(async () => setAccess(remoteId, false));
+ await click("Close");
+ expect(hasViewport()).toBe(false);
+ expect(state.close).not.toHaveBeenCalled();
+ await click("Continue");
+ expect(text(renderer!.root)).toContain("Choose your projects");
+ });
+
+ it("settles accepted pretyping locally after revocation without closing the PTY", async () => {
+ const writing = deferred<CommandResult>();
+ state.write.mockReturnValueOnce(writing.promise);
+ await enterRemoteAgents();
+ await click("Sign in");
+ await act(async () => {
+ setAccess(remoteId, false);
+ writing.resolve(AsyncResult.success(undefined));
+ });
+ expect(state.open).toHaveBeenCalledOnce();
+ expect(state.write).toHaveBeenCalledOnce();
+ expect(hasViewport()).toBe(true);
+ await act(async () => setAccess(remoteId, true));
+ expect(text(renderer!.root)).toContain("Review the command, then press Enter to run it.");
+ expect(state.open).toHaveBeenCalledOnce();
+ expect(state.write).toHaveBeenCalledOnce();
+ await act(async () => setAccess(remoteId, false));
+ await click("Close");
+ expect(state.close).not.toHaveBeenCalled();
+ });
+
+ it("rechecks the original environment when cleanup runs after pending pretyping", async () => {
+ const writing = deferred<CommandResult>();
+ state.write.mockReturnValueOnce(writing.promise);
+ await enterRemoteAgents();
+ await click("Install");
+ await click("Back");
+ expect(state.close).not.toHaveBeenCalled();
+ await act(async () => {
+ setAccess(remoteId, false);
+ writing.resolve(AsyncResult.success(undefined));
+ });
+ expect(state.close).not.toHaveBeenCalled();
+ expect(text(renderer!.root)).toContain("Connect your computers");
+ });
+});
diff --git a/apps/web/src/components/onboarding/WelcomeWizard.tsx b/apps/web/src/components/onboarding/WelcomeWizard.tsx
index bb4055d8468..9d1c96e19ee 100644
--- a/apps/web/src/components/onboarding/WelcomeWizard.tsx
+++ b/apps/web/src/components/onboarding/WelcomeWizard.tsx
@@ -15,6 +15,7 @@ import {
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import {
+ AuthTerminalOperateScope,
CommandId,
defaultInstanceIdForDriver,
AuthOrchestrationOperateScope,
@@ -61,7 +62,11 @@ import { isOnboardingRelayEnvironment } from "../../onboarding/targetEnvironment
import { useProjectScans } from "../../onboarding/useProjectScans";
import { projectEnvironment } from "../../state/projects";
import { serverEnvironment } from "../../state/server";
-import { readEnvironmentScope, useEnvironmentsWithScope } from "../../state/session";
+import {
+ readEnvironmentScope,
+ useEnvironmentScope,
+ useEnvironmentsWithScope,
+} from "../../state/session";
import { terminalEnvironment } from "../../state/terminal";
import { useAtomCommand } from "../../state/use-atom-command";
import { connectPairing } from "../../connection/onboarding";
@@ -712,6 +717,7 @@ function ConnectedAgentsStep({
displayName: string;
autoStart: boolean;
} | null>(null);
+ const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
// Re-probe on entry so freshly installed CLIs show up without a manual
// refresh; harmless when nothing changed (single-flighted per environment).
@@ -745,6 +751,11 @@ function ConnectedAgentsStep({
return (
<section>
<h2 className="mb-2 text-sm font-medium">{machineLabel}</h2>
+ {!canOperateTerminal ? (
+ <p className="mb-2 text-sm text-muted-foreground">
+ This connection cannot control terminals.
+ </p>
+ ) : null}
<div className="space-y-1.5">
{primaryAgents.map(({ driver, provider, instanceId }) =>
driver === "codex" && serverConfig !== null ? (
@@ -759,7 +770,11 @@ function ConnectedAgentsStep({
}
terminalOpen={terminalSession?.driver === driver}
onOpenTerminal={() => {
- if (provider === undefined) return;
+ if (
+ provider === undefined ||
+ !readEnvironmentScope(environmentId, AuthTerminalOperateScope)
+ )
+ return;
setTerminalSession({
environmentId,
driver,
@@ -785,9 +800,14 @@ function ConnectedAgentsStep({
driver={driver}
provider={provider}
terminalOpen={terminalSession?.driver === driver}
- terminalAvailable={serverConfig !== null}
+ terminalAvailable={serverConfig !== null && canOperateTerminal}
onOpenTerminal={() => {
- if (provider === undefined || serverConfig === null) return;
+ if (
+ provider === undefined ||
+ serverConfig === null ||
+ !readEnvironmentScope(environmentId, AuthTerminalOperateScope)
+ )
+ return;
setTerminalSession({
environmentId,
driver,
@@ -864,6 +884,7 @@ function OnboardingCodexSetup({
} | null;
readonly onAutoStartConsumed: () => void;
}) {
+ const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
const update = useAtomCommand(serverEnvironment.updateSettings, "Codex setup settings");
const instanceId =
createdAccount?.instanceId ??
@@ -911,7 +932,7 @@ function OnboardingCodexSetup({
driver="codex"
provider={provider}
terminalOpen={terminalOpen}
- terminalAvailable
+ terminalAvailable={canOperateTerminal}
onOpenTerminal={onOpenTerminal}
/>
) : (
@@ -1005,6 +1026,7 @@ function AgentInstallTerminal({
readonly onClose: () => void;
}) {
const { command, cwd, driver, environmentId, keybindings, providerInstanceId } = session;
+ const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
// Same terminal typography preference the thread drawer honors.
const [advancedTypography] = useLocalStorage(
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
@@ -1039,6 +1061,10 @@ function AgentInstallTerminal({
setupQueueRef.current = setupQueueRef.current.then(async () => {
if (activeSetupGenerationRef.current !== generation) return;
+ if (!readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
+ setSetupState("openFailed");
+ return;
+ }
const opened = await openTerminal({
environmentId,
input: {
@@ -1054,6 +1080,10 @@ function AgentInstallTerminal({
}
if (activeSetupGenerationRef.current !== generation) return;
+ if (!readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
+ setSetupState("writeFailed");
+ return;
+ }
const wrote = await writeTerminal({
environmentId,
@@ -1063,15 +1093,14 @@ function AgentInstallTerminal({
setSetupState(wrote._tag === "Success" ? "ready" : "writeFailed");
});
- // Every exit path unmounts the drawer (Done, Continue/Skip, card switch,
- // session exit), so this cleanup is the single place the PTY dies —
- // nothing is left running behind the wizard. An interrupted install is
- // re-runnable from the card.
+ // Every exit path unmounts the drawer. Close the PTY only while this
+ // connection still has terminal access; revocation leaves it running.
return () => {
if (activeSetupGenerationRef.current === generation) {
activeSetupGenerationRef.current = null;
}
setupQueueRef.current = setupQueueRef.current.then(async () => {
+ if (!readEnvironmentScope(environmentId, AuthTerminalOperateScope)) return;
await closeTerminal({
environmentId,
input: { threadId: AGENT_ONBOARDING_THREAD_ID, terminalId, deleteHistory: true },
@@ -1097,7 +1126,9 @@ function AgentInstallTerminal({
>
<div className="flex items-center justify-between border-b border-border/60 bg-background/60 px-3 py-1.5">
<span className="text-2xs font-medium text-muted-foreground">
- {setupState === "writeFailed" ? (
+ {!canOperateTerminal ? (
+ "This connection cannot control terminals."
+ ) : setupState === "writeFailed" ? (
<>
Run <code className="rounded bg-muted px-1 font-mono">{command}</code> in this
terminal.
@@ -1112,7 +1143,16 @@ function AgentInstallTerminal({
</span>
<div className="flex items-center gap-1">
{setupState === "openFailed" ? (
- <Button size="xs" variant="ghost" onClick={() => setSetupAttempt((value) => value + 1)}>
+ <Button
+ size="xs"
+ variant="ghost"
+ disabled={!canOperateTerminal}
+ onClick={() => {
+ if (readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
+ setSetupAttempt((value) => value + 1);
+ }
+ }}
+ >
Retry
</Button>
) : null}
diff --git a/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts b/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts
index 79a29fa6985..ee50ac2c427 100644
--- a/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts
@@ -6,8 +6,44 @@ import {
isQrShareableEndpoint,
isWslSettingsRowVisible,
selectQrEndpointOption,
+ togglePairingScopeSelection,
} from "./ConnectionsSettings.logic";
+describe("togglePairingScopeSelection", () => {
+ it.each([
+ {
+ label: "adds terminal:read when terminal:operate is selected",
+ current: ["orchestration:read"],
+ scope: "terminal:operate",
+ checked: true,
+ expected: ["orchestration:read", "terminal:operate", "terminal:read"],
+ },
+ {
+ label: "drops terminal:operate when terminal:read is cleared",
+ current: ["terminal:read", "terminal:operate", "relay:read"],
+ scope: "terminal:read",
+ checked: false,
+ expected: ["relay:read"],
+ },
+ {
+ label: "keeps terminal:read when terminal:operate is cleared",
+ current: ["terminal:read", "terminal:operate"],
+ scope: "terminal:operate",
+ checked: false,
+ expected: ["terminal:read"],
+ },
+ {
+ label: "toggles unrelated scopes on their own",
+ current: ["terminal:read"],
+ scope: "filesystem:read",
+ checked: true,
+ expected: ["terminal:read", "filesystem:read"],
+ },
+ ] as const)("$label", ({ current, scope, checked, expected }) => {
+ expect(togglePairingScopeSelection(current, scope, checked)).toEqual(expected);
+ });
+});
+
const baseWslState: DesktopWslState = {
enabled: false,
distro: null,
diff --git a/apps/web/src/components/settings/ConnectionsSettings.logic.ts b/apps/web/src/components/settings/ConnectionsSettings.logic.ts
index 4dcabbb4b40..2e26eba27d4 100644
--- a/apps/web/src/components/settings/ConnectionsSettings.logic.ts
+++ b/apps/web/src/components/settings/ConnectionsSettings.logic.ts
@@ -1,4 +1,34 @@
-import type { AdvertisedEndpoint, DesktopBridge, DesktopWslState } from "@t3tools/contracts";
+import {
+ type AdvertisedEndpoint,
+ type AuthGrantScope,
+ AuthTerminalOperateScope,
+ AuthTerminalReadScope,
+ type DesktopBridge,
+ type DesktopWslState,
+} from "@t3tools/contracts";
+
+/**
+ * Operating terminals without being able to list them leaves a client
+ * allocating a fresh shell for every script run it cannot see, so the pairing
+ * form keeps `terminal:read` alongside `terminal:operate`.
+ */
+export function togglePairingScopeSelection(
+ current: ReadonlyArray<AuthGrantScope>,
+ scope: AuthGrantScope,
+ checked: boolean,
+): ReadonlyArray<AuthGrantScope> {
+ const without = (scopes: ReadonlyArray<AuthGrantScope>) =>
+ scopes.filter((currentScope) => currentScope !== scope);
+ if (!checked) {
+ return scope === AuthTerminalReadScope
+ ? without(current).filter((currentScope) => currentScope !== AuthTerminalOperateScope)
+ : without(current);
+ }
+ const next = [...without(current), scope];
+ return scope === AuthTerminalOperateScope && !next.includes(AuthTerminalReadScope)
+ ? [...next, AuthTerminalReadScope]
+ : next;
+}
/** A missing access list says nothing about whether other clients exist. */
export function canRevokeOtherClients(
diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx
index e095e64af56..1520097eda7 100644
--- a/apps/web/src/components/settings/ConnectionsSettings.tsx
+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx
@@ -37,6 +37,7 @@ import {
AuthFilesystemWriteScope,
AuthStandardClientScopes,
AuthTerminalOperateScope,
+ AuthTerminalReadScope,
type AuthClientSession,
type AuthEnvironmentScope,
type AuthGrantScope,
@@ -75,6 +76,7 @@ import {
isQrShareableEndpoint,
isWslSettingsRowVisible,
selectQrEndpointOption,
+ togglePairingScopeSelection,
} from "./ConnectionsSettings.logic";
import {
SettingsPageContainer,
@@ -269,6 +271,11 @@ const PAIRING_SCOPE_OPTIONS: ReadonlyArray<{
title: "View diagnostics and usage",
description: "Read process diagnostics, resource history, and usage totals.",
},
+ {
+ scope: AuthTerminalReadScope,
+ title: "View terminals",
+ description: "Read existing terminal output and status.",
+ },
{
scope: AuthTerminalOperateScope,
title: "Use terminals",
@@ -1165,9 +1172,7 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio
}, [delegatableScopes, onPairingLinkCreated, pairingLabel, primaryEnvironmentId, selectedScopes]);
const togglePairingScope = useCallback((scope: AuthGrantScope, checked: boolean) => {
- setPairingScopes((current) =>
- checked ? [...current, scope] : current.filter((currentScope) => currentScope !== scope),
- );
+ setPairingScopes((current) => togglePairingScopeSelection(current, scope, checked));
}, []);
return (
@@ -1240,6 +1245,7 @@ const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderActio
AuthOrchestrationReadScope,
AuthFilesystemReadScope,
AuthDiagnosticsReadScope,
+ AuthTerminalReadScope,
].filter((scope) => delegatableScopes.includes(scope)),
)
}
diff --git a/apps/web/src/state/terminalSessionAvailability.test.ts b/apps/web/src/state/terminalSessionAvailability.test.ts
new file mode 100644
index 00000000000..1e054680f3c
--- /dev/null
+++ b/apps/web/src/state/terminalSessionAvailability.test.ts
@@ -0,0 +1,104 @@
+import { EnvironmentId, ThreadId, type TerminalSummary } from "@t3tools/contracts";
+import { act, createElement, useEffect } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
+
+import { useKnownTerminalSessions } from "./terminalSessions";
+
+const state = vi.hoisted(() => ({
+ canRead: true,
+ data: null as ReadonlyArray<TerminalSummary> | null,
+ error: null as string | null,
+}));
+
+vi.mock("./session", () => ({ useEnvironmentScope: () => state.canRead }));
+vi.mock("./terminal", () => ({ terminalEnvironment: { metadata: () => ({}) } }));
+vi.mock("./query", () => ({
+ useEnvironmentQuery: (atom: unknown) =>
+ atom === null ? { data: null, error: null } : { data: state.data, error: state.error },
+}));
+
+let root: Root;
+let current: ReturnType<typeof useKnownTerminalSessions>;
+const target = {
+ environmentId: EnvironmentId.make("secondary"),
+ threadId: ThreadId.make("thread"),
+};
+const terminal: TerminalSummary = {
+ threadId: "thread",
+ terminalId: "term-1",
+ cwd: "/repo",
+ worktreePath: null,
+ status: "running",
+ pid: 123,
+ exitCode: null,
+ exitSignal: null,
+ hasRunningSubprocess: true,
+ label: "Busy process",
+ updatedAt: "2026-09-05T00:00:00.000Z",
+};
+
+function Probe() {
+ const sessions = useKnownTerminalSessions(target);
+ useEffect(() => {
+ current = sessions;
+ }, [sessions]);
+ return null;
+}
+
+function render() {
+ return act(() => root.render(createElement(Probe)));
+}
+
+beforeEach(() => {
+ state.canRead = true;
+ state.data = null;
+ state.error = null;
+ const document = { nodeType: 9, addEventListener() {}, removeEventListener() {} };
+ const container = {
+ nodeType: 1,
+ tagName: "DIV",
+ namespaceURI: "http://www.w3.org/1999/xhtml",
+ ownerDocument: document,
+ addEventListener() {},
+ removeEventListener() {},
+ };
+ vi.stubGlobal("document", document);
+ vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ root = createRoot(container as unknown as HTMLElement);
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ vi.unstubAllGlobals();
+});
+
+it("distinguishes missing metadata from an authoritative empty list across scope changes", async () => {
+ await render();
+ expect(current).toBeNull();
+
+ state.data = [terminal];
+ await render();
+ expect(current?.[0]).toMatchObject({
+ target: { environmentId: "secondary", terminalId: "term-1" },
+ state: { hasRunningSubprocess: true },
+ });
+
+ state.canRead = false;
+ await render();
+ expect(current).toBeNull();
+
+ state.canRead = true;
+ state.data = [];
+ await render();
+ expect(current).toEqual([]);
+});
+
+it("does not reuse cached terminal metadata after a subscription failure", async () => {
+ state.data = [terminal];
+ await render();
+ state.error = "Access denied";
+ await render();
+ expect(current).toBeNull();
+});
diff --git a/apps/web/src/state/terminalSessions.ts b/apps/web/src/state/terminalSessions.ts
index 5e3a397826d..326b9f8db2a 100644
--- a/apps/web/src/state/terminalSessions.ts
+++ b/apps/web/src/state/terminalSessions.ts
@@ -8,6 +8,8 @@ import {
} from "@t3tools/client-runtime/state/terminal";
import {
ThreadId,
+ AuthTerminalReadScope,
+ AuthTerminalOperateScope,
type EnvironmentId,
type TerminalAttachInput,
type TerminalSummary,
@@ -16,6 +18,7 @@ import { useMemo } from "react";
import { useEnvironmentQuery } from "./query";
import { terminalEnvironment } from "./terminal";
+import { useEnvironmentScope } from "./session";
const EMPTY_KNOWN_TERMINAL_SESSIONS = Object.freeze<ReadonlyArray<KnownTerminalSession>>([]);
@@ -125,16 +128,25 @@ export function useAttachedTerminalSession(input: {
readonly environmentId: EnvironmentId | null;
readonly terminal: TerminalAttachInput | null;
}): TerminalSessionState {
+ const canRead = useEnvironmentScope(input.environmentId, AuthTerminalReadScope);
+ const canOperate = useEnvironmentScope(input.environmentId, AuthTerminalOperateScope);
const attach = useEnvironmentQuery(
input.environmentId !== null && input.terminal !== null
- ? terminalEnvironment.attach({
- environmentId: input.environmentId,
- input: input.terminal,
- })
+ ? canOperate
+ ? terminalEnvironment.attach({
+ environmentId: input.environmentId,
+ input: input.terminal,
+ })
+ : canRead
+ ? terminalEnvironment.observe({
+ environmentId: input.environmentId,
+ input: { threadId: input.terminal.threadId, terminalId: input.terminal.terminalId },
+ })
+ : null
: null,
);
const metadata = useEnvironmentQuery(
- input.environmentId === null
+ input.environmentId === null || !canRead
? null
: terminalEnvironment.metadata({
environmentId: input.environmentId,
@@ -160,9 +172,10 @@ export function useAttachedTerminalSession(input: {
export function useKnownTerminalSessions(input: {
readonly environmentId: EnvironmentId | null;
readonly threadId: ThreadId | null;
-}): ReadonlyArray<KnownTerminalSession> {
+}): ReadonlyArray<KnownTerminalSession> | null {
+ const canRead = useEnvironmentScope(input.environmentId, AuthTerminalReadScope);
const metadata = useEnvironmentQuery(
- input.environmentId === null
+ input.environmentId === null || !canRead
? null
: terminalEnvironment.metadata({
environmentId: input.environmentId,
@@ -170,8 +183,11 @@ export function useKnownTerminalSessions(input: {
}),
);
return useMemo(
- () => selectKnownTerminalSessions(metadata.data, input.environmentId, input.threadId),
- [input.environmentId, input.threadId, metadata.data],
+ () =>
+ metadata.data === null || metadata.error !== null
+ ? null
+ : selectKnownTerminalSessions(metadata.data, input.environmentId, input.threadId),
+ [input.environmentId, input.threadId, metadata.data, metadata.error],
);
}
@@ -180,5 +196,5 @@ export function useThreadRunningTerminalIds(input: {
readonly threadId: ThreadId | null;
}): ReadonlyArray<string> {
const sessions = useKnownTerminalSessions(input);
- return useMemo(() => selectRunningSubprocessTerminalIds(sessions), [sessions]);
+ return useMemo(() => selectRunningSubprocessTerminalIds(sessions ?? []), [sessions]);
}
diff --git a/apps/web/src/terminal/ghostty/surface.test.ts b/apps/web/src/terminal/ghostty/surface.test.ts
index 59150ee320a..cd08933e5c4 100644
--- a/apps/web/src/terminal/ghostty/surface.test.ts
+++ b/apps/web/src/terminal/ghostty/surface.test.ts
@@ -167,7 +167,13 @@ describe("GhosttyTerminalSurface visibility", () => {
resize() {
for (const callback of resizeCallbacks) callback();
},
- pointer(type: string, clientX: number, buttons: number, shiftKey = false, button = 0) {
+ pointer(
+ type: string,
+ clientX: number,
+ buttons: number,
+ modifiers: boolean | Partial<Pick<MouseEvent, "ctrlKey" | "metaKey" | "shiftKey">> = {},
+ button = 0,
+ ) {
canvas.dispatchEvent(
Object.assign(new Event(type, { cancelable: true }), {
clientX,
@@ -175,7 +181,7 @@ describe("GhosttyTerminalSurface visibility", () => {
pointerId: 1,
button,
buttons,
- shiftKey,
+ ...(typeof modifiers === "boolean" ? { shiftKey: modifiers } : modifiers),
}),
);
},
@@ -210,6 +216,113 @@ describe("GhosttyTerminalSurface visibility", () => {
vi.restoreAllMocks();
});
+ it.each([
+ { platform: "Linux x86_64", modifiers: { ctrlKey: true, metaKey: false } },
+ { platform: "MacIntel", modifiers: { ctrlKey: false, metaKey: true } },
+ ])(
+ "gates path links and preserves selection and URLs ($platform)",
+ async ({ platform, modifiers }) => {
+ vi.stubGlobal("navigator", { platform });
+ const harness = createHarness();
+ vi.spyOn(Event.prototype, "timeStamp", "get").mockImplementation(() => Date.now());
+ let canOpenPaths = false;
+ const openLink = vi.fn();
+ const surface = await harness.create({
+ canActivateLink: (text) => text.startsWith("https://") || canOpenPaths,
+ onLinkActivate: openLink,
+ });
+ surface.write("/repo/file.ts");
+ harness.flushFrame();
+ harness.pointer("pointermove", 5, 0, modifiers);
+ expect(surface.canvas.style.cursor).toBe("");
+ harness.pointer("pointerdown", 5, 1, modifiers);
+ harness.pointer("pointerup", 5, 0, modifiers);
+ expect(openLink).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(501);
+ harness.pointer("pointerdown", 5, 1);
+ harness.pointer("pointermove", 37, 1);
+ harness.pointer("pointerup", 37, 0);
+ expect(surface.getSelection()).toBe("/repo");
+
+ vi.advanceTimersByTime(501);
+ harness.pointer("pointermove", 5, 0, modifiers);
+ canOpenPaths = true;
+ surface.refreshLinkActivation();
+ expect(surface.canvas.style.cursor).toBe("pointer");
+ harness.pointer("pointerdown", 5, 1, modifiers);
+ harness.pointer("pointerup", 5, 0, modifiers);
+ expect(openLink).toHaveBeenCalledExactlyOnceWith("/repo/file.ts", expect.any(Event));
+
+ vi.advanceTimersByTime(501);
+ harness.pointer("pointerdown", 5, 1, modifiers);
+ canOpenPaths = false;
+ surface.refreshLinkActivation();
+ expect(surface.canvas.style.cursor).toBe("");
+ harness.pointer("pointerup", 5, 0, modifiers);
+ expect(openLink).toHaveBeenCalledOnce();
+
+ vi.advanceTimersByTime(501);
+ surface.resetAndWrite("https://t3.codes");
+ harness.flushFrame();
+ harness.pointer("pointermove", 5, 0, modifiers);
+ expect(surface.canvas.style.cursor).toBe("pointer");
+ harness.pointer("pointerdown", 5, 1, modifiers);
+ harness.pointer("pointerup", 5, 0, modifiers);
+ expect(openLink).toHaveBeenLastCalledWith("https://t3.codes", expect.any(Event));
+ },
+ );
+
+ it("resends an unchanged grid when authorization and attachment become ready", async () => {
+ const harness = createHarness();
+ let canOperate = false;
+ let attached = false;
+ const resizePty = vi.fn<(cols: number, rows: number) => void>();
+ const surface = await harness.create({
+ onResize: (cols, rows) => {
+ if (canOperate && attached) resizePty(cols, rows);
+ },
+ });
+ vi.advanceTimersByTime(150);
+ expect(resizePty).not.toHaveBeenCalled();
+
+ canOperate = true;
+ surface.resendSize();
+ vi.advanceTimersByTime(150);
+ expect(resizePty).not.toHaveBeenCalled();
+
+ attached = true;
+ surface.resendSize();
+ vi.advanceTimersByTime(150);
+ expect(resizePty).toHaveBeenCalledExactlyOnceWith(20, 6);
+ surface.fit();
+ vi.advanceTimersByTime(150);
+ expect(resizePty).toHaveBeenCalledOnce();
+
+ canOperate = false;
+ harness.mount.clientWidth = 248;
+ surface.fit();
+ vi.advanceTimersByTime(150);
+ expect(resizePty).toHaveBeenCalledOnce();
+ });
+
+ it("replays the current grid on reveal when a hidden host becomes ready", async () => {
+ const harness = createHarness();
+ const onResize = vi.fn<(cols: number, rows: number) => void>();
+ const surface = await harness.create({ onResize });
+ vi.advanceTimersByTime(150);
+ onResize.mockClear();
+
+ surface.setVisible(false);
+ surface.resendSize();
+ vi.advanceTimersByTime(150);
+ expect(onResize).not.toHaveBeenCalled();
+
+ surface.setVisible(true);
+ vi.advanceTimersByTime(150);
+ expect(onResize).toHaveBeenCalledExactlyOnceWith(20, 6);
+ });
+
it("stops hidden snapshots and paint while preserving live VT replies and the next cursor", async () => {
const harness = createHarness();
const surface = await harness.create();
diff --git a/apps/web/src/terminal/ghostty/surface.ts b/apps/web/src/terminal/ghostty/surface.ts
index be62ede4d06..1ec3f48bcff 100644
--- a/apps/web/src/terminal/ghostty/surface.ts
+++ b/apps/web/src/terminal/ghostty/surface.ts
@@ -547,6 +547,7 @@ export interface GhosttyTerminalSurfaceOptions {
readonly onSelectionChange: () => void;
readonly beforeKey: (event: KeyboardEvent) => boolean;
readonly onLinkActivate: (text: string, event: MouseEvent) => void;
+ readonly canActivateLink?: (text: string) => boolean;
/**
* A right-click the running application did not claim through mouse
* reporting. The host owns the menu, so it also owns preventing the browser
@@ -793,6 +794,12 @@ export class GhosttyTerminalSurface {
this.requestRender();
}
+ /** Re-evaluate link feedback after the host's available actions change. */
+ refreshLinkActivation(): void {
+ if (this.disposed) return;
+ this.refreshHoveredLink();
+ }
+
async setFont(font: GhosttyTerminalFont): Promise<void> {
if (this.disposed) return;
const fontSize = terminalFontSize(font.size);
@@ -855,6 +862,12 @@ export class GhosttyTerminalSurface {
this.applyFontMetrics();
};
+ /** Replay the measured grid after the host becomes ready to resize its PTY. */
+ resendSize(): void {
+ this.resizeNotified = false;
+ this.fit();
+ }
+
fit(): boolean {
if (this.disposed || !this.visible) return false;
const width = this.mount.clientWidth;
@@ -1926,6 +1939,11 @@ export class GhosttyTerminalSurface {
}
private linkAt(clientX: number, clientY: number): TerminalLinkWithRange | null {
+ const link = this.findLinkAt(clientX, clientY);
+ return link && this.options.canActivateLink?.(link.text) !== false ? link : null;
+ }
+
+ private findLinkAt(clientX: number, clientY: number): TerminalLinkWithRange | null {
if (!this.snapshot) return null;
const cell = terminalGridCellAt({
bounds: this.canvas.getBoundingClientRect(),
diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts
index dbf8150542f..1bbd507bb75 100644
--- a/packages/client-runtime/src/rpc/client.ts
+++ b/packages/client-runtime/src/rpc/client.ts
@@ -66,7 +66,8 @@ export type EnvironmentSubscriptionRpcTag =
| typeof WS_METHODS.subscribeVcsStatus
| typeof WS_METHODS.subscribeWorktreeSetup
| typeof WS_METHODS.subscribeProjectClones
- | typeof WS_METHODS.terminalAttach;
+ | typeof WS_METHODS.terminalAttach
+ | typeof WS_METHODS.terminalObserve;
export type EnvironmentStreamCommandRpcTag =
| typeof WS_METHODS.chatGptHandoffSubscribe
diff --git a/packages/client-runtime/src/state/terminal.ts b/packages/client-runtime/src/state/terminal.ts
index d336b9e25ca..8a3e3e74903 100644
--- a/packages/client-runtime/src/state/terminal.ts
+++ b/packages/client-runtime/src/state/terminal.ts
@@ -37,6 +37,15 @@ export function createTerminalEnvironmentAtoms<R, E>(
}) => JSON.stringify([environmentId, input.threadId, input.terminalId ?? null]);
const lifecycleConcurrency = { mode: "serial" as const, key: terminalThreadKey };
return {
+ observe: createEnvironmentSubscriptionAtomFamily(runtime, {
+ label: "environment-data:terminal:observe",
+ subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.terminalObserve>) =>
+ Stream.suspend(() =>
+ subscribe(WS_METHODS.terminalObserve, input).pipe(
+ Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent),
+ ),
+ ),
+ }),
attach: createEnvironmentSubscriptionAtomFamily(runtime, {
label: "environment-data:terminal:attach",
subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.terminalAttach>) =>
diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts
index 6ac40ae8241..5df81853adb 100644
--- a/packages/contracts/src/auth.ts
+++ b/packages/contracts/src/auth.ts
@@ -85,6 +85,7 @@ export const AuthProvidersManageScope = "providers:manage" as const;
export const AuthEnvironmentMaintainScope = "environment:maintain" as const;
export const AuthPreviewOperateScope = "preview:operate" as const;
export const AuthDiagnosticsReadScope = "diagnostics:read" as const;
+export const AuthTerminalReadScope = "terminal:read" as const;
export const AuthTerminalOperateScope = "terminal:operate" as const;
export const AuthSourceControlWriteScope = "source-control:write" as const;
export const AuthFilesystemReadScope = "filesystem:read" as const;
@@ -103,6 +104,7 @@ export const AuthEnvironmentScope = Schema.Literals([
AuthEnvironmentMaintainScope,
AuthPreviewOperateScope,
AuthDiagnosticsReadScope,
+ AuthTerminalReadScope,
AuthTerminalOperateScope,
AuthFilesystemReadScope,
AuthFilesystemWriteScope,
@@ -132,6 +134,7 @@ export const AuthStandardClientScopes = [
AuthEnvironmentMaintainScope,
AuthPreviewOperateScope,
AuthDiagnosticsReadScope,
+ AuthTerminalReadScope,
AuthTerminalOperateScope,
AuthSourceControlWriteScope,
AuthFilesystemReadScope,
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index f0593530923..ba4ce828879 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -218,6 +218,7 @@ import {
} from "./project.ts";
import {
TerminalAttachInput,
+ TerminalObserveInput,
TerminalAttachStreamEvent,
TerminalClearInput,
TerminalCloseInput,
@@ -406,6 +407,7 @@ export const WS_METHODS = {
// Terminal methods
terminalOpen: "terminal.open",
terminalAttach: "terminal.attach",
+ terminalObserve: "terminal.observe",
terminalWrite: "terminal.write",
terminalResize: "terminal.resize",
terminalClear: "terminal.clear",
@@ -1351,6 +1353,13 @@ const WsTerminalAttachRpc = Rpc.make(WS_METHODS.terminalAttach, {
stream: true,
});
+const WsTerminalObserveRpc = Rpc.make(WS_METHODS.terminalObserve, {
+ payload: TerminalObserveInput,
+ success: TerminalAttachStreamEvent,
+ error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),
+ stream: true,
+});
+
const WsTerminalWriteRpc = Rpc.make(WS_METHODS.terminalWrite, {
payload: TerminalWriteInput,
error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),
@@ -1866,6 +1875,7 @@ export const WsRpcGroup = RpcGroup.make(
WsReviewGetDiffFileContentsRpc,
WsTerminalOpenRpc,
WsTerminalAttachRpc,
+ WsTerminalObserveRpc,
WsTerminalWriteRpc,
WsTerminalResizeRpc,
WsTerminalClearRpc,
diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts
index 595ad543887..e8772e4d1ae 100644
--- a/packages/contracts/src/terminal.ts
+++ b/packages/contracts/src/terminal.ts
@@ -60,6 +60,9 @@ export const TerminalAttachInput = Schema.Struct({
});
export type TerminalAttachInput = typeof TerminalAttachInput.Type;
+export const TerminalObserveInput = TerminalSessionInput;
+export type TerminalObserveInput = Schema.Codec.Encoded<typeof TerminalObserveInput>;
+
export const TerminalWriteInput = Schema.Struct({
...TerminalSessionInput.fields,
data: Schema.String.check(Schema.isNonEmpty()).check(Schema.isMaxLength(65_536)),
diff --git a/packages/shared/src/terminalLabels.test.ts b/packages/shared/src/terminalLabels.test.ts
index b8a146b0cc2..2b2d73418b1 100644
--- a/packages/shared/src/terminalLabels.test.ts
+++ b/packages/shared/src/terminalLabels.test.ts
@@ -1,10 +1,13 @@
import { describe, expect, it } from "vite-plus/test";
import type { TerminalSummary } from "@t3tools/contracts";
-import { DEFAULT_TERMINAL_ID } from "@t3tools/contracts";
+import { DEFAULT_TERMINAL_ID, TerminalOpenInput } from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
import { getTerminalLabel, nextTerminalId, resolveTerminalSessionLabel } from "./terminalLabels.ts";
+const decodeTerminalOpen = Schema.decodeUnknownSync(TerminalOpenInput);
+
describe("getTerminalLabel", () => {
it("uses the numeric suffix for term-* ids", () => {
expect(getTerminalLabel(DEFAULT_TERMINAL_ID)).toBe("Terminal 1");
@@ -16,6 +19,10 @@ describe("getTerminalLabel", () => {
it("falls back to the raw id for unknown shapes", () => {
expect(getTerminalLabel("custom-session")).toBe("custom-session");
});
+
+ it("keeps a numbered label for terminals allocated without host metadata", () => {
+ expect(getTerminalLabel("term-2-783c91cc-a413-47c7-8312-c2a5a1f05e40")).toBe("Terminal 2");
+ });
});
describe("resolveTerminalSessionLabel", () => {
@@ -50,4 +57,20 @@ describe("nextTerminalId", () => {
expect(nextTerminalId(["", " ", DEFAULT_TERMINAL_ID])).toBe("term-2");
expect(nextTerminalId(["", " "])).toBe("term-1");
});
+
+ it("avoids unseen sessions when metadata is unavailable and resumes normal numbering", () => {
+ const first = nextTerminalId([], "783c91cc-a413-47c7-8312-c2a5a1f05e40");
+ const second = nextTerminalId([first], "102315fc-ceef-45c4-b978-c4d4947d3c26");
+ expect(first).not.toBe(DEFAULT_TERMINAL_ID);
+ expect(second).not.toBe(first);
+ expect(getTerminalLabel(second)).toBe("Terminal 2");
+ expect(nextTerminalId([first, second])).toBe("term-3");
+ expect(
+ decodeTerminalOpen({
+ threadId: "thread",
+ terminalId: second,
+ cwd: "/workspace",
+ }),
+ ).toMatchObject({ terminalId: second });
+ });
});
diff --git a/packages/shared/src/terminalLabels.ts b/packages/shared/src/terminalLabels.ts
index 1cdae101430..9873c32c4cb 100644
--- a/packages/shared/src/terminalLabels.ts
+++ b/packages/shared/src/terminalLabels.ts
@@ -1,8 +1,14 @@
import type { TerminalSummary } from "@t3tools/contracts";
+function terminalNumber(terminalId: string): string | undefined {
+ return /^term(?:inal)?-(\d+)(?:-[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12})?$/i.exec(
+ terminalId,
+ )?.[1];
+}
+
/** Human-readable label for a terminal tab; matches mobile and web sidebars. */
export function getTerminalLabel(terminalId: string): string {
- const numericSuffix = /^term(?:inal)?-(\d+)$/i.exec(terminalId)?.[1];
+ const numericSuffix = terminalNumber(terminalId);
if (numericSuffix) {
return `Terminal ${numericSuffix}`;
}
@@ -26,15 +32,18 @@ export function resolveTerminalSessionLabel(
* Client-side terminal id allocator. Ids are ALWAYS chosen by the client and sent explicitly
* on every `terminal.open` / `terminal.attach` call — the server never allocates.
*
- * Returns the lowest unused `term-N` id (starting at `term-1`), skipping any ids already in
- * `existingTerminalIds`.
+ * Returns the lowest unused `term-N` number. When metadata is unavailable,
+ * callers append a UUID so an unseen host session cannot be reused accidentally.
*/
-export function nextTerminalId(existingTerminalIds: ReadonlyArray<string>): string {
- const usedIds = new Set(existingTerminalIds.filter((id) => id.trim().length > 0));
+export function nextTerminalId(
+ existingTerminalIds: ReadonlyArray<string>,
+ uniqueSuffix?: string,
+): string {
+ const usedNumbers = new Set(existingTerminalIds.map(terminalNumber));
let nextIndex = 1;
- while (usedIds.has(`term-${nextIndex}`)) {
+ while (usedNumbers.has(String(nextIndex))) {
nextIndex += 1;
}
- return `term-${nextIndex}`;
+ return `term-${nextIndex}${uniqueSuffix === undefined ? "" : `-${uniqueSuffix}`}`;
}