diff --git a/src/commands/chat.ts b/src/commands/chat.ts index 30d6075c3..3f147d8c6 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -25,7 +25,7 @@ export interface ChatOptions extends BaseCommandOptions { resume?: boolean; } -async function initializeChatHistory( +export async function initializeChatHistory( options: ChatOptions ): Promise { let chatHistory: ChatCompletionMessageParam[] = []; diff --git a/src/session.test.ts b/src/session.test.ts new file mode 100644 index 000000000..7a3730db0 --- /dev/null +++ b/src/session.test.ts @@ -0,0 +1,124 @@ +import { saveSession, hasSession, clearSession } from "./session.js"; + +describe("Session Management", () => { + let originalEnv: NodeJS.ProcessEnv; + + beforeEach(() => { + originalEnv = { ...process.env }; + + // Clear session-related environment variables + delete process.env.TMUX_PANE; + delete process.env.TERM_SESSION_ID; + delete process.env.SSH_TTY; + delete process.env.TMUX; + delete process.env.STY; + }); + + afterEach(() => { + process.env = originalEnv; + // Clean up any test sessions + try { + clearSession(); + } catch (error) { + // Ignore cleanup errors + } + }); + + describe("Environment Variable Session IDs", () => { + it("should create unique sessions for different TMUX_PANE values", () => { + // Test first session + process.env.TMUX_PANE = "%1"; + saveSession([{ role: "user", content: "test1" }]); + expect(hasSession()).toBe(true); + clearSession(); + + // Test second session with different TMUX_PANE + process.env.TMUX_PANE = "%2"; + saveSession([{ role: "user", content: "test2" }]); + expect(hasSession()).toBe(true); + clearSession(); + }); + + it("should use TERM_SESSION_ID when TMUX_PANE is not available", () => { + process.env.TERM_SESSION_ID = "w1t0s0:0.0"; + + saveSession([{ role: "user", content: "test" }]); + expect(hasSession()).toBe(true); + clearSession(); + }); + + it("should use SSH_TTY when other env vars are not available", () => { + process.env.SSH_TTY = "/dev/pts/0"; + + saveSession([{ role: "user", content: "test" }]); + expect(hasSession()).toBe(true); + clearSession(); + }); + + it("should clean special characters from session IDs", () => { + process.env.TMUX_PANE = "%1:0.0/special#chars@test!"; + + // Should not throw error despite special characters + expect(() => { + saveSession([{ role: "user", content: "test" }]); + }).not.toThrow(); + + expect(hasSession()).toBe(true); + clearSession(); + }); + }); + + describe("Test Mode", () => { + it("should use test session ID when provided", () => { + process.env.CONTINUE_CLI_TEST_SESSION_ID = "test-123"; + + saveSession([{ role: "user", content: "test" }]); + expect(hasSession()).toBe(true); + clearSession(); + }); + }); + + describe("Fallback Mechanisms", () => { + it("should create a session even when no environment variables are available", () => { + // No environment variables set + + // Should fall back to TTY path, process tree, or PID + expect(() => { + saveSession([{ role: "user", content: "fallback test" }]); + }).not.toThrow(); + + expect(hasSession()).toBe(true); + clearSession(); + }); + + it("should handle session persistence correctly", () => { + process.env.TMUX_PANE = "%test"; + + const testHistory = [ + { role: "user" as const, content: "Hello" }, + { role: "assistant" as const, content: "Hi there!" } + ]; + + // Save session + saveSession(testHistory); + expect(hasSession()).toBe(true); + + // Clear and verify it's gone + clearSession(); + expect(hasSession()).toBe(false); + }); + }); + + describe("Error Handling", () => { + it("should handle filesystem errors gracefully", () => { + // Try to save to invalid session ID that might cause filesystem issues + process.env.CONTINUE_CLI_TEST_SESSION_ID = "test-with-various-chars"; + + expect(() => { + saveSession([{ role: "user", content: "test" }]); + }).not.toThrow(); + + clearSession(); + }); + }); +}); \ No newline at end of file diff --git a/src/session.ts b/src/session.ts index e7d885e18..b78f1d904 100644 --- a/src/session.ts +++ b/src/session.ts @@ -1,9 +1,105 @@ -import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import { execSync } from "child_process"; import fs from "fs"; -import path from "path"; +import { ChatCompletionMessageParam } from "openai/resources.mjs"; import os from "os"; +import path from "path"; import logger from "./util/logger.js"; +/** + * Get the terminal process ID by walking up the process tree + */ +function getTerminalProcessId(): string | null { + try { + // Skip on Windows - ps command doesn't exist + if (os.platform() === "win32") { + return null; + } + + // Get parent process info by walking up the tree + let currentPid = process.ppid; + + for (let i = 0; i < 10 && currentPid; i++) { + try { + const psOutput = execSync(`ps -o pid,ppid,comm -p ${currentPid}`, { + encoding: "utf8", + timeout: 1000, + stdio: ["ignore", "pipe", "ignore"], // Suppress stderr + }).trim(); + + const lines = psOutput.split("\n"); + if (lines.length < 2) break; + + const processInfo = lines[1].trim().split(/\s+/); + const [pid, ppid, comm] = processInfo; + + // Check if this looks like a terminal process + if ( + comm && + (comm.includes("Terminal") || + comm.includes("iTerm") || + comm.includes("tmux") || + comm.includes("screen") || + comm.includes("bash") || + comm.includes("zsh") || + comm.includes("fish") || + comm.includes("kitty") || + comm.includes("alacritty") || + comm.includes("wt") || // Windows Terminal + comm.includes("cmd") || // Windows Command Prompt + comm.includes("powershell")) + ) { + return pid; + } + + const nextPid = parseInt(ppid); + if (isNaN(nextPid) || nextPid <= 1) break; + currentPid = nextPid; + } catch (innerError) { + // Continue to next iteration if this process lookup fails + break; + } + } + } catch (error) { + // Silently fail - this is a fallback mechanism + } + + return null; +} + +/** + * Get the TTY device path for unique terminal identification + */ +function getTtyPath(): string | null { + try { + // Skip on Windows - tty command doesn't exist + if (os.platform() === "win32") { + return null; + } + + if (process.stdin.isTTY) { + // Get the TTY device path + const ttyPath = execSync("tty", { + encoding: "utf8", + timeout: 1000, + stdio: ["ignore", "pipe", "ignore"], // Suppress stderr + }).trim(); + + if ( + ttyPath && + ttyPath !== "not a tty" && + !ttyPath.includes("not found") + ) { + // Convert /dev/ttys002 to ttys002 for cleaner ID + return ttyPath.replace("/dev/", ""); + } + } + } catch (error) { + // Silently fail - this is a fallback mechanism + } + + return null; +} + /** * Get a unique session identifier for the current terminal session * Uses environment variables to ensure each terminal window has its own session @@ -13,20 +109,35 @@ function getSessionId(): string { if (process.env.CONTINUE_CLI_TEST_SESSION_ID) { return `continue-cli-${process.env.CONTINUE_CLI_TEST_SESSION_ID}`; } - - // Use a combination of terminal session ID and process ID to ensure uniqueness - // For tmux, use TMUX_PANE which is unique per pane - const terminalSession = process.env.TMUX_PANE || - process.env.TERM_SESSION_ID || - process.env.SSH_TTY || - process.env.TMUX || - process.env.STY || - process.pid.toString(); - - // Clean up the session ID to be filesystem-safe - const cleanSessionId = terminalSession.replace(/[^a-zA-Z0-9-_]/g, '-'); - - return `continue-cli-${cleanSessionId}`; + + // Try environment variables first (most reliable) + const envSession = + process.env.TMUX_PANE || + process.env.TERM_SESSION_ID || + process.env.SSH_TTY || + process.env.TMUX || + process.env.STY; + + if (envSession) { + const cleanSessionId = envSession.replace(/[^a-zA-Z0-9-_]/g, "-"); + return `continue-cli-${cleanSessionId}`; + } + + // Fallback 1: Try to get TTY device path (unique per terminal window) + const ttyPath = getTtyPath(); + if (ttyPath) { + const cleanTtyId = ttyPath.replace(/[^a-zA-Z0-9-_]/g, "-"); + return `continue-cli-tty-${cleanTtyId}`; + } + + // Fallback 2: Try to get terminal process ID (unique per terminal process) + const terminalPid = getTerminalProcessId(); + if (terminalPid) { + return `continue-cli-term-${terminalPid}`; + } + + // Final fallback: Use process PID (least reliable but always available) + return `continue-cli-pid-${process.pid}`; } /** @@ -35,24 +146,24 @@ function getSessionId(): string { function getSessionDir(): string { // For tests, use the test directory if we're in test mode if (process.env.CONTINUE_CLI_TEST && process.env.HOME) { - const sessionDir = path.join(process.env.HOME, '.continue-cli', 'sessions'); - + const sessionDir = path.join(process.env.HOME, ".continue-cli", "sessions"); + // Create directory if it doesn't exist if (!fs.existsSync(sessionDir)) { fs.mkdirSync(sessionDir, { recursive: true }); } - + return sessionDir; } - + const homeDir = os.homedir(); - const sessionDir = path.join(homeDir, '.continue-cli', 'sessions'); - + const sessionDir = path.join(homeDir, ".continue-cli", "sessions"); + // Create directory if it doesn't exist if (!fs.existsSync(sessionDir)) { fs.mkdirSync(sessionDir, { recursive: true }); } - + return sessionDir; } @@ -73,12 +184,12 @@ export function saveSession(chatHistory: ChatCompletionMessageParam[]): void { const sessionFilePath = getSessionFilePath(); const sessionData = { timestamp: new Date().toISOString(), - chatHistory + chatHistory, }; - + fs.writeFileSync(sessionFilePath, JSON.stringify(sessionData, null, 2)); } catch (error) { - logger.error('Error saving session:', error); + logger.error("Error saving session:", error); } } @@ -88,15 +199,15 @@ export function saveSession(chatHistory: ChatCompletionMessageParam[]): void { export function loadSession(): ChatCompletionMessageParam[] | null { try { const sessionFilePath = getSessionFilePath(); - + if (!fs.existsSync(sessionFilePath)) { return null; } - - const sessionData = JSON.parse(fs.readFileSync(sessionFilePath, 'utf8')); + + const sessionData = JSON.parse(fs.readFileSync(sessionFilePath, "utf8")); return sessionData.chatHistory || null; } catch (error) { - logger.error('Error loading session:', error); + logger.error("Error loading session:", error); return null; } } @@ -111,7 +222,7 @@ export function clearSession(): void { fs.unlinkSync(sessionFilePath); } } catch (error) { - logger.error('Error clearing session:', error); + logger.error("Error clearing session:", error); } } @@ -121,4 +232,4 @@ export function clearSession(): void { export function hasSession(): boolean { const sessionFilePath = getSessionFilePath(); return fs.existsSync(sessionFilePath); -} \ No newline at end of file +} diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index f78d9ed56..921e4dad2 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -10,14 +10,14 @@ import { StreamCallbacks, streamChatResponse, } from "../../streamChatResponse.js"; -import { constructSystemMessage } from "../../systemMessage.js"; import telemetryService from "../../telemetry/telemetryService.js"; import { formatToolCall } from "../../tools/formatters.js"; import { formatError } from "../../util/formatError.js"; import logger from "../../util/logger.js"; -import { DisplayMessage } from "../types.js"; +import { initializeChatHistory } from "../../commands/chat.js"; import { posthogService } from "../../telemetry/posthogService.js"; +import { DisplayMessage } from "../types.js"; interface UseChatProps { assistant?: AssistantUnrolled; @@ -60,35 +60,21 @@ export function useChat({ return []; } - let history: ChatCompletionMessageParam[] = []; + // Synchronously initialize chat history to prevent race conditions + // This ensures system message is always loaded before handleUserMessage runs + let initialHistory: ChatCompletionMessageParam[] = []; + // Load previous session if resume flag is used if (resume) { const savedHistory = loadSession(); if (savedHistory) { - history = savedHistory; + initialHistory = savedHistory; } } - if (history.length === 0) { - const rulesSystemMessage = ""; - const systemMessage = constructSystemMessage( - rulesSystemMessage, - additionalRules - ); - if (systemMessage instanceof Promise) { - // Handle the promise case - we'll need to initialize this asynchronously - systemMessage.then((resolvedMessage) => { - if (resolvedMessage) { - history.push({ role: "system", content: resolvedMessage }); - setChatHistory([...history]); - } - }); - } else if (systemMessage) { - history.push({ role: "system", content: systemMessage }); - } - } - - return history; + // If no session loaded or not resuming, we'll need to add system message + // We can't make this async, so we'll handle it in the useEffect + return resume ? loadSession() ?? [] : []; } ); @@ -114,6 +100,14 @@ export function useChat({ const [inputMode, setInputMode] = useState(true); const [abortController, setAbortController] = useState(null); + const [isChatHistoryInitialized, setIsChatHistoryInitialized] = useState( + // If we're resuming and found a saved session, we're already initialized + // If we're in remote mode, we're initialized (will be populated by polling) + isRemoteMode || (resume && loadSession() !== null) + ); + + // Capture initial rules to prevent re-initialization when rules change + const [initialRules] = useState(additionalRules); const [attachedFiles, setAttachedFiles] = useState< Array<{ path: string; content: string }> >([]); @@ -230,37 +224,40 @@ export function useChat({ }, [isRemoteMode, remoteUrl, responseStartTime]); useEffect(() => { - // Skip system message initialization in remote mode - if (isRemoteMode) return; + // Skip initialization in remote mode or if already initialized + if (isRemoteMode || isChatHistoryInitialized) return; - // Initialize system message asynchronously - const initializeSystemMessage = async () => { - if ( - chatHistory.length === 0 || - !chatHistory.some((msg) => msg.role === "system") - ) { - const rulesSystemMessage = ""; - const systemMessage = await constructSystemMessage( - rulesSystemMessage, - additionalRules - ); - if (systemMessage) { - const newHistory = [ - { role: "system" as const, content: systemMessage }, - ]; - setChatHistory(newHistory); - } + // Initialize chat history with system message only if we don't have a session + const initializeHistory = async () => { + // Only add system message if we don't have any messages yet + if (chatHistory.length === 0) { + const history = await initializeChatHistory({ + resume, + rule: initialRules, + }); + setChatHistory(history); } + setIsChatHistoryInitialized(true); }; - initializeSystemMessage(); - }, [isRemoteMode]); + initializeHistory(); + // Note: Using initialRules instead of additionalRules to prevent re-initialization + // when rules change during the conversation + }, [ + isRemoteMode, + isChatHistoryInitialized, + chatHistory.length, + resume, + initialRules, + ]); useEffect(() => { - if (initialPrompt) { + // Only handle initial prompt after chat history is initialized + // This prevents race conditions where the prompt runs before system message is loaded + if (initialPrompt && isChatHistoryInitialized) { handleUserMessage(initialPrompt); } - }, [initialPrompt]); + }, [initialPrompt, isChatHistoryInitialized]); const handleUserMessage = async (message: string) => { // Special handling for /org command in TUI @@ -661,14 +658,10 @@ export function useChat({ }; const resetChatHistory = async () => { - const rulesSystemMessage = ""; - const systemMessage = await constructSystemMessage( - rulesSystemMessage, - additionalRules - ); - const newHistory = systemMessage - ? [{ role: "system" as const, content: systemMessage }] - : []; + const newHistory = await initializeChatHistory({ + resume: false, // Don't resume when resetting + rule: additionalRules, + }); setChatHistory(newHistory); setMessages([]); };