From f6daf93cb2f6260426f07376191955b8782d7856 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 27 Jul 2025 20:16:20 -0700 Subject: [PATCH 1/5] resume in TUI mode --- src/commands/chat.ts | 2 +- src/session.ts | 60 ++++++++++++++++---------------- src/ui/hooks/useChat.ts | 76 +++++++++-------------------------------- 3 files changed, 49 insertions(+), 89 deletions(-) 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.ts b/src/session.ts index e7d885e18..2b0e24aef 100644 --- a/src/session.ts +++ b/src/session.ts @@ -1,7 +1,7 @@ -import { ChatCompletionMessageParam } from "openai/resources.mjs"; 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"; /** @@ -13,19 +13,20 @@ 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(); - + 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, '-'); - + const cleanSessionId = terminalSession.replace(/[^a-zA-Z0-9-_]/g, "-"); + return `continue-cli-${cleanSessionId}`; } @@ -35,24 +36,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 +74,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); } } @@ -87,16 +88,17 @@ export function saveSession(chatHistory: ChatCompletionMessageParam[]): void { */ export function loadSession(): ChatCompletionMessageParam[] | null { try { - const sessionFilePath = getSessionFilePath(); - + const sessionFilePath = + "/Users/nate/.continue-cli/sessions/continue-cli-94507.json"; // 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 +113,7 @@ export function clearSession(): void { fs.unlinkSync(sessionFilePath); } } catch (error) { - logger.error('Error clearing session:', error); + logger.error("Error clearing session:", error); } } @@ -121,4 +123,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..91ad92d2f 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -10,7 +10,6 @@ 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"; @@ -18,6 +17,7 @@ import logger from "../../util/logger.js"; import { DisplayMessage } from "../types.js"; import { posthogService } from "../../telemetry/posthogService.js"; +import { initializeChatHistory } from "../../commands/chat.js"; interface UseChatProps { assistant?: AssistantUnrolled; @@ -60,35 +60,8 @@ export function useChat({ return []; } - let history: ChatCompletionMessageParam[] = []; - - if (resume) { - const savedHistory = loadSession(); - if (savedHistory) { - history = 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; + // Initialize with empty array - will be populated asynchronously + return []; } ); @@ -230,31 +203,20 @@ export function useChat({ }, [isRemoteMode, remoteUrl, responseStartTime]); useEffect(() => { - // Skip system message initialization in remote mode + // Skip initialization in remote mode if (isRemoteMode) 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 using the shared function + const initializeHistory = async () => { + const history = await initializeChatHistory({ + resume, + rule: additionalRules, + }); + setChatHistory(history); }; - initializeSystemMessage(); - }, [isRemoteMode]); + initializeHistory(); + }, [isRemoteMode, resume, additionalRules]); useEffect(() => { if (initialPrompt) { @@ -661,14 +623,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([]); }; From 2b5b39242d2a4995bae94175afe0b2564377fdb0 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 27 Jul 2025 20:52:22 -0700 Subject: [PATCH 2/5] fix: resume --- src/session.test.ts | 271 ++++++++++++++++++++++++++++++++++++++++++++ src/session.ts | 129 +++++++++++++++++++-- 2 files changed, 390 insertions(+), 10 deletions(-) create mode 100644 src/session.test.ts diff --git a/src/session.test.ts b/src/session.test.ts new file mode 100644 index 000000000..8c23aaafa --- /dev/null +++ b/src/session.test.ts @@ -0,0 +1,271 @@ +import os from "os"; +import { execSync } from "child_process"; + +// Mock external dependencies +jest.mock("child_process"); +jest.mock("os"); + +const mockedExecSync = execSync as jest.MockedFunction; +const mockedOs = os as jest.Mocked; + +// We need to import the module functions to test them +// Since they're not exported, we'll test through the public API +import { saveSession, loadSession, hasSession, clearSession } from "./session.js"; + +describe("Session ID Generation", () => { + let originalEnv: NodeJS.ProcessEnv; + let originalProcess: any; + + beforeEach(() => { + // Store original values + originalEnv = { ...process.env }; + originalProcess = { + ppid: process.ppid, + pid: process.pid, + stdin: process.stdin, + }; + + // Clear 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; + delete process.env.CONTINUE_CLI_TEST_SESSION_ID; + + // Reset mocks + jest.clearAllMocks(); + }); + + afterEach(() => { + // Restore original values + process.env = originalEnv; + Object.assign(process, originalProcess); + }); + + describe("Environment Variable Fallbacks", () => { + it("should use TMUX_PANE when available", () => { + process.env.TMUX_PANE = "%1"; + + // Create a session to trigger session ID generation + saveSession([]); + + // Verify session was created (indicates session ID worked) + 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([]); + 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([]); + expect(hasSession()).toBe(true); + clearSession(); + }); + }); + + describe("TTY Path Fallback", () => { + beforeEach(() => { + // Mock platform detection + mockedOs.platform.mockReturnValue("darwin"); + + // Mock stdin.isTTY + Object.defineProperty(process.stdin, 'isTTY', { + value: true, + writable: true + }); + }); + + it("should use TTY path when environment variables are not available", () => { + mockedExecSync.mockReturnValue("/dev/ttys002\n"); + + saveSession([]); + expect(hasSession()).toBe(true); + clearSession(); + + expect(mockedExecSync).toHaveBeenCalledWith("tty", { + encoding: "utf8", + timeout: 1000, + stdio: ["ignore", "pipe", "ignore"] + }); + }); + + it("should skip TTY detection on Windows", () => { + mockedOs.platform.mockReturnValue("win32"); + + saveSession([]); + expect(hasSession()).toBe(true); + clearSession(); + + // Should not call execSync for tty command on Windows + expect(mockedExecSync).not.toHaveBeenCalledWith( + expect.stringContaining("tty"), + expect.any(Object) + ); + }); + + it("should handle TTY command errors gracefully", () => { + mockedExecSync.mockImplementation((command) => { + if (command === "tty") { + throw new Error("tty: not found"); + } + return ""; + }); + + // Should not throw and should fall back to process ID + expect(() => { + saveSession([]); + }).not.toThrow(); + + expect(hasSession()).toBe(true); + clearSession(); + }); + + it("should handle 'not a tty' response", () => { + mockedExecSync.mockReturnValue("not a tty\n"); + + saveSession([]); + expect(hasSession()).toBe(true); + clearSession(); + }); + }); + + describe("Process Tree Fallback", () => { + beforeEach(() => { + mockedOs.platform.mockReturnValue("darwin"); + Object.defineProperty(process.stdin, 'isTTY', { + value: false, + writable: true + }); + }); + + it("should find terminal process in process tree", () => { + // Mock process tree with terminal process + mockedExecSync.mockImplementation((command) => { + if (command.includes("ps -o pid,ppid,comm")) { + return " PID PPID COMMAND\n 1234 5678 iTerm2\n"; + } + return ""; + }); + + // Mock process.ppid + Object.defineProperty(process, 'ppid', { + value: 1234, + writable: true + }); + + saveSession([]); + expect(hasSession()).toBe(true); + clearSession(); + }); + + it("should skip process tree analysis on Windows", () => { + mockedOs.platform.mockReturnValue("win32"); + + saveSession([]); + expect(hasSession()).toBe(true); + clearSession(); + + // Should not call ps command on Windows + expect(mockedExecSync).not.toHaveBeenCalledWith( + expect.stringContaining("ps -o"), + expect.any(Object) + ); + }); + + it("should handle ps command errors gracefully", () => { + mockedExecSync.mockImplementation((command) => { + if (command.includes("ps -o")) { + throw new Error("ps: command not found"); + } + return ""; + }); + + expect(() => { + saveSession([]); + }).not.toThrow(); + + expect(hasSession()).toBe(true); + clearSession(); + }); + + it("should handle malformed ps output", () => { + mockedExecSync.mockImplementation((command) => { + if (command.includes("ps -o")) { + return "malformed output\n"; + } + return ""; + }); + + expect(() => { + saveSession([]); + }).not.toThrow(); + + expect(hasSession()).toBe(true); + clearSession(); + }); + }); + + describe("Final Fallback", () => { + beforeEach(() => { + mockedOs.platform.mockReturnValue("linux"); + Object.defineProperty(process.stdin, 'isTTY', { + value: false, + writable: true + }); + + // Mock all external commands to fail + mockedExecSync.mockImplementation(() => { + throw new Error("Command failed"); + }); + }); + + it("should fall back to process PID when all other methods fail", () => { + const originalPid = process.pid; + Object.defineProperty(process, 'pid', { + value: 9999, + writable: true + }); + + saveSession([]); + expect(hasSession()).toBe(true); + clearSession(); + + // Restore original PID + Object.defineProperty(process, 'pid', { + value: originalPid, + writable: true + }); + }); + }); + + describe("Session ID Cleaning", () => { + it("should clean up special characters in session IDs", () => { + process.env.TMUX_PANE = "%1:0.0/special#chars"; + + saveSession([]); + expect(hasSession()).toBe(true); + clearSession(); + + // The session should be created successfully despite special characters + }); + }); + + describe("Test Mode", () => { + it("should use test session ID when provided", () => { + process.env.CONTINUE_CLI_TEST_SESSION_ID = "test-123"; + + saveSession([]); + expect(hasSession()).toBe(true); + clearSession(); + }); + }); +}); \ No newline at end of file diff --git a/src/session.ts b/src/session.ts index 2b0e24aef..b78f1d904 100644 --- a/src/session.ts +++ b/src/session.ts @@ -1,9 +1,105 @@ +import { execSync } from "child_process"; import fs from "fs"; 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 @@ -14,20 +110,34 @@ function getSessionId(): string { 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 = + // 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 || - process.pid.toString(); + process.env.STY; - // Clean up the session ID to be filesystem-safe - const cleanSessionId = terminalSession.replace(/[^a-zA-Z0-9-_]/g, "-"); + if (envSession) { + const cleanSessionId = envSession.replace(/[^a-zA-Z0-9-_]/g, "-"); + return `continue-cli-${cleanSessionId}`; + } - 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}`; } /** @@ -88,8 +198,7 @@ export function saveSession(chatHistory: ChatCompletionMessageParam[]): void { */ export function loadSession(): ChatCompletionMessageParam[] | null { try { - const sessionFilePath = - "/Users/nate/.continue-cli/sessions/continue-cli-94507.json"; // getSessionFilePath(); + const sessionFilePath = getSessionFilePath(); if (!fs.existsSync(sessionFilePath)) { return null; From 0c383e4b22f905e8cdbdf3741e724c043e0deb94 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 27 Jul 2025 21:13:36 -0700 Subject: [PATCH 3/5] fix tests for windows --- src/session.test.ts | 289 +++++++++++--------------------------------- 1 file changed, 71 insertions(+), 218 deletions(-) diff --git a/src/session.test.ts b/src/session.test.ts index 8c23aaafa..7a3730db0 100644 --- a/src/session.test.ts +++ b/src/session.test.ts @@ -1,56 +1,40 @@ -import os from "os"; -import { execSync } from "child_process"; +import { saveSession, hasSession, clearSession } from "./session.js"; -// Mock external dependencies -jest.mock("child_process"); -jest.mock("os"); - -const mockedExecSync = execSync as jest.MockedFunction; -const mockedOs = os as jest.Mocked; - -// We need to import the module functions to test them -// Since they're not exported, we'll test through the public API -import { saveSession, loadSession, hasSession, clearSession } from "./session.js"; - -describe("Session ID Generation", () => { +describe("Session Management", () => { let originalEnv: NodeJS.ProcessEnv; - let originalProcess: any; beforeEach(() => { - // Store original values originalEnv = { ...process.env }; - originalProcess = { - ppid: process.ppid, - pid: process.pid, - stdin: process.stdin, - }; - - // Clear environment variables + + // 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; - delete process.env.CONTINUE_CLI_TEST_SESSION_ID; - - // Reset mocks - jest.clearAllMocks(); }); afterEach(() => { - // Restore original values process.env = originalEnv; - Object.assign(process, originalProcess); + // Clean up any test sessions + try { + clearSession(); + } catch (error) { + // Ignore cleanup errors + } }); - describe("Environment Variable Fallbacks", () => { - it("should use TMUX_PANE when available", () => { + describe("Environment Variable Session IDs", () => { + it("should create unique sessions for different TMUX_PANE values", () => { + // Test first session process.env.TMUX_PANE = "%1"; - - // Create a session to trigger session ID generation - saveSession([]); - - // Verify session was created (indicates session ID worked) + 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(); }); @@ -58,7 +42,7 @@ describe("Session ID Generation", () => { it("should use TERM_SESSION_ID when TMUX_PANE is not available", () => { process.env.TERM_SESSION_ID = "w1t0s0:0.0"; - saveSession([]); + saveSession([{ role: "user", content: "test" }]); expect(hasSession()).toBe(true); clearSession(); }); @@ -66,206 +50,75 @@ describe("Session ID Generation", () => { it("should use SSH_TTY when other env vars are not available", () => { process.env.SSH_TTY = "/dev/pts/0"; - saveSession([]); + saveSession([{ role: "user", content: "test" }]); expect(hasSession()).toBe(true); clearSession(); }); - }); - describe("TTY Path Fallback", () => { - beforeEach(() => { - // Mock platform detection - mockedOs.platform.mockReturnValue("darwin"); + it("should clean special characters from session IDs", () => { + process.env.TMUX_PANE = "%1:0.0/special#chars@test!"; - // Mock stdin.isTTY - Object.defineProperty(process.stdin, 'isTTY', { - value: true, - writable: true - }); - }); - - it("should use TTY path when environment variables are not available", () => { - mockedExecSync.mockReturnValue("/dev/ttys002\n"); - - saveSession([]); - expect(hasSession()).toBe(true); - clearSession(); - - expect(mockedExecSync).toHaveBeenCalledWith("tty", { - encoding: "utf8", - timeout: 1000, - stdio: ["ignore", "pipe", "ignore"] - }); - }); - - it("should skip TTY detection on Windows", () => { - mockedOs.platform.mockReturnValue("win32"); - - saveSession([]); - expect(hasSession()).toBe(true); - clearSession(); - - // Should not call execSync for tty command on Windows - expect(mockedExecSync).not.toHaveBeenCalledWith( - expect.stringContaining("tty"), - expect.any(Object) - ); - }); - - it("should handle TTY command errors gracefully", () => { - mockedExecSync.mockImplementation((command) => { - if (command === "tty") { - throw new Error("tty: not found"); - } - return ""; - }); - - // Should not throw and should fall back to process ID + // Should not throw error despite special characters expect(() => { - saveSession([]); + saveSession([{ role: "user", content: "test" }]); }).not.toThrow(); expect(hasSession()).toBe(true); clearSession(); }); - - it("should handle 'not a tty' response", () => { - mockedExecSync.mockReturnValue("not a tty\n"); - - saveSession([]); - expect(hasSession()).toBe(true); - clearSession(); - }); - }); - - describe("Process Tree Fallback", () => { - beforeEach(() => { - mockedOs.platform.mockReturnValue("darwin"); - Object.defineProperty(process.stdin, 'isTTY', { - value: false, - writable: true - }); - }); - - it("should find terminal process in process tree", () => { - // Mock process tree with terminal process - mockedExecSync.mockImplementation((command) => { - if (command.includes("ps -o pid,ppid,comm")) { - return " PID PPID COMMAND\n 1234 5678 iTerm2\n"; - } - return ""; - }); - - // Mock process.ppid - Object.defineProperty(process, 'ppid', { - value: 1234, - writable: true - }); - - saveSession([]); - expect(hasSession()).toBe(true); - clearSession(); - }); - - it("should skip process tree analysis on Windows", () => { - mockedOs.platform.mockReturnValue("win32"); - - saveSession([]); - expect(hasSession()).toBe(true); - clearSession(); - - // Should not call ps command on Windows - expect(mockedExecSync).not.toHaveBeenCalledWith( - expect.stringContaining("ps -o"), - expect.any(Object) - ); - }); - - it("should handle ps command errors gracefully", () => { - mockedExecSync.mockImplementation((command) => { - if (command.includes("ps -o")) { - throw new Error("ps: command not found"); - } - return ""; - }); - - expect(() => { - saveSession([]); - }).not.toThrow(); - - expect(hasSession()).toBe(true); - clearSession(); - }); - - it("should handle malformed ps output", () => { - mockedExecSync.mockImplementation((command) => { - if (command.includes("ps -o")) { - return "malformed output\n"; - } - return ""; - }); - - expect(() => { - saveSession([]); - }).not.toThrow(); - - expect(hasSession()).toBe(true); - clearSession(); - }); - }); - - describe("Final Fallback", () => { - beforeEach(() => { - mockedOs.platform.mockReturnValue("linux"); - Object.defineProperty(process.stdin, 'isTTY', { - value: false, - writable: true - }); - - // Mock all external commands to fail - mockedExecSync.mockImplementation(() => { - throw new Error("Command failed"); - }); - }); - - it("should fall back to process PID when all other methods fail", () => { - const originalPid = process.pid; - Object.defineProperty(process, 'pid', { - value: 9999, - writable: true - }); - - saveSession([]); - expect(hasSession()).toBe(true); - clearSession(); - - // Restore original PID - Object.defineProperty(process, 'pid', { - value: originalPid, - writable: true - }); - }); - }); - - describe("Session ID Cleaning", () => { - it("should clean up special characters in session IDs", () => { - process.env.TMUX_PANE = "%1:0.0/special#chars"; - - saveSession([]); - expect(hasSession()).toBe(true); - clearSession(); - - // The session should be created successfully despite special characters - }); }); describe("Test Mode", () => { it("should use test session ID when provided", () => { process.env.CONTINUE_CLI_TEST_SESSION_ID = "test-123"; - saveSession([]); + 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 From c9a4083ccf174fe8baf8a08b357d78793704b7c7 Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Sun, 27 Jul 2025 21:19:59 -0700 Subject: [PATCH 4/5] Update src/ui/hooks/useChat.ts Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> --- src/ui/hooks/useChat.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index 91ad92d2f..a6f552365 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -61,7 +61,7 @@ export function useChat({ } // Initialize with empty array - will be populated asynchronously - return []; + return resume ? loadSession() ?? [] : []; } ); From 82d7020744d56f069dde6859d8a26cbb1b9b8ea2 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 27 Jul 2025 21:29:56 -0700 Subject: [PATCH 5/5] fix: race condition --- src/ui/hooks/useChat.ts | 55 +++++++++++++++++++++++++++++++---------- 1 file changed, 42 insertions(+), 13 deletions(-) diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index 91ad92d2f..7025226a4 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -60,8 +60,21 @@ export function useChat({ return []; } - // Initialize with empty array - will be populated asynchronously - return []; + // 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) { + initialHistory = savedHistory; + } + } + + // 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 initialHistory; } ); @@ -87,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 }> >([]); @@ -203,26 +224,34 @@ export function useChat({ }, [isRemoteMode, remoteUrl, responseStartTime]); useEffect(() => { - // Skip initialization in remote mode - if (isRemoteMode) return; + // Skip initialization in remote mode or if already initialized + if (isRemoteMode || isChatHistoryInitialized) return; - // Initialize chat history using the shared function + // Initialize chat history with system message only if we don't have a session const initializeHistory = async () => { - const history = await initializeChatHistory({ - resume, - rule: additionalRules, - }); - setChatHistory(history); + // 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); }; initializeHistory(); - }, [isRemoteMode, resume, additionalRules]); + // 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