Terminal.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. import { Plus, X } from "lucide-react";
  2. import { useCallback, useEffect, useRef, useState } from "react";
  3. import type { IServiceAccessor } from "@zcode/services";
  4. import { TID_TERMINAL, TID_TERMINAL_CLOSE_BUTTON } from "@zcode/shared";
  5. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  6. import { useIsOfficeMode } from "@/hooks/useInterfaceMode.js";
  7. import { logger } from "@/logger.js";
  8. import { Button } from "@/components/ui/button.js";
  9. import { Tabs, TabsContent, TabsList } from "@/components/ui/tabs.js";
  10. import { getPathLeaf } from "@/lib/path.js";
  11. import { TerminalTabTrigger } from "@/terminal/TerminalTabTrigger.js";
  12. import { TerminalSession } from "@/terminal/TerminalSession.js";
  13. import {
  14. closeTerminalSession,
  15. createTerminalSession,
  16. createWorkspaceTerminalState,
  17. ensureWorkspaceTerminalState,
  18. exitTerminalSession,
  19. formatTerminalTabTitle,
  20. getNextTerminalSessionIndex,
  21. getTerminalSessionCloseAction,
  22. type TerminalPanelState,
  23. type TerminalSessionDescriptor,
  24. } from "@/terminal/terminalPanelState.js";
  25. export function Terminal({
  26. services,
  27. cwd,
  28. workspaceIdentity,
  29. openWorkspaceKeys,
  30. isVisible,
  31. isPanelResizing = false,
  32. isWindowsDesktop = false,
  33. onClose,
  34. onOpenBrowserUrl,
  35. }: {
  36. services: IServiceAccessor;
  37. cwd?: string;
  38. workspaceIdentity?: string;
  39. openWorkspaceKeys?: string[];
  40. isVisible: boolean;
  41. isPanelResizing?: boolean;
  42. isWindowsDesktop?: boolean;
  43. onClose: () => void;
  44. onOpenBrowserUrl: (url: string) => void;
  45. }) {
  46. const { intl } = useZCodeIntl();
  47. const isOfficeMode = useIsOfficeMode();
  48. const workspaceKey = workspaceIdentity?.trim() || cwd || "__default__";
  49. const [panelState, setPanelState] = useState<TerminalPanelState>(() => {
  50. const { session, workspace } = createWorkspaceTerminalState({
  51. workspaceKey,
  52. services,
  53. cwd,
  54. });
  55. return {
  56. sessions: {
  57. [session.id]: session,
  58. },
  59. workspaces: {
  60. [workspaceKey]: workspace,
  61. },
  62. };
  63. });
  64. const closePanelAfterExitWorkspaceRef = useRef<string | null>(null);
  65. useEffect(() => {
  66. if (!isVisible) {
  67. return;
  68. }
  69. // 业务逻辑:终端会话按 workspace identity 隔离保存,切换 workspace 时只切换可见 tab,
  70. // 不卸载旧 workspace 的 xterm/PTY,避免长时间运行的命令因为 React 生命周期变化被杀掉。
  71. // PTY exit 会删除最后一个 session;面板下次重新打开时也通过这里懒创建新终端。
  72. setPanelState((current) =>
  73. ensureWorkspaceTerminalState(current, {
  74. workspaceKey,
  75. services,
  76. cwd,
  77. }),
  78. );
  79. }, [cwd, isVisible, services, workspaceKey]);
  80. useEffect(() => {
  81. const exitedWorkspaceKey = closePanelAfterExitWorkspaceRef.current;
  82. if (!exitedWorkspaceKey) {
  83. return;
  84. }
  85. closePanelAfterExitWorkspaceRef.current = null;
  86. if (exitedWorkspaceKey === workspaceKey) {
  87. onClose();
  88. }
  89. }, [onClose, panelState, workspaceKey]);
  90. useEffect(() => {
  91. if (!openWorkspaceKeys) {
  92. return;
  93. }
  94. // 终端现在会跨 workspace 切换保活,但 workspace tab 被真正关闭后,
  95. // 对应的隐藏终端不能继续占着 PTY 进程;这里按仍打开的 workspace key 做回收。
  96. const retainedWorkspaceKeys = new Set(openWorkspaceKeys);
  97. retainedWorkspaceKeys.add(workspaceKey);
  98. setPanelState((current) => {
  99. const removedWorkspaceKeys = Object.keys(current.workspaces).filter(
  100. (key) => !retainedWorkspaceKeys.has(key),
  101. );
  102. if (removedWorkspaceKeys.length === 0) {
  103. return current;
  104. }
  105. const nextWorkspaces = { ...current.workspaces };
  106. const nextSessions = { ...current.sessions };
  107. for (const removedWorkspaceKey of removedWorkspaceKeys) {
  108. const workspace = nextWorkspaces[removedWorkspaceKey];
  109. delete nextWorkspaces[removedWorkspaceKey];
  110. for (const sessionId of workspace?.sessionIds ?? []) {
  111. delete nextSessions[sessionId];
  112. }
  113. }
  114. return {
  115. sessions: nextSessions,
  116. workspaces: nextWorkspaces,
  117. };
  118. });
  119. }, [openWorkspaceKeys, workspaceKey]);
  120. const handleShellLabelChange = useCallback((sessionId: string, shellLabel: string | null) => {
  121. setPanelState((current) => {
  122. const session = current.sessions[sessionId];
  123. if (!session || session.shellLabel === shellLabel) {
  124. return current;
  125. }
  126. return {
  127. ...current,
  128. sessions: {
  129. ...current.sessions,
  130. [sessionId]: {
  131. ...session,
  132. shellLabel,
  133. },
  134. },
  135. };
  136. });
  137. }, []);
  138. const handleCreateSession = useCallback(() => {
  139. setPanelState((current) => {
  140. const ensured = ensureWorkspaceTerminalState(current, {
  141. workspaceKey,
  142. services,
  143. cwd,
  144. });
  145. const workspace = ensured.workspaces[workspaceKey];
  146. if (!workspace) {
  147. return ensured;
  148. }
  149. const session = createTerminalSession({
  150. workspaceKey,
  151. services,
  152. cwd,
  153. index: getNextTerminalSessionIndex(ensured, workspaceKey),
  154. });
  155. logger.info("[Terminal] create terminal tab", {
  156. cwd,
  157. terminalTabId: session.id,
  158. workspaceKey,
  159. });
  160. return {
  161. sessions: {
  162. ...ensured.sessions,
  163. [session.id]: session,
  164. },
  165. workspaces: {
  166. ...ensured.workspaces,
  167. [workspaceKey]: {
  168. sessionIds: [...workspace.sessionIds, session.id],
  169. activeSessionId: session.id,
  170. },
  171. },
  172. };
  173. });
  174. }, [cwd, services, workspaceKey]);
  175. const handleCloseSession = useCallback(
  176. (sessionId: string) => {
  177. const closeAction = getTerminalSessionCloseAction(panelState, sessionId);
  178. if (closeAction === "close-panel") {
  179. // 旧 UI 在只剩一个 tab 时直接隐藏关闭按钮,用户无法从 tab 完成关闭。
  180. // 最后一个 tab 的关闭语义是收起整个面板并保活 session,与右上角关闭面板按钮保持一致。
  181. logger.info("[Terminal] close terminal panel from last tab", {
  182. terminalTabId: sessionId,
  183. workspaceKey,
  184. });
  185. onClose();
  186. return;
  187. }
  188. if (closeAction !== "close-session") {
  189. return;
  190. }
  191. setPanelState((current) => {
  192. const session = current.sessions[sessionId];
  193. const next = closeTerminalSession(current, sessionId);
  194. if (!session || next === current) {
  195. return current;
  196. }
  197. logger.info("[Terminal] close terminal tab", {
  198. terminalTabId: sessionId,
  199. workspaceKey: session.workspaceKey,
  200. });
  201. return next;
  202. });
  203. },
  204. [onClose, panelState, workspaceKey],
  205. );
  206. const handleSessionExit = useCallback(
  207. (sessionId: string, exitCode: number) => {
  208. setPanelState((current) => {
  209. const exitedWorkspaceKey = current.sessions[sessionId]?.workspaceKey;
  210. const result = exitTerminalSession(current, sessionId, workspaceKey);
  211. if (result.action === "none") {
  212. return current;
  213. }
  214. // 不能只在 xterm 中写“进程已退出”、让 descriptor 留在 tab registry。
  215. // PTY exit 是 session 生命周期终点,必须同步删除 tab;只有当前 workspace 的最后一个 tab 才关闭面板。
  216. logger.info("[Terminal] auto close exited terminal tab", {
  217. action: result.action,
  218. exitCode,
  219. terminalTabId: sessionId,
  220. workspaceKey: exitedWorkspaceKey,
  221. });
  222. if (result.action === "close-panel") {
  223. closePanelAfterExitWorkspaceRef.current = exitedWorkspaceKey ?? null;
  224. }
  225. return result.state;
  226. });
  227. },
  228. [workspaceKey],
  229. );
  230. const handleActivateSession = useCallback((sessionId: string) => {
  231. setPanelState((current) => {
  232. const session = current.sessions[sessionId];
  233. if (!session) {
  234. return current;
  235. }
  236. const workspace = current.workspaces[session.workspaceKey];
  237. if (!workspace || workspace.activeSessionId === sessionId) {
  238. return current;
  239. }
  240. return {
  241. ...current,
  242. workspaces: {
  243. ...current.workspaces,
  244. [session.workspaceKey]: {
  245. ...workspace,
  246. activeSessionId: sessionId,
  247. },
  248. },
  249. };
  250. });
  251. }, []);
  252. const workspace = panelState.workspaces[workspaceKey];
  253. const currentSessions =
  254. workspace?.sessionIds
  255. .map((sessionId) => panelState.sessions[sessionId])
  256. .filter((session): session is TerminalSessionDescriptor => Boolean(session)) ?? [];
  257. const activeSession =
  258. currentSessions.find((session) => session.id === workspace?.activeSessionId) ??
  259. currentSessions[0] ??
  260. null;
  261. const allSessions = Object.values(panelState.sessions);
  262. // 修复说明:关闭面板只收起 UI,不 dispose tab。真正关闭某个终端由 tab 上的关闭按钮负责,
  263. // 这样 workspace/task 切换或面板收起都不会中断正在运行的命令。
  264. return (
  265. <section
  266. data-testid={TID_TERMINAL}
  267. className="flex h-full min-h-0 flex-col gap-2 overflow-hidden bg-background p-3 pb-2"
  268. >
  269. <Tabs
  270. value={activeSession?.id ?? ""}
  271. onValueChange={handleActivateSession}
  272. className="h-full min-h-0 gap-2"
  273. >
  274. <div className="flex shrink-0 items-center gap-2">
  275. <div className="flex min-w-0 shrink-0 items-center gap-2">
  276. <div className="truncate text-ui-base font-medium text-foreground">
  277. {intl.formatMessage({ id: "terminal.title" })}
  278. </div>
  279. {activeSession?.shellLabel ? (
  280. <div className="shrink-0 text-ui-base text-foreground-subtle">
  281. {activeSession.shellLabel}
  282. </div>
  283. ) : null}
  284. </div>
  285. <div className="min-w-0 flex-1 overflow-x-auto !scrollbar-hide">
  286. <TabsList className="flex !h-7 w-max justify-start gap-1 rounded-none bg-transparent p-0">
  287. {currentSessions.map((session) => {
  288. const projectName =
  289. getPathLeaf(session.cwd ?? "") || intl.formatMessage({ id: "terminal.title" });
  290. const title = formatTerminalTabTitle(projectName, session.index);
  291. return (
  292. <TerminalTabTrigger
  293. key={session.id}
  294. session={session}
  295. title={title}
  296. closeLabel={intl.formatMessage({ id: "terminal.closeTab" }, { title })}
  297. isActive={session.id === activeSession?.id}
  298. onClose={handleCloseSession}
  299. />
  300. );
  301. })}
  302. </TabsList>
  303. </div>
  304. <div className="flex shrink-0 items-center gap-1">
  305. {!isOfficeMode && (
  306. <Button
  307. type="button"
  308. size="icon-md"
  309. variant="ghost"
  310. onClick={handleCreateSession}
  311. title={intl.formatMessage({ id: "terminal.new" })}
  312. aria-label={intl.formatMessage({ id: "terminal.new" })}
  313. >
  314. <Plus className="h-4 w-4" />
  315. </Button>
  316. )}
  317. <Button
  318. type="button"
  319. size="icon-md"
  320. variant="ghost"
  321. onClick={onClose}
  322. data-testid={TID_TERMINAL_CLOSE_BUTTON}
  323. title={intl.formatMessage({ id: "terminal.close" })}
  324. aria-label={intl.formatMessage({ id: "terminal.close" })}
  325. >
  326. <X className="h-4 w-4" />
  327. </Button>
  328. </div>
  329. </div>
  330. <div className="min-h-0 flex-1 overflow-hidden">
  331. {allSessions.map((session) => (
  332. <TabsContent
  333. key={session.id}
  334. value={session.id}
  335. forceMount
  336. className="h-full min-h-0 flex-1 data-[state=inactive]:hidden"
  337. >
  338. <TerminalSession
  339. sessionId={session.id}
  340. services={session.services}
  341. cwd={session.cwd}
  342. isVisible={
  343. isVisible &&
  344. session.workspaceKey === workspaceKey &&
  345. session.id === activeSession?.id
  346. }
  347. isPanelResizing={isPanelResizing}
  348. isWindowsDesktop={isWindowsDesktop}
  349. onShellLabelChange={handleShellLabelChange}
  350. onExit={handleSessionExit}
  351. onOpenBrowserUrl={onOpenBrowserUrl}
  352. />
  353. </TabsContent>
  354. ))}
  355. </div>
  356. </Tabs>
  357. </section>
  358. );
  359. }