TypeScript
refactor(web): open and close thread terminals through one hook (#20289)
Julius Marminged109aa74ea07
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex a5ae5e41486..c94d10c5c6c 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -25,6 +25,7 @@ import {import { useLoadBalancedEnvironment } from "../hooks/useLoadBalancedEnvironment";import { useScratchProject } from "../hooks/useScratchProject";import { useStableCallback } from "../hooks/useStableCallback";+import { useThreadTerminalActions } from "./terminal/useThreadTerminalActions";import { usePendingThreadRequests } from "./chat/usePendingThreadRequests";import { isScratchProject } from "@t3tools/client-runtime/state/projects";import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";@@ -76,7 +77,6 @@ import {resolveEnvironmentMachineKind,resolveProjectProviderInstanceEnabled,RuntimeMode,- TerminalOpenInput,type WorktreeSetupSnapshot,} from "@t3tools/contracts";import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";@@ -125,11 +125,7 @@ import {resolvePromptInjectedEffort,resolveSelectableModel,} from "@t3tools/shared/model";-import {- projectScriptCwd,- projectScriptRuntimeEnv,- resolveProjectScripts,-} from "@t3tools/shared/projectScripts";+import { projectScriptCwd, resolveProjectScripts } from "@t3tools/shared/projectScripts";import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";import {@@ -140,7 +136,7 @@ import { resolveProjectSettings } from "@t3tools/shared/projectSettings";import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";import { truncate } from "@t3tools/shared/String";import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";-import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";+import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";import { Debouncer } from "@tanstack/react-pacer";import { useAtomValue } from "@effect/atom-react";import { Atom } from "effect/reactivity";@@ -400,7 +396,6 @@ import {primaryServerKeybindingsAtom,serverEnvironment,} from "../state/server";-import { terminalEnvironment } from "../state/terminal";import { threadEnvironment } from "../state/threads";import { workspacePreparationRetryRunIds } from "@t3tools/client-runtime/state/turn-item-presentation";import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";@@ -1025,9 +1020,6 @@ export default function ChatView(props: ChatViewProps) {const removeKeybinding = useAtomCommand(serverEnvironment.removeKeybinding, {reportFailure: false,});- const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");- const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");- const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close");const createThread = useOrchestrationCommand(threadEnvironment.create, { reportFailure: false });const deleteThread = useOrchestrationCommand(threadEnvironment.delete, { reportFailure: false });const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {@@ -1602,6 +1594,7 @@ export default function ChatView(props: ChatViewProps) {return labels;}, [activeThreadKnownSessions]);const activeThreadRef = useActiveThreadRef(activeThread);+ const terminalActions = useThreadTerminalActions(activeThreadRef);const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;const activeEnvironmentServerBrowser = useEnvironmentSupportsServerBrowser(activeThreadRef?.environmentId ?? null,@@ -1690,18 +1683,7 @@ export default function ChatView(props: ChatViewProps) {),[rightPanelState.surfaces],);- const allocatableActiveTerminalIds = useMemo(- () => [...new Set([...activeKnownTerminalIds, ...panelTerminalIds])],- [activeKnownTerminalIds, panelTerminalIds],- );const canReuseTerminal = activeThreadKnownSessionsRaw !== null;- const allocateTerminalId = () =>- nextTerminalId(- allocatableActiveTerminalIds,- canReuseTerminal && readEnvironmentScope(environmentId, AuthTerminalReadScope)- ? undefined- : randomUUID(),- );const previewPanelOpen = activeRightPanelKind === "preview" && browserAvailable;const rightPanelOpen = rightPanelState.isOpen;const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =@@ -3871,119 +3853,40 @@ export default function ChatView(props: ChatViewProps) {storeEnsureTerminal(activeThreadRef, existingTerminalId, { open: true, active: true });return;}- if (!activeThreadId || !activeProject) {- return;- }- const cwdForOpen = gitCwd ?? activeProject.workspaceRoot;- if (!cwdForOpen) {- return;- }- const terminalId = allocateTerminalId();- storeEnsureTerminal(activeThreadRef, terminalId, { open: true });- void openTerminal({- environmentId,- input: {- threadId: activeThreadId,- terminalId,- cwd: cwdForOpen,- ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),- env: projectScriptRuntimeEnv({- project: { cwd: activeProject.workspaceRoot },- worktreePath: activeThreadWorktreePath,- }),- },- });+ void terminalActions.launchTerminal({+ place: (terminalId) => storeEnsureTerminal(activeThreadRef, terminalId, { open: true }),+ })?.result;return;}setTerminalOpen(nextOpen);};const toggleTerminalVisibilityStable = useStableCallback(toggleTerminalVisibility);const splitTerminal = (direction: "horizontal" | "vertical" = "horizontal") => {- if (- !hasTerminalWriteAccess() ||- !activeThreadRef ||- hasReachedSplitLimit ||- !activeThreadId ||- !activeProject- ) {- return;- }- const cwdForOpen = gitCwd ?? activeProject.workspaceRoot;- if (!cwdForOpen) {- return;- }- const terminalId = allocateTerminalId();- if (direction === "vertical") {- storeSplitTerminalVertical(activeThreadRef, terminalId);- } else {- storeSplitTerminal(activeThreadRef, terminalId);- }- setTerminalFocusRequestId((value) => value + 1);- void openTerminal({- environmentId,- input: {- threadId: activeThreadId,- terminalId,- cwd: cwdForOpen,- ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),- env: projectScriptRuntimeEnv({- project: { cwd: activeProject.workspaceRoot },- worktreePath: activeThreadWorktreePath,- }),- },+ if (!activeThreadRef || hasReachedSplitLimit) return;+ const launched = terminalActions.launchTerminal({+ place: (terminalId) =>+ direction === "vertical"+ ? storeSplitTerminalVertical(activeThreadRef, terminalId)+ : storeSplitTerminal(activeThreadRef, terminalId),});+ if (!launched) return;+ setTerminalFocusRequestId((value) => value + 1);+ void launched.result;};const splitTerminalStable = useStableCallback(splitTerminal);const createNewTerminal = () => {- if (!hasTerminalWriteAccess() || !activeThreadRef || !activeThreadId || !activeProject) {- return;- }- const cwdForOpen = gitCwd ?? activeProject.workspaceRoot;- if (!cwdForOpen) {- return;- }- const terminalId = allocateTerminalId();- storeNewTerminal(activeThreadRef, terminalId);- setTerminalFocusRequestId((value) => value + 1);- void openTerminal({- environmentId,- input: {- threadId: activeThreadId,- terminalId,- cwd: cwdForOpen,- ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),- env: projectScriptRuntimeEnv({- project: { cwd: activeProject.workspaceRoot },- worktreePath: activeThreadWorktreePath,- }),- },+ if (!activeThreadRef) return;+ const launched = terminalActions.launchTerminal({+ place: (terminalId) => storeNewTerminal(activeThreadRef, terminalId),});+ if (!launched) return;+ setTerminalFocusRequestId((value) => value + 1);+ void launched.result;};const createNewTerminalStable = useStableCallback(createNewTerminal);const closeTerminal = (terminalId: string) => {- if (!hasTerminalWriteAccess() || !activeThreadId || !activeThreadRef) return;- const fallbackExitWrite = () =>- writeTerminal({- environmentId,- input: { threadId: activeThreadId, terminalId, data: "exit\n" },- });- void (async () => {- const closeResult = await closeTerminalMutation({- environmentId,- input: {- threadId: activeThreadId,- terminalId,- deleteHistory: true,- },- });- if (- closeResult._tag === "Failure" &&- !isAtomCommandInterrupted(closeResult) &&- hasTerminalWriteAccess()- ) {- await fallbackExitWrite();- }- })();+ if (!hasTerminalWriteAccess() || !activeThreadRef) return;+ terminalActions.closeTerminalSession(terminalId);storeCloseTerminal(activeThreadRef, terminalId);setTerminalFocusRequestId((value) => value + 1);};@@ -4026,39 +3929,20 @@ export default function ChatView(props: ChatViewProps) {}setTerminalFocusRequestId((value) => value + 1);- const runtimeEnv = projectScriptRuntimeEnv({- project: {- cwd: activeProject.workspaceRoot,- },- worktreePath: targetWorktreePath,+ const launched = terminalActions.launchTerminal({+ place: (terminalId) =>+ shouldCreateNewTerminal+ ? storeNewTerminal(activeThreadRef, terminalId)+ : storeSetActiveTerminal(activeThreadRef, terminalId),+ ...(shouldCreateNewTerminal+ ? { size: { cols: SCRIPT_TERMINAL_COLS, rows: SCRIPT_TERMINAL_ROWS } }+ : { terminalId: baseTerminalId }),+ location: { cwd: targetCwd, worktreePath: targetWorktreePath },...(options?.env ? { extraEnv: options.env } : {}),});- const targetTerminalId = shouldCreateNewTerminal ? allocateTerminalId() : baseTerminalId;- const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal- ? {- threadId: activeThreadId,- terminalId: targetTerminalId,- cwd: targetCwd,- ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),- env: runtimeEnv,- cols: SCRIPT_TERMINAL_COLS,- rows: SCRIPT_TERMINAL_ROWS,- }- : {- threadId: activeThreadId,- terminalId: targetTerminalId,- cwd: targetCwd,- ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),- env: runtimeEnv,- };-- if (shouldCreateNewTerminal) {- storeNewTerminal(activeThreadRef, targetTerminalId);- } else {- storeSetActiveTerminal(activeThreadRef, targetTerminalId);- }-- const openResult = await openTerminal({ environmentId, input: openTerminalInput });+ if (!launched) return;+ const targetTerminalId = launched.terminalId;+ const openResult = await launched.result;if (openResult._tag === "Failure") {if (!isAtomCommandInterrupted(openResult)) {const error = squashAtomCommandFailure(openResult);@@ -4070,15 +3954,11 @@ export default function ChatView(props: ChatViewProps) {return;}- if (!hasTerminalWriteAccess()) return;- const writeResult = await writeTerminal({- environmentId,- input: {- threadId: activeThreadId,- terminalId: targetTerminalId,- data: `${script.command}\r`,- },- });+ const writeResult = await terminalActions.writeToTerminal(+ targetTerminalId,+ `${script.command}\r`,+ );+ if (!writeResult) return;if (writeResult._tag === "Failure") {if (!isAtomCommandInterrupted(writeResult)) {const error = squashAtomCommandFailure(writeResult);@@ -4846,56 +4726,34 @@ export default function ChatView(props: ChatViewProps) {};const togglePreviewPanelStable = useStableCallback(togglePreviewPanel);const addTerminalSurface = () => {- if (!hasTerminalWriteAccess() || !activeThreadRef || !activeThreadId || !activeProject) return;- const cwd = gitCwd ?? activeProject.workspaceRoot;- const terminalId = allocateTerminalId();- useRightPanelStore.getState().openTerminal(activeThreadRef, terminalId);- setTerminalFocusRequestId((value) => value + 1);- void openTerminal({- environmentId: activeThreadRef.environmentId,- input: {- threadId: activeThreadId,- terminalId,- cwd,- ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),- env: projectScriptRuntimeEnv({- project: { cwd: activeProject.workspaceRoot },- worktreePath: activeThreadWorktreePath,- }),- },+ if (!activeThreadRef) return;+ const launched = terminalActions.launchTerminal({+ place: (terminalId) =>+ useRightPanelStore.getState().openTerminal(activeThreadRef, terminalId),});+ if (!launched) return;+ setTerminalFocusRequestId((value) => value + 1);+ void launched.result;};const addTerminalSurfaceStable = useStableCallback(addTerminalSurface);const splitPanelTerminal = (direction: "horizontal" | "vertical" = "horizontal") => {if (- !hasTerminalWriteAccess() ||!activeThreadRef ||- !activeThreadId ||- !activeProject ||activeRightPanelSurface?.kind !== "terminal" ||activeRightPanelSurface.terminalIds.length >= MAX_TERMINALS_PER_GROUP) {return;}- const terminalId = allocateTerminalId();- const cwd = gitCwd ?? activeProject.workspaceRoot;- useRightPanelStore- .getState()- .splitTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId, direction);- setTerminalFocusRequestId((value) => value + 1);- void openTerminal({- environmentId: activeThreadRef.environmentId,- input: {- threadId: activeThreadId,- terminalId,- cwd,- ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),- env: projectScriptRuntimeEnv({- project: { cwd: activeProject.workspaceRoot },- worktreePath: activeThreadWorktreePath,- }),- },+ const surfaceId = activeRightPanelSurface.id;+ const launched = terminalActions.launchTerminal({+ place: (terminalId) =>+ useRightPanelStore+ .getState()+ .splitTerminal(activeThreadRef, surfaceId, terminalId, direction),});+ if (!launched) return;+ setTerminalFocusRequestId((value) => value + 1);+ void launched.result;};const splitPanelTerminalStable = useStableCallback(splitPanelTerminal);const splitPanelTerminalVertical = () => {@@ -4917,10 +4775,7 @@ export default function ChatView(props: ChatViewProps) {activeRightPanelSurface?.kind !== "terminal")return;- void closeTerminalMutation({- environmentId: activeThreadRef.environmentId,- input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true },- });+ terminalActions.closeTerminalSession(terminalId);storeCloseTerminal(activeThreadRef, terminalId);useRightPanelStore.getState()@@ -5004,10 +4859,7 @@ export default function ChatView(props: ChatViewProps) {) {for (const terminalId of surface.terminalIds) {storeCloseTerminal(activeThreadRef, terminalId);- void closeTerminalMutation({- environmentId: activeThreadRef.environmentId,- input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true },- });+ terminalActions.closeTerminalSession(terminalId);}}}diff --git a/apps/web/src/components/PersistentThreadTerminals.tsx b/apps/web/src/components/PersistentThreadTerminals.tsxindex 0e630fe4209..9dfd67bceab 100644--- a/apps/web/src/components/PersistentThreadTerminals.tsx+++ b/apps/web/src/components/PersistentThreadTerminals.tsx@@ -1,30 +1,28 @@import {AuthTerminalOperateScope,- AuthTerminalReadScope,type EnvironmentId,type ResolvedKeybindingsConfig,type ScopedThreadRef,type ThreadId,} from "@t3tools/contracts";import { scopeProjectRef } from "@t3tools/client-runtime/environment";-import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";-import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";+import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";import { memo, useCallback, useEffect, useMemo, useState } from "react";import { useComposerDraftStore } from "../composerDraftStore";+import { useStableCallback } from "../hooks/useStableCallback";import type { TerminalContextSelection } from "../lib/terminalContext";-import { cn, randomUUID } from "~/lib/utils";+import { cn } from "~/lib/utils";import {selectThreadRightPanelState,useRightPanelStore,type RightPanelSurface,} from "../rightPanelStore";import { useProject, useThreadShell } from "../state/entities";-import { readEnvironmentScope, useEnvironmentScope } from "../state/session";-import { terminalEnvironment } from "../state/terminal";+import { useEnvironmentScope } from "../state/session";import { useKnownTerminalSessions } from "../state/terminalSessions";-import { useAtomCommand } from "../state/use-atom-command";import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";+import { useThreadTerminalActions } from "./terminal/useThreadTerminalActions";import ThreadTerminalDrawer from "./ThreadTerminalDrawer";/** Where a drawer or panel opens new terminals when a script run overrides the thread's own. */@@ -100,13 +98,7 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTermonAddTerminalContext,}: 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");+ const terminalActions = useThreadTerminalActions(threadRef);const serverThread = useThreadShell(threadRef);const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));const projectRef = serverThread@@ -188,30 +180,6 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm() => drawerTerminalSessions.map((session) => session.target.terminalId),[drawerTerminalSessions],);- // Every client-side id source participates in allocation: the server list- // lags fresh opens, and panel terminals are filtered out of the drawer's- // sessions — an id collision attaches two viewports to one PTY session.- const allocatableTerminalIds = useMemo(- () => [- ...new Set([- ...serverOrderedTerminalIds,- ...terminalUiState.terminalIds,- ...panelTerminalIds,- ]),- ],- [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(@@ -277,94 +245,25 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm[storeSetTerminalHeight, threadRef],);- const splitTerminal = useCallback(() => {- if (!hasTerminalWriteAccess() || !cwd) {- return;- }- const terminalId = allocateTerminalId();- storeSplitTerminal(threadRef, terminalId);- bumpFocusRequestId();- void openTerminal({- environmentId: threadRef.environmentId,- input: {- threadId,- terminalId,- cwd,- ...(effectiveWorktreePath != null ? { worktreePath: effectiveWorktreePath } : {}),- env: runtimeEnv,- },- });- }, [- allocateTerminalId,- bumpFocusRequestId,- cwd,- effectiveWorktreePath,- runtimeEnv,- storeSplitTerminal,- threadId,- threadRef,- openTerminal,- hasTerminalWriteAccess,- ]);- const splitTerminalVertical = useCallback(() => {- if (!hasTerminalWriteAccess() || !cwd) {- return;- }- const terminalId = allocateTerminalId();- storeSplitTerminalVertical(threadRef, terminalId);- bumpFocusRequestId();- void openTerminal({- environmentId: threadRef.environmentId,- input: {- threadId,- terminalId,- cwd,- ...(effectiveWorktreePath != null ? { worktreePath: effectiveWorktreePath } : {}),- env: runtimeEnv,- },+ const launchDrawerTerminal = (place: (terminalId: string) => void) => {+ if (!cwd) return;+ const launched = terminalActions.launchTerminal({+ place,+ location: { cwd, worktreePath: effectiveWorktreePath },});- }, [- allocateTerminalId,- bumpFocusRequestId,- cwd,- effectiveWorktreePath,- openTerminal,- hasTerminalWriteAccess,- runtimeEnv,- storeSplitTerminalVertical,- threadId,- threadRef,- ]);-- const createNewTerminal = useCallback(() => {- if (!hasTerminalWriteAccess() || !cwd) {- return;- }- const terminalId = allocateTerminalId();- storeNewTerminal(threadRef, terminalId);+ if (!launched) return;bumpFocusRequestId();- void openTerminal({- environmentId: threadRef.environmentId,- input: {- threadId,- terminalId,- cwd,- ...(effectiveWorktreePath != null ? { worktreePath: effectiveWorktreePath } : {}),- env: runtimeEnv,- },- });- }, [- bumpFocusRequestId,- cwd,- effectiveWorktreePath,- allocateTerminalId,- runtimeEnv,- storeNewTerminal,- threadId,- threadRef,- openTerminal,- hasTerminalWriteAccess,- ]);+ void launched.result;+ };+ const splitTerminal = useStableCallback(() =>+ launchDrawerTerminal((terminalId) => storeSplitTerminal(threadRef, terminalId)),+ );+ const splitTerminalVertical = useStableCallback(() =>+ launchDrawerTerminal((terminalId) => storeSplitTerminalVertical(threadRef, terminalId)),+ );+ const createNewTerminal = useStableCallback(() =>+ launchDrawerTerminal((terminalId) => storeNewTerminal(threadRef, terminalId)),+ );const activateTerminal = useCallback((terminalId: string) => {@@ -374,46 +273,12 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm[bumpFocusRequestId, storeSetActiveTerminal, threadRef],);- const closeTerminal = useCallback(- (terminalId: string) => {- if (!hasTerminalWriteAccess()) return;- const fallbackExitWrite = () =>- writeTerminal({- environmentId: threadRef.environmentId,- input: { threadId, terminalId, data: "exit\n" },- });-- void (async () => {- const closeResult = await closeTerminalMutation({- environmentId: threadRef.environmentId,- input: {- threadId,- terminalId,- deleteHistory: true,- },- });- if (- closeResult._tag === "Failure" &&- !isAtomCommandInterrupted(closeResult) &&- hasTerminalWriteAccess()- ) {- await fallbackExitWrite();- }- })();-- storeCloseTerminal(threadRef, terminalId);- bumpFocusRequestId();- },- [- bumpFocusRequestId,- storeCloseTerminal,- threadId,- threadRef,- closeTerminalMutation,- hasTerminalWriteAccess,- writeTerminal,- ],- );+ const closeTerminal = useStableCallback((terminalId: string) => {+ if (!terminalActions.canWrite()) return;+ terminalActions.closeTerminalSession(terminalId);+ storeCloseTerminal(threadRef, terminalId);+ bumpFocusRequestId();+ });const handleAddTerminalContext = useCallback((selection: TerminalContextSelection) => {diff --git a/apps/web/src/components/terminal/useThreadTerminalActions.ts b/apps/web/src/components/terminal/useThreadTerminalActions.tsnew file mode 100644index 00000000000..2b4b922a184--- /dev/null+++ b/apps/web/src/components/terminal/useThreadTerminalActions.ts@@ -0,0 +1,162 @@+import {+ AuthTerminalOperateScope,+ AuthTerminalReadScope,+ type ScopedThreadRef,+} from "@t3tools/contracts";+import { scopeProjectRef } from "@t3tools/client-runtime/environment";+import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";+import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";+import { nextTerminalId } from "@t3tools/shared/terminalLabels";+import { useComposerDraftStore } from "../../composerDraftStore";+import { useStableCallback } from "../../hooks/useStableCallback";+import { randomUUID } from "~/lib/utils";+import { selectThreadRightPanelState, useRightPanelStore } from "../../rightPanelStore";+import { useProject, useThreadShell } from "../../state/entities";+import { readEnvironmentScope } from "../../state/session";+import { terminalEnvironment } from "../../state/terminal";+import { useKnownTerminalSessions } from "../../state/terminalSessions";+import { useAtomCommand } from "../../state/use-atom-command";+import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../../terminalUiStateStore";++/** Where a new terminal starts. Omitted fields fall back to the thread's project and worktree. */+export interface TerminalLaunchLocation {+ readonly cwd: string;+ readonly worktreePath: string | null;+}++/**+ * Opens and closes a thread's terminal sessions. Every surface that hosts a+ * terminal (the drawer, a right panel tab, the setup flow, script runs) goes+ * through here, so ids are allocated from one view of the thread's terminals+ * and every new session starts with the same cwd and environment.+ */+export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) {+ const openTerminalCommand = useAtomCommand(terminalEnvironment.open, "terminal open");+ const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");+ const closeTerminalCommand = useAtomCommand(terminalEnvironment.close, "terminal close");+ const serverThread = useThreadShell(threadRef);+ const draftThread = useComposerDraftStore((store) =>+ threadRef ? store.getDraftThreadByRef(threadRef) : null,+ );+ const projectRef = serverThread+ ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)+ : draftThread+ ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)+ : null;+ const project = useProject(projectRef);+ const threadWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;+ const knownSessions = useKnownTerminalSessions({+ environmentId: threadRef?.environmentId ?? null,+ threadId: threadRef?.threadId ?? null,+ });+ const drawerTerminalIds = useTerminalUiStateStore(+ (state) => selectThreadTerminalUiState(state.terminalUiStateByThreadKey, threadRef).terminalIds,+ );+ const panelSurfaces = useRightPanelStore(+ (state) => selectThreadRightPanelState(state.byThreadKey, threadRef).surfaces,+ );++ const canWrite = () =>+ threadRef !== null && readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope);++ // Every client-side id source participates: the server list lags fresh opens,+ // and an id collision attaches two viewports to one PTY session. Without a+ // readable session list the next free number may already be taken on the+ // server, so the id gets a unique suffix.+ const allocateTerminalId = () => {+ const ids = new Set([+ ...(knownSessions ?? []).map((session) => session.target.terminalId),+ ...drawerTerminalIds,+ ...panelSurfaces.flatMap((surface) =>+ surface.kind === "terminal" ? surface.terminalIds : [],+ ),+ ]);+ const canReuse =+ knownSessions !== null &&+ threadRef !== null &&+ readEnvironmentScope(threadRef.environmentId, AuthTerminalReadScope);+ return nextTerminalId([...ids], canReuse ? undefined : randomUUID());+ };++ const defaultLaunchLocation = (): TerminalLaunchLocation | null =>+ project+ ? {+ cwd: projectScriptCwd({+ project: { cwd: project.workspaceRoot },+ worktreePath: threadWorktreePath,+ }),+ worktreePath: threadWorktreePath,+ }+ : null;++ /**+ * Starts a session for `terminalId` on the server. `place` records the id in+ * the surface that will show it, before the open resolves, so the viewport+ * mounts while the session starts.+ */+ const launchTerminal = (input: {+ readonly place: (terminalId: string) => void;+ readonly terminalId?: string;+ readonly location?: TerminalLaunchLocation | null;+ readonly extraEnv?: Record<string, string>;+ readonly size?: { readonly cols: number; readonly rows: number };+ }) => {+ if (!threadRef || !canWrite() || !project) return null;+ const location = input.location ?? defaultLaunchLocation();+ if (!location) return null;+ const terminalId = input.terminalId ?? allocateTerminalId();+ input.place(terminalId);+ const result = openTerminalCommand({+ environmentId: threadRef.environmentId,+ input: {+ threadId: threadRef.threadId,+ terminalId,+ cwd: location.cwd,+ ...(location.worktreePath !== null ? { worktreePath: location.worktreePath } : {}),+ env: projectScriptRuntimeEnv({+ project: { cwd: project.workspaceRoot },+ worktreePath: location.worktreePath,+ ...(input.extraEnv ? { extraEnv: input.extraEnv } : {}),+ }),+ ...input.size,+ },+ });+ return { terminalId, result };+ };++ /** Ends a session and deletes its history. A failed close falls back to typing `exit`. */+ const closeTerminalSession = (terminalId: string) => {+ if (!threadRef || !canWrite()) return;+ const environmentId = threadRef.environmentId;+ const threadId = threadRef.threadId;+ void (async () => {+ const closeResult = await closeTerminalCommand({+ environmentId,+ input: { threadId, terminalId, deleteHistory: true },+ });+ if (+ closeResult._tag === "Failure" &&+ !isAtomCommandInterrupted(closeResult) &&+ readEnvironmentScope(environmentId, AuthTerminalOperateScope)+ ) {+ await writeTerminal({ environmentId, input: { threadId, terminalId, data: "exit\n" } });+ }+ })();+ };++ const writeToTerminal = (terminalId: string, data: string) => {+ if (!threadRef || !canWrite()) return null;+ return writeTerminal({+ environmentId: threadRef.environmentId,+ input: { threadId: threadRef.threadId, terminalId, data },+ });+ };++ return {+ canWrite: useStableCallback(canWrite),+ allocateTerminalId: useStableCallback(allocateTerminalId),+ launchTerminal: useStableCallback(launchTerminal),+ closeTerminalSession: useStableCallback(closeTerminalSession),+ writeToTerminal: useStableCallback(writeToTerminal),+ };+}