From 72e91d5c10c63ec74388d2f73852bfce7b3db43c Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 20 Jul 2025 19:43:57 -0700 Subject: [PATCH] feat: remote TUI --- src/commands/remote-test.ts | 29 +++++ src/commands/remote.ts | 23 +++- src/index.ts | 10 ++ src/ui/TUIChat.tsx | 33 ++++-- src/ui/UserInput.tsx | 14 ++- src/ui/hooks/useChat.ts | 229 ++++++++++++++++++++++++++++-------- src/ui/index.ts | 21 ++++ test-remote-tui.sh | 27 +++++ 8 files changed, 317 insertions(+), 69 deletions(-) create mode 100644 src/commands/remote-test.ts create mode 100755 test-remote-tui.sh diff --git a/src/commands/remote-test.ts b/src/commands/remote-test.ts new file mode 100644 index 000000000..8068a91ac --- /dev/null +++ b/src/commands/remote-test.ts @@ -0,0 +1,29 @@ +import chalk from "chalk"; +import telemetryService from "../telemetry/telemetryService.js"; +import { startRemoteTUIChat } from "../ui/index.js"; +import logger from "../util/logger.js"; + +export async function remoteTest( + prompt: string, + url: string = "http://localhost:8000" +) { + console.info(chalk.white(`Connecting to remote environment at ${url}...`)); + + try { + // Record session start + telemetryService.recordSessionStart(); + telemetryService.startActiveTime(); + + try { + // Start the TUI in remote mode + await startRemoteTUIChat(url, prompt); + } finally { + telemetryService.stopActiveTime(); + } + } catch (error: any) { + logger.error( + chalk.red(`Failed to connect to remote environment: ${error.message}`) + ); + process.exit(1); + } +} diff --git a/src/commands/remote.ts b/src/commands/remote.ts index 488021075..58adacfd3 100644 --- a/src/commands/remote.ts +++ b/src/commands/remote.ts @@ -5,6 +5,9 @@ import { loadAuthConfig, } from "../auth/workos.js"; import { env } from "../env.js"; +import { startRemoteTUIChat } from "../ui/index.js"; +import telemetryService from "../telemetry/telemetryService.js"; +import logger from "../util/logger.js"; export async function remote(prompt: string) { console.info(chalk.white("Setting up remote development environment...")); @@ -48,13 +51,27 @@ export async function remote(prompt: string) { chalk.green("✅ Remote development environment created successfully!") ); - if (result.url) { + if (result.url && result.port) { + const remoteUrl = `${result.url}:${result.port}`; console.info( - chalk.white(`Access your environment at: ${result.url}:${result.port}`) + chalk.white(`Connecting to remote environment at: ${remoteUrl}`) ); + + // Record session start + telemetryService.recordSessionStart(); + telemetryService.startActiveTime(); + + try { + // Start the TUI in remote mode + await startRemoteTUIChat(remoteUrl, prompt); + } finally { + telemetryService.stopActiveTime(); + } + } else { + throw new Error("No URL or port returned from remote environment creation"); } } catch (error: any) { - console.error( + logger.error( chalk.red(`Failed to create remote environment: ${error.message}`) ); process.exit(1); diff --git a/src/index.ts b/src/index.ts index 3d45f2e08..a8ebac5e5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,6 +4,7 @@ import { Command } from "commander"; import { chat } from "./commands/chat.js"; import { login } from "./commands/login.js"; import { logout } from "./commands/logout.js"; +import { remoteTest } from "./commands/remote-test.js"; import { remote } from "./commands/remote.js"; import { serve } from "./commands/serve.js"; import { configureConsoleForHeadless } from "./util/consoleOverride.js"; @@ -129,6 +130,15 @@ program await serve(prompt, options); }); +// Remote test subcommand (for development) +program + .command("remote-test [prompt]") + .description("Test remote TUI mode with a local server") + .option("--url ", "Server URL (default: http://localhost:8000)") + .action(async (prompt: string = "Hello from remote!", options) => { + await remoteTest(prompt, options.url); + }); + // Handle unknown commands program.on("command:*", () => { console.error(`Error: Unknown command '${program.args.join(" ")}'\n`); diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 82d852a29..64ad9be6c 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -26,10 +26,14 @@ import UserInput from "./UserInput.js"; const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); interface TUIChatProps { - config: AssistantUnrolled; - model: ModelConfig; - llmApi: BaseLlmApi; - mcpService: MCPService; + // Remote mode props + remoteUrl?: string; + + // Local mode props + config?: AssistantUnrolled; + model?: ModelConfig; + llmApi?: BaseLlmApi; + mcpService?: MCPService; apiClient?: DefaultApiInterface; configPath?: string; initialPrompt?: string; @@ -38,6 +42,7 @@ interface TUIChatProps { } const TUIChat: React.FC = ({ + remoteUrl, config: initialAssistant, model: initialModel, llmApi: initialLlmApi, @@ -48,6 +53,9 @@ const TUIChat: React.FC = ({ resume, additionalRules, }) => { + // Check if we're in remote mode + const isRemoteMode = !!remoteUrl; + // Track current assistant configuration state const [assistant, setAssistant] = useState(initialAssistant); const [model, setModel] = useState(initialModel); @@ -220,6 +228,9 @@ const TUIChat: React.FC = ({ onShowConfigSelector: () => showConfigSelectorUI(), onLoginPrompt: handleLoginPrompt, onReload: handleReload, + // Remote mode configuration + isRemoteMode, + remoteUrl, }); const { renderMessage } = useMessageRenderer(); @@ -364,6 +375,7 @@ const TUIChat: React.FC = ({ assistant={assistant} onFileAttached={handleFileAttached} disabled={isInputDisabled} + isRemoteMode={isRemoteMode} /> )} @@ -374,11 +386,14 @@ const TUIChat: React.FC = ({ alignItems="center" > - + {!isRemoteMode && model && ( + + )} + {isRemoteMode && Remote Mode} diff --git a/src/ui/UserInput.tsx b/src/ui/UserInput.tsx index 7204ce830..836297241 100644 --- a/src/ui/UserInput.tsx +++ b/src/ui/UserInput.tsx @@ -12,11 +12,12 @@ interface UserInputProps { isWaitingForResponse: boolean; inputMode: boolean; onInterrupt?: () => void; - assistant: AssistantConfig; + assistant?: AssistantConfig; onFileAttached?: (filePath: string, content: string) => void; disabled?: boolean; placeholder?: string; hideNormalUI?: boolean; + isRemoteMode?: boolean; } const UserInput: React.FC = ({ @@ -29,6 +30,7 @@ const UserInput: React.FC = ({ disabled = false, placeholder, hideNormalUI = false, + isRemoteMode = false, }) => { const [textBuffer] = useState(() => new TextBuffer()); const [inputHistory] = useState(() => new InputHistory()); @@ -78,7 +80,7 @@ const UserInput: React.FC = ({ ]; const assistantCommands = - assistant.prompts?.map((prompt) => ({ + assistant?.prompts?.map((prompt) => ({ name: prompt?.name || "", description: prompt?.description || "", })) || []; @@ -492,15 +494,15 @@ const UserInput: React.FC = ({ return ( {/* Input box */} - - - ●{" "} + + + {isRemoteMode ? "◉" : "●"}{" "} {renderInputText()} {/* Slash command UI */} - {showSlashCommands && inputMode && !hideNormalUI && ( + {showSlashCommands && inputMode && !hideNormalUI && assistant && ( void; onLoginPrompt?: (promptText: string) => Promise; onReload?: () => Promise; + // Remote mode props + isRemoteMode?: boolean; + remoteUrl?: string; } export function useChat({ @@ -42,11 +45,18 @@ export function useChat({ onShowConfigSelector, onLoginPrompt, onReload, + isRemoteMode = false, + remoteUrl, }: UseChatProps) { const { exit } = useApp(); const [chatHistory, setChatHistory] = useState( () => { + // In remote mode, start with empty history (will be populated by polling) + if (isRemoteMode) { + return []; + } + let history: ChatCompletionMessageParam[] = []; if (resume) { @@ -105,7 +115,66 @@ export function useChat({ Array<{ path: string; content: string }> >([]); + // Remote mode polling useEffect(() => { + if (!isRemoteMode || !remoteUrl) return; + + let pollInterval: NodeJS.Timeout; + let isPolling = false; + + const pollServerState = async () => { + if (isPolling) return; // Prevent overlapping polls + isPolling = true; + + try { + const response = await fetch(`${remoteUrl}/state`); + if (response.ok) { + const state = await response.json(); + + // Update chat history from server + if (state.chatHistory) { + setChatHistory(state.chatHistory); + + // Update display messages + const displayMessages = state.chatHistory + .filter((msg: ChatCompletionMessageParam) => msg.role !== "system") + .map((msg: ChatCompletionMessageParam) => ({ + role: msg.role, + content: msg.content as string, + })); + setMessages(displayMessages); + } + + // Update processing state + setIsWaitingForResponse(state.isProcessing); + if (state.isProcessing && !responseStartTime) { + setResponseStartTime(Date.now()); + } else if (!state.isProcessing && responseStartTime) { + setResponseStartTime(null); + } + } + } catch (error) { + logger.error("Failed to poll server state:", error); + } finally { + isPolling = false; + } + }; + + // Start polling immediately + pollServerState(); + + // Set up interval for continuous polling + pollInterval = setInterval(pollServerState, 500); // Poll every 500ms + + return () => { + clearInterval(pollInterval); + }; + }, [isRemoteMode, remoteUrl, responseStartTime]); + + useEffect(() => { + // Skip system message initialization in remote mode + if (isRemoteMode) return; + // Initialize system message asynchronously const initializeSystemMessage = async () => { if (chatHistory.length === 0 || !chatHistory.some(msg => msg.role === "system")) { @@ -122,7 +191,7 @@ export function useChat({ }; initializeSystemMessage(); - }, []); + }, [isRemoteMode]); useEffect(() => { if (initialPrompt) { @@ -143,33 +212,48 @@ export function useChat({ return; } - // Handle slash commands - const commandResult = await handleSlashCommands( - message, - assistant, - onLoginPrompt, - onReload - ); - if (commandResult) { - if (commandResult.exit) { - exit(); - return; - } + // Handle slash commands (skip in remote mode for now) + if (!isRemoteMode && assistant) { + const commandResult = await handleSlashCommands( + message, + assistant, + onLoginPrompt, + onReload + ); + if (commandResult) { + if (commandResult.exit) { + exit(); + return; + } - if (commandResult.openConfigSelector) { - onShowConfigSelector(); - return; - } + if (commandResult.openConfigSelector) { + onShowConfigSelector(); + return; + } - if (commandResult.clear) { - const systemMessage = chatHistory.find((msg) => msg.role === "system"); - const newHistory = systemMessage ? [systemMessage] : []; - setChatHistory(newHistory); - setMessages([]); + if (commandResult.clear) { + const systemMessage = chatHistory.find((msg) => msg.role === "system"); + const newHistory = systemMessage ? [systemMessage] : []; + setChatHistory(newHistory); + setMessages([]); + + if (commandResult.output) { + const output = commandResult.output; + setMessages([ + { + role: "system", + content: output, + messageType: "system" as const, + }, + ]); + } + return; + } if (commandResult.output) { const output = commandResult.output; - setMessages([ + setMessages((prev) => [ + ...prev, { role: "system", content: output, @@ -177,25 +261,12 @@ export function useChat({ }, ]); } - return; - } - if (commandResult.output) { - const output = commandResult.output; - setMessages((prev) => [ - ...prev, - { - role: "system", - content: output, - messageType: "system" as const, - }, - ]); - } - - if (commandResult.newInput) { - message = commandResult.newInput; - } else { - return; + if (commandResult.newInput) { + message = commandResult.newInput; + } else { + return; + } } } @@ -218,6 +289,44 @@ export function useChat({ setAttachedFiles([]); } + // In remote mode, send message to server instead of processing locally + if (isRemoteMode && remoteUrl) { + try { + const response = await fetch(`${remoteUrl}/message`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ message: messageContent }), + }); + + if (!response.ok) { + const error = await response.json(); + setMessages((prev) => [ + ...prev, + { + role: "system", + content: `Error: ${error.error || "Failed to send message"}`, + messageType: "system" as const, + }, + ]); + } + // State will be updated by polling + } catch (error) { + logger.error("Failed to send message to remote server:", error); + setMessages((prev) => [ + ...prev, + { + role: "system", + content: `Error: Failed to connect to remote server`, + messageType: "system" as const, + }, + ]); + } + return; + } + + // Local mode: process message normally const newUserMessage: ChatCompletionMessageParam = { role: "user", content: messageContent, @@ -339,13 +448,15 @@ export function useChat({ // Call streamChatResponse with the new history that includes the user message const finalHistory = [...newHistory]; - await streamChatResponse( - finalHistory, - model, - llmApi, - controller, - streamCallbacks - ); + if (model && llmApi) { + await streamChatResponse( + finalHistory, + model, + llmApi, + controller, + streamCallbacks + ); + } if (currentStreamingMessage && (currentStreamingMessage as any).content) { const messageContent = (currentStreamingMessage as any).content; @@ -391,6 +502,22 @@ export function useChat({ }; const handleInterrupt = () => { + // In remote mode, send interrupt signal to server + if (isRemoteMode && remoteUrl) { + // Send a message to interrupt the remote server + fetch(`${remoteUrl}/message`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ message: "" }), // Empty message triggers interrupt + }).catch((error) => { + logger.error("Failed to send interrupt to remote server:", error); + }); + return; + } + + // Local mode: abort the controller if (abortController && isWaitingForResponse) { abortController.abort(); setMessages((prev) => [ diff --git a/src/ui/index.ts b/src/ui/index.ts index 930a118fe..c3159e8a3 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -46,3 +46,24 @@ export async function startTUIChat( return { unmount }; } + +export async function startRemoteTUIChat( + remoteUrl: string, + initialPrompt?: string +) { + // Start the TUI in remote mode + const { unmount } = render( + React.createElement(TUIChat, { + remoteUrl, + initialPrompt, + }) + ); + + // Handle cleanup + process.on("SIGINT", () => { + unmount(); + process.exit(0); + }); + + return { unmount }; +} diff --git a/test-remote-tui.sh b/test-remote-tui.sh new file mode 100755 index 000000000..7467515ac --- /dev/null +++ b/test-remote-tui.sh @@ -0,0 +1,27 @@ +#!/bin/bash + +echo "Testing Remote TUI Mode" +echo "======================" +echo "" +echo "1. Starting local serve instance..." +npm run dev -- serve --port 8000 --timeout 60 & +SERVER_PID=$! + +# Wait for server to start +sleep 5 + +echo "" +echo "2. Server should now be running at http://localhost:8000" +echo "" +echo "3. In another terminal, you can now test the remote TUI with:" +echo " npm run dev -- remote-test 'Hello from remote mode!'" +echo "" +echo " This will connect to the local server and you'll see:" +echo " - The input border will be cyan instead of gray" +echo " - The prompt icon will be ◉ instead of ●" +echo " - 'Remote Mode' will be shown at the bottom" +echo "" +echo "Press Ctrl+C to stop the server..." + +# Wait for the server +wait $SERVER_PID \ No newline at end of file