The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | AuthTerminalOperateScope, |
| 3 | AuthTerminalReadScope, |
| 4 | type ScopedThreadRef, |
| 5 | } from "@t3tools/contracts"; |
| 6 | import { scopeProjectRef } from "@t3tools/client-runtime/environment"; |
| 7 | import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime"; |
| 8 | import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts"; |
| 9 | import { nextTerminalId } from "@t3tools/shared/terminalLabels"; |
| 10 | import { useComposerDraftStore } from "../../composerDraftStore"; |
| 11 | import { useStableCallback } from "../../hooks/useStableCallback"; |
| 12 | import { randomUUID } from "~/lib/utils"; |
| 13 | import { selectThreadRightPanelState, useRightPanelStore } from "../../rightPanelStore"; |
| 14 | import { useProject, useQuietThreadShell } from "../../state/entities"; |
| 15 | import { readEnvironmentScope } from "../../state/session"; |
| 16 | import { terminalEnvironment } from "../../state/terminal"; |
| 17 | import { useKnownTerminalSessions } from "../../state/terminalSessions"; |
| 18 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 19 | import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../../terminalUiStateStore"; |
| 20 | import { closingTerminalIds, holdTerminalIdWhileClosing } from "./closingTerminals"; |
| 21 | |
| 22 | /** Where a new terminal starts. Omitted fields fall back to the thread's project and worktree. */ |
| 23 | export interface TerminalLaunchLocation { |
| 24 | readonly cwd: string; |
| 25 | readonly worktreePath: string | null; |
| 26 | } |
| 27 | |
| 28 | /** Allocate terminal ids and launch locations centrally so all surfaces share one view of sessions. */ |
| 29 | export function useThreadTerminalActions(threadRef: ScopedThreadRef | null) { |
| 30 | const openTerminalCommand = useAtomCommand(terminalEnvironment.open, "terminal open"); |
| 31 | const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write"); |
| 32 | const closeTerminalCommand = useAtomCommand(terminalEnvironment.close, "terminal close"); |
| 33 | const serverThread = useQuietThreadShell(threadRef); |
| 34 | const draftThread = useComposerDraftStore((store) => |
| 35 | threadRef ? store.getDraftThreadByRef(threadRef) : null, |
| 36 | ); |
| 37 | const projectRef = serverThread |
| 38 | ? scopeProjectRef(serverThread.environmentId, serverThread.projectId) |
| 39 | : draftThread |
| 40 | ? scopeProjectRef(draftThread.environmentId, draftThread.projectId) |
| 41 | : null; |
| 42 | const project = useProject(projectRef); |
| 43 | const threadWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; |
| 44 | const knownSessions = useKnownTerminalSessions({ |
| 45 | environmentId: threadRef?.environmentId ?? null, |
| 46 | threadId: threadRef?.threadId ?? null, |
| 47 | }); |
| 48 | const drawerTerminalIds = useTerminalUiStateStore( |
| 49 | (state) => selectThreadTerminalUiState(state.terminalUiStateByThreadKey, threadRef).terminalIds, |
| 50 | ); |
| 51 | const panelSurfaces = useRightPanelStore( |
| 52 | (state) => selectThreadRightPanelState(state.byThreadKey, threadRef).surfaces, |
| 53 | ); |
| 54 | |
| 55 | const canWrite = () => |
| 56 | threadRef !== null && readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope); |
| 57 | |
| 58 | // Server lists lag and colliding ids share a PTY; without read access, suffix ids to avoid unseen sessions. |
| 59 | const allocateTerminalId = () => { |
| 60 | const ids = new Set([ |
| 61 | ...(knownSessions ?? []).map((session) => session.target.terminalId), |
| 62 | ...drawerTerminalIds, |
| 63 | ...panelSurfaces.flatMap((surface) => |
| 64 | surface.kind === "terminal" ? surface.terminalIds : [], |
| 65 | ), |
| 66 | ...(threadRef ? closingTerminalIds(threadRef) : []), |
| 67 | ]); |
| 68 | const canReuse = |
| 69 | knownSessions !== null && |
| 70 | threadRef !== null && |
| 71 | readEnvironmentScope(threadRef.environmentId, AuthTerminalReadScope); |
| 72 | return nextTerminalId([...ids], canReuse ? undefined : randomUUID()); |
| 73 | }; |
| 74 | |
| 75 | const defaultLaunchLocation = (): TerminalLaunchLocation | null => |
| 76 | project |
| 77 | ? { |
| 78 | cwd: projectScriptCwd({ |
| 79 | project: { cwd: project.workspaceRoot }, |
| 80 | worktreePath: threadWorktreePath, |
| 81 | }), |
| 82 | worktreePath: threadWorktreePath, |
| 83 | } |
| 84 | : null; |
| 85 | |
| 86 | /** place mounts the destination before the server open resolves. */ |
| 87 | const launchTerminal = (input: { |
| 88 | readonly place: (terminalId: string) => void; |
| 89 | readonly terminalId?: string; |
| 90 | readonly location?: TerminalLaunchLocation | null; |
| 91 | readonly extraEnv?: Record<string, string>; |
| 92 | readonly stopOnSettle?: boolean; |
| 93 | readonly size?: { readonly cols: number; readonly rows: number }; |
| 94 | }) => { |
| 95 | if (!threadRef || !canWrite() || !project) return null; |
| 96 | const location = input.location ?? defaultLaunchLocation(); |
| 97 | if (!location) return null; |
| 98 | const terminalId = input.terminalId ?? allocateTerminalId(); |
| 99 | input.place(terminalId); |
| 100 | const result = openTerminalCommand({ |
| 101 | environmentId: threadRef.environmentId, |
| 102 | input: { |
| 103 | threadId: threadRef.threadId, |
| 104 | terminalId, |
| 105 | cwd: location.cwd, |
| 106 | ...(location.worktreePath !== null ? { worktreePath: location.worktreePath } : {}), |
| 107 | env: projectScriptRuntimeEnv({ |
| 108 | project: { cwd: project.workspaceRoot }, |
| 109 | worktreePath: location.worktreePath, |
| 110 | ...(input.extraEnv ? { extraEnv: input.extraEnv } : {}), |
| 111 | }), |
| 112 | ...input.size, |
| 113 | ...(input.stopOnSettle !== undefined ? { stopOnSettle: input.stopOnSettle } : {}), |
| 114 | }, |
| 115 | }); |
| 116 | return { terminalId, result }; |
| 117 | }; |
| 118 | |
| 119 | /** Ends a session and deletes its history. A failed close falls back to typing `exit`. */ |
| 120 | const closeTerminalSession = (terminalId: string, target = threadRef) => { |
| 121 | if (!target || !readEnvironmentScope(target.environmentId, AuthTerminalOperateScope)) return; |
| 122 | const environmentId = target.environmentId; |
| 123 | const threadId = target.threadId; |
| 124 | void holdTerminalIdWhileClosing(target, terminalId, async () => { |
| 125 | const closeResult = await closeTerminalCommand({ |
| 126 | environmentId, |
| 127 | input: { threadId, terminalId, deleteHistory: true }, |
| 128 | }); |
| 129 | if ( |
| 130 | closeResult._tag === "Failure" && |
| 131 | !isAtomCommandInterrupted(closeResult) && |
| 132 | readEnvironmentScope(environmentId, AuthTerminalOperateScope) |
| 133 | ) { |
| 134 | await writeTerminal({ environmentId, input: { threadId, terminalId, data: "exit\n" } }); |
| 135 | } |
| 136 | }); |
| 137 | }; |
| 138 | |
| 139 | const writeToTerminal = (terminalId: string, data: string) => { |
| 140 | if (!threadRef || !canWrite()) return null; |
| 141 | return writeTerminal({ |
| 142 | environmentId: threadRef.environmentId, |
| 143 | input: { threadId: threadRef.threadId, terminalId, data }, |
| 144 | }); |
| 145 | }; |
| 146 | |
| 147 | return { |
| 148 | canWrite: useStableCallback(canWrite), |
| 149 | allocateTerminalId: useStableCallback(allocateTerminalId), |
| 150 | launchTerminal: useStableCallback(launchTerminal), |
| 151 | closeTerminalSession: useStableCallback(closeTerminalSession), |
| 152 | writeToTerminal: useStableCallback(writeToTerminal), |
| 153 | }; |
| 154 | } |