π OpenHands: AI-Driven Development
Restore terminal interactivity while keeping UI changes (#7903)
Robert Brennanb452fe273cf1
diff --git a/frontend/__tests__/hooks/use-terminal.test.tsx b/frontend/__tests__/hooks/use-terminal.test.tsxindex 74b73cb9ce..10f93a86ef 100644--- a/frontend/__tests__/hooks/use-terminal.test.tsx+++ b/frontend/__tests__/hooks/use-terminal.test.tsx@@ -1,9 +1,19 @@import { beforeAll, describe, expect, it, vi } from "vitest";-import { render } from "@testing-library/react";import { afterEach } from "node:test";-import { ReactNode } from "react";import { useTerminal } from "#/hooks/use-terminal";import { Command } from "#/state/command-slice";+import { AgentState } from "#/types/agent-state";+import { renderWithProviders } from "../../test-utils";++// Mock the WsClient context+vi.mock("#/context/ws-client-provider", () => ({+ useWsClient: () => ({+ send: vi.fn(),+ status: "CONNECTED",+ isLoadingMessages: false,+ events: [],+ }),+}));interface TestTerminalComponentProps {commands: Command[];@@ -16,14 +26,6 @@ function TestTerminalComponent({return <div ref={ref} />;}-interface WrapperProps {- children: ReactNode;-}--function Wrapper({ children }: WrapperProps) {- return <div>{children}</div>;-}-describe("useTerminal", () => {const mockTerminal = vi.hoisted(() => ({loadAddon: vi.fn(),@@ -55,8 +57,11 @@ describe("useTerminal", () => {});it("should render", () => {- render(<TestTerminalComponent commands={[]} />, {- wrapper: Wrapper,+ renderWithProviders(<TestTerminalComponent commands={[]} />, {+ preloadedState: {+ agent: { curAgentState: AgentState.RUNNING },+ cmd: { commands: [] },+ },});});@@ -66,8 +71,11 @@ describe("useTerminal", () => {{ content: "hello", type: "output" },];- render(<TestTerminalComponent commands={commands} />, {- wrapper: Wrapper,+ renderWithProviders(<TestTerminalComponent commands={commands} />, {+ preloadedState: {+ agent: { curAgentState: AgentState.RUNNING },+ cmd: { commands },+ },});expect(mockTerminal.writeln).toHaveBeenNthCalledWith(1, "echo hello");@@ -86,12 +94,15 @@ describe("useTerminal", () => {{ content: secret, type: "output" },];- render(+ renderWithProviders(<TestTerminalComponentcommands={commands}/>,{- wrapper: Wrapper,+ preloadedState: {+ agent: { curAgentState: AgentState.RUNNING },+ cmd: { commands },+ },},);diff --git a/frontend/src/components/features/terminal/terminal.tsx b/frontend/src/components/features/terminal/terminal.tsxindex a4c52382e6..bb9e8d8900 100644--- a/frontend/src/components/features/terminal/terminal.tsx+++ b/frontend/src/components/features/terminal/terminal.tsx@@ -1,10 +1,15 @@import { useSelector } from "react-redux";+import { useTranslation } from "react-i18next";import { RootState } from "#/store";import { useTerminal } from "#/hooks/use-terminal";import "@xterm/xterm/css/xterm.css";+import { RUNTIME_INACTIVE_STATES } from "#/types/agent-state";function Terminal() {const { commands } = useSelector((state: RootState) => state.cmd);+ const { curAgentState } = useSelector((state: RootState) => state.agent);+ const isRuntimeInactive = RUNTIME_INACTIVE_STATES.includes(curAgentState);+ const { t } = useTranslation();const ref = useTerminal({commands,@@ -12,6 +17,11 @@ function Terminal() {return (<div className="h-full p-2 min-h-0 flex-grow">+ {isRuntimeInactive && (+ <div className="text-sm text-gray-400 mb-2">+ {t("DIFF_VIEWER$WAITING_FOR_RUNTIME")}+ </div>+ )}<div ref={ref} className="h-full w-full" /></div>);diff --git a/frontend/src/hooks/use-terminal.ts b/frontend/src/hooks/use-terminal.tsindex 2af297e77c..04ffd6f159 100644--- a/frontend/src/hooks/use-terminal.ts+++ b/frontend/src/hooks/use-terminal.ts@@ -1,7 +1,12 @@import { FitAddon } from "@xterm/addon-fit";import { Terminal } from "@xterm/xterm";import React from "react";+import { useSelector } from "react-redux";import { Command } from "#/state/command-slice";+import { RootState } from "#/store";+import { RUNTIME_INACTIVE_STATES } from "#/types/agent-state";+import { useWsClient } from "#/context/ws-client-provider";+import { getTerminalCommand } from "#/services/terminal-service";import { parseTerminalOutput } from "#/utils/parse-terminal-output";/*@@ -18,20 +23,11 @@ const DEFAULT_TERMINAL_CONFIG: UseTerminalConfig = {};const renderCommand = (command: Command, terminal: Terminal) => {- const { content, type } = command;-- if (type === "input") {- terminal.write("$ ");- terminal.writeln(- parseTerminalOutput(content.replaceAll("\n", "\r\n").trim()),- );- } else {- terminal.write(`\n`);- terminal.writeln(- parseTerminalOutput(content.replaceAll("\n", "\r\n").trim()),- );- terminal.write(`\n`);- }+ const { content } = command;++ terminal.writeln(+ parseTerminalOutput(content.replaceAll("\n", "\r\n").trim()),+ );};// Create a persistent reference that survives component unmounts@@ -41,10 +37,14 @@ const persistentLastCommandIndex = { current: 0 };export const useTerminal = ({commands,}: UseTerminalConfig = DEFAULT_TERMINAL_CONFIG) => {+ const { send } = useWsClient();+ const { curAgentState } = useSelector((state: RootState) => state.agent);const terminal = React.useRef<Terminal | null>(null);const fitAddon = React.useRef<FitAddon | null>(null);const ref = React.useRef<HTMLDivElement>(null);const lastCommandIndex = persistentLastCommandIndex; // Use the persistent reference+ const keyEventDisposable = React.useRef<{ dispose: () => void } | null>(null);+ const disabled = RUNTIME_INACTIVE_STATES.includes(curAgentState);const createTerminal = () =>new Terminal({@@ -62,6 +62,53 @@ export const useTerminal = ({}};+ const copySelection = (selection: string) => {+ const clipboardItem = new ClipboardItem({+ "text/plain": new Blob([selection], { type: "text/plain" }),+ });++ navigator.clipboard.write([clipboardItem]);+ };++ const pasteSelection = (callback: (text: string) => void) => {+ navigator.clipboard.readText().then(callback);+ };++ const pasteHandler = (event: KeyboardEvent, cb: (text: string) => void) => {+ const isControlOrMetaPressed =+ event.type === "keydown" && (event.ctrlKey || event.metaKey);++ if (isControlOrMetaPressed) {+ if (event.code === "KeyV") {+ pasteSelection((text: string) => {+ terminal.current?.write(text);+ cb(text);+ });+ }++ if (event.code === "KeyC") {+ const selection = terminal.current?.getSelection();+ if (selection) copySelection(selection);+ }+ }++ return true;+ };++ const handleEnter = (command: string) => {+ terminal.current?.write("\r\n");+ // Don't write the command again as it will be added to the commands array+ // and rendered by the useEffect that watches commands+ send(getTerminalCommand(command));+ // Don't add the prompt here as it will be added when the command is processed+ // and the commands array is updated+ };++ const handleBackspace = (command: string) => {+ terminal.current?.write("\b \b");+ return command.slice(0, -1);+ };+// Initialize terminal and handle cleanupReact.useEffect(() => {terminal.current = createTerminal();@@ -73,30 +120,38 @@ export const useTerminal = ({// This happens when we just switch to Terminal from other tabsif (commands.length > 0) {for (let i = 0; i < commands.length; i += 1) {+ if (commands[i].type === "input") {+ terminal.current.write("$ ");+ }renderCommand(commands[i], terminal.current);}lastCommandIndex.current = commands.length;}+ terminal.current.write("$ ");}return () => {terminal.current?.dispose();};- }, [commands]);+ }, []);React.useEffect(() => {- // Render new commands when they are added to the commands arrayif (terminal.current &&commands.length > 0 &&lastCommandIndex.current < commands.length) {+ let lastCommandType = "";for (let i = lastCommandIndex.current; i < commands.length; i += 1) {+ lastCommandType = commands[i].type;renderCommand(commands[i], terminal.current);}lastCommandIndex.current = commands.length;+ if (lastCommandType === "output") {+ terminal.current.write("$ ");+ }}- }, [commands]);+ }, [commands, disabled]);React.useEffect(() => {let resizeObserver: ResizeObserver | null = null;@@ -114,5 +169,60 @@ export const useTerminal = ({};}, []);+ React.useEffect(() => {+ if (terminal.current) {+ // Dispose of existing listeners if they exist+ if (keyEventDisposable.current) {+ keyEventDisposable.current.dispose();+ keyEventDisposable.current = null;+ }++ let commandBuffer = "";++ if (!disabled) {+ // Add new key event listener and store the disposable+ keyEventDisposable.current = terminal.current.onKey(+ ({ key, domEvent }) => {+ if (domEvent.key === "Enter") {+ handleEnter(commandBuffer);+ commandBuffer = "";+ } else if (domEvent.key === "Backspace") {+ if (commandBuffer.length > 0) {+ commandBuffer = handleBackspace(commandBuffer);+ }+ } else {+ // Ignore paste event+ if (key.charCodeAt(0) === 22) {+ return;+ }+ commandBuffer += key;+ terminal.current?.write(key);+ }+ },+ );++ // Add custom key handler and store the disposable+ terminal.current.attachCustomKeyEventHandler((event) =>+ pasteHandler(event, (text) => {+ commandBuffer += text;+ }),+ );+ } else {+ // Add a noop handler when disabled+ keyEventDisposable.current = terminal.current.onKey((e) => {+ e.domEvent.preventDefault();+ e.domEvent.stopPropagation();+ });+ }+ }++ return () => {+ if (keyEventDisposable.current) {+ keyEventDisposable.current.dispose();+ keyEventDisposable.current = null;+ }+ };+ }, [disabled]);+return ref;};