From e9f053eaf0b66e54bbb5d373965cd11a4c2b1088 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 9 Aug 2025 11:20:54 -0400 Subject: [PATCH 1/4] fix: plan mode switching --- src/ui/UserInput.tsx | 9 +- src/ui/__tests__/TUIChat.planModeBug.test.tsx | 181 ++++++++++++++++++ 2 files changed, 187 insertions(+), 3 deletions(-) create mode 100644 src/ui/__tests__/TUIChat.planModeBug.test.tsx diff --git a/src/ui/UserInput.tsx b/src/ui/UserInput.tsx index 719d82cbb..021ed39a7 100644 --- a/src/ui/UserInput.tsx +++ b/src/ui/UserInput.tsx @@ -4,7 +4,7 @@ import React, { useState } from "react"; import { getAllSlashCommands } from "../commands/commands.js"; import type { PermissionMode } from "../permissions/types.js"; -import { reloadService, SERVICE_NAMES } from "../services/index.js"; +import { SERVICE_NAMES, serviceContainer } from "../services/index.js"; import { modeService } from "../services/ModeService.js"; import { InputHistory } from "../util/inputHistory.js"; import { logger } from "../util/logger.js"; @@ -78,8 +78,11 @@ const UserInput: React.FC = ({ modeService.switchMode(nextMode); - // Reload the tool permissions service to ensure the service container has the latest state - await reloadService(SERVICE_NAMES.TOOL_PERMISSIONS); + // Update the service container with the new tool permissions state + // Since TOOL_PERMISSIONS was registered with registerValue(), we need to + // update its value directly rather than reloading from a factory + const updatedState = modeService.getToolPermissionService().getState(); + serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); // Show a brief indicator of the mode change // This will be reflected in the ModeIndicator component diff --git a/src/ui/__tests__/TUIChat.planModeBug.test.tsx b/src/ui/__tests__/TUIChat.planModeBug.test.tsx new file mode 100644 index 000000000..101cb7891 --- /dev/null +++ b/src/ui/__tests__/TUIChat.planModeBug.test.tsx @@ -0,0 +1,181 @@ +import { render } from "ink-testing-library"; +import React from "react"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +import { SERVICE_NAMES, serviceContainer } from "../../services/index.js"; +import { modeService } from "../../services/ModeService.js"; +import { getAllTools } from "../../streamChatResponse.js"; +import { createUITestContext } from "../../test-helpers/ui-test-context.js"; +import { AppRoot } from "../AppRoot.js"; + +describe("TUIChat - Plan Mode Bug Reproduction", () => { + let context: any; + + beforeEach(async () => { + context = createUITestContext({ + allServicesReady: true, + serviceState: "ready", + serviceValue: { some: "data" }, + }); + + // Ensure mode service is properly initialized in normal mode + await modeService.initialize({}); + }); + + afterEach(() => { + context.cleanup(); + }); + + it("a) start up b) shift+tab to plan c) [plan] visible d) send message", async () => { + const { lastFrame, stdin, unmount } = render(React.createElement(AppRoot)); + + try { + // a) Start up + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("Ask anything"); + + // b) Shift+Tab to switch into plan mode + stdin.write("\x1b[Z"); + await new Promise(resolve => setTimeout(resolve, 200)); + + frame = lastFrame(); + + // c) Make sure the string "[plan]" is on the screen + expect(frame!).toContain("[plan]"); + + // d) Successfully send a message without error + const testMessage = "Can you help me analyze this code?"; + stdin.write(testMessage); + stdin.write("\r"); + + // Wait for message processing + await new Promise(resolve => setTimeout(resolve, 300)); + + frame = lastFrame(); + + // Verify no crash occurred and UI is still functional + expect(frame).toBeDefined(); + expect(frame!.length).toBeGreaterThan(0); + + // Should still be in plan mode after sending message + expect(frame!).toContain("[plan]"); + + // Should still show the input prompt + expect(frame!).toContain("Ask anything"); + } finally { + unmount(); + } + }); + + it("tests mode switching back and forth works correctly", async () => { + const { lastFrame, stdin, unmount } = render(React.createElement(AppRoot)); + + try { + // Start in normal mode + let frame = lastFrame(); + expect(frame!).not.toContain("[plan]"); + expect(frame!).not.toContain("[auto]"); + + // Switch to plan mode + stdin.write("\x1b[Z"); + await new Promise(resolve => setTimeout(resolve, 100)); + + frame = lastFrame(); + expect(frame!).toContain("[plan]"); + + // Switch to auto mode + stdin.write("\x1b[Z"); + await new Promise(resolve => setTimeout(resolve, 100)); + + frame = lastFrame(); + expect(frame!).toContain("[auto]"); + expect(frame!).not.toContain("[plan]"); + + // Switch back to normal mode + stdin.write("\x1b[Z"); + await new Promise(resolve => setTimeout(resolve, 100)); + + frame = lastFrame(); + expect(frame!).not.toContain("[plan]"); + expect(frame!).not.toContain("[auto]"); + + + } finally { + unmount(); + } + }); + +it("tests that you can switch modes after being in plan mode", async () => { + const { lastFrame, stdin, unmount } = render(React.createElement(AppRoot)); + + try { + // Switch to plan mode + stdin.write("\x1b[Z"); + await new Promise(resolve => setTimeout(resolve, 100)); + + let frame = lastFrame(); + expect(frame!).toContain("[plan]"); + + // Send a message while in plan mode + stdin.write("Test message"); + stdin.write("\r"); + await new Promise(resolve => setTimeout(resolve, 200)); + + frame = lastFrame(); + + // Try to switch to another mode - this is where the bug might occur + stdin.write("\x1b[Z]"); // Should go to auto mode + await new Promise(resolve => setTimeout(resolve, 200)); + + frame = lastFrame(); + + // This should work - if it fails, we've reproduced the "can't switch back" bug + expect(frame!).toContain("[auto]"); + expect(frame!).not.toContain("[plan]"); + + + } finally { + unmount(); + } + }); + + it("reproduces the 'ToolPermissionService not initialized' error when switching modes", async () => { + // This test specifically tests the service container interaction + // that causes the actual bug in production + + // First, set up a realistic service state (not mocked) + await modeService.initialize({ isHeadless: false }); + + // Register the tool permissions service like the real app does + const initialState = modeService.getToolPermissionService().getState(); + serviceContainer.registerValue(SERVICE_NAMES.TOOL_PERMISSIONS, initialState); + + // Verify initial state works + expect(() => getAllTools()).not.toThrow(); + + // Switch modes WITHOUT updating the service container (this simulates the bug) + modeService.switchMode("plan"); + + // The service container still has the old state, so getAllTools() should not find + // the updated state with plan mode permissions. However, since the ToolPermissionService + // overrides isReady() to always return true, getAllTools() will actually work. + // The real bug would manifest when the service container has an out-of-sync state. + + // To reproduce the ACTUAL bug, we need to simulate the case where the service + // container has a stale state that doesn't match the ToolPermissionService + const staleState = { ...initialState, currentMode: "normal" as const }; + serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, staleState); + + + // Now getAllTools() should work because it gets the service state from the container + // and the container has a valid state (even if it's stale) + const tools = getAllTools(); + expect(tools).toBeDefined(); + expect(Array.isArray(tools)).toBe(true); + + // But the tools returned will be for "normal" mode, not "plan" mode + // In plan mode, many tools should be excluded, but with stale normal state, all tools are available + const planModeState = modeService.getToolPermissionService().getState(); + }); +}); \ No newline at end of file From f447dc6fa1ee8382e896e022bd162bc8a6bad642 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 9 Aug 2025 11:29:45 -0400 Subject: [PATCH 2/4] Skip update checks for development versions --- src/ui/UpdateNotification.test.tsx | 122 +++++++++++++++++++++++++++++ src/ui/UpdateNotification.tsx | 5 ++ 2 files changed, 127 insertions(+) create mode 100644 src/ui/UpdateNotification.test.tsx diff --git a/src/ui/UpdateNotification.test.tsx b/src/ui/UpdateNotification.test.tsx new file mode 100644 index 000000000..8d1e36d04 --- /dev/null +++ b/src/ui/UpdateNotification.test.tsx @@ -0,0 +1,122 @@ +// Mock the version module before any other imports +vi.mock("../version.js", () => ({ + getVersion: vi.fn(), + getLatestVersion: vi.fn(), + compareVersions: vi.fn(), +})); + +// Mock useTerminalSize hook +vi.mock("./hooks/useTerminalSize.js", () => ({ + useTerminalSize: () => ({ columns: 80, rows: 24 }), +})); + +// Mock sentry to prevent initialization issues +vi.mock("../sentry.js", () => ({ + sentryService: { + captureException: vi.fn(), + captureMessage: vi.fn(), + setUser: vi.fn(), + setTag: vi.fn(), + setContext: vi.fn(), + addBreadcrumb: vi.fn(), + startSpan: vi.fn(), + flush: vi.fn(), + close: vi.fn(), + isEnabled: vi.fn().mockReturnValue(false), + }, +})); + +import { render } from "ink-testing-library"; +import React from "react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import * as versionModule from "../version.js"; + +import { UpdateNotification } from "./UpdateNotification.js"; + +const mockVersionModule = vi.mocked(versionModule); + +describe("UpdateNotification", () => { + let originalNodeEnv: string | undefined; + + beforeEach(() => { + vi.clearAllMocks(); + originalNodeEnv = process.env.NODE_ENV; + // Default mock implementations + mockVersionModule.getLatestVersion.mockResolvedValue("1.0.1"); + mockVersionModule.compareVersions.mockReturnValue("older"); + }); + + afterEach(() => { + // Restore original NODE_ENV + if (originalNodeEnv !== undefined) { + process.env.NODE_ENV = originalNodeEnv; + } else { + delete process.env.NODE_ENV; + } + }); + + it("should not check for updates when version ends with -dev", async () => { + // Set NODE_ENV to non-test value to enable update checks + process.env.NODE_ENV = "development"; + mockVersionModule.getVersion.mockReturnValue("1.0.0-dev"); + + render(); + + // Wait a bit to ensure useEffect has run + await new Promise((resolve) => setTimeout(resolve, 50)); + + // getLatestVersion should not have been called for dev versions + expect(mockVersionModule.getLatestVersion).not.toHaveBeenCalled(); + }); + + it("should check for updates when version does not end with -dev", async () => { + // Set NODE_ENV to non-test value to enable update checks + process.env.NODE_ENV = "development"; + mockVersionModule.getVersion.mockReturnValue("1.0.0"); + + render(); + + // Wait a bit to ensure useEffect has run + await new Promise((resolve) => setTimeout(resolve, 50)); + + // getLatestVersion should have been called for non-dev versions + expect(mockVersionModule.getLatestVersion).toHaveBeenCalled(); + }); + + it("should handle various dev version formats", async () => { + // Set NODE_ENV to non-test value to enable update checks + process.env.NODE_ENV = "development"; + const devVersions = ["1.0.0-dev", "2.1.3-dev", "0.5.0-dev"]; + + for (const version of devVersions) { + vi.clearAllMocks(); + mockVersionModule.getVersion.mockReturnValue(version); + + render(); + + // Wait a bit to ensure useEffect has run + await new Promise((resolve) => setTimeout(resolve, 50)); + + expect(mockVersionModule.getLatestVersion).not.toHaveBeenCalled(); + } + }); + + it("should still check for updates with other version suffixes", async () => { + // Set NODE_ENV to non-test value to enable update checks + process.env.NODE_ENV = "development"; + const nonDevVersions = ["1.0.0-beta", "1.0.0-alpha", "1.0.0-rc1"]; + + for (const version of nonDevVersions) { + vi.clearAllMocks(); + mockVersionModule.getVersion.mockReturnValue(version); + + render(); + + // Wait a bit to ensure useEffect has run + await new Promise((resolve) => setTimeout(resolve, 50)); + + expect(mockVersionModule.getLatestVersion).toHaveBeenCalled(); + } + }); +}); \ No newline at end of file diff --git a/src/ui/UpdateNotification.tsx b/src/ui/UpdateNotification.tsx index c893da02e..0179b5e6b 100644 --- a/src/ui/UpdateNotification.tsx +++ b/src/ui/UpdateNotification.tsx @@ -23,6 +23,11 @@ const UpdateNotification: React.FC = ({ return; } + // Skip update check for development versions + if (currentVersion.endsWith("-dev")) { + return; + } + const abortController = new AbortController(); const checkForUpdate = async () => { From ac3b3c3ff050f45e7b3e9c093c755362e09a4e8e Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 9 Aug 2025 11:33:08 -0400 Subject: [PATCH 3/4] add .next to list of folders to ignore --- src/ui/FileSearchUI.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/src/ui/FileSearchUI.tsx b/src/ui/FileSearchUI.tsx index 74dfb51c1..e9d63e595 100644 --- a/src/ui/FileSearchUI.tsx +++ b/src/ui/FileSearchUI.tsx @@ -95,6 +95,7 @@ const initializeCache = async (): Promise => { "**/*.tgz", "**/*.rar", "**/*.7z", + "**/*.next", ], dot: true, absolute: false, From be21d5cd43cf007ae94d7a40cdfcd2fdd4ad2b23 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 9 Aug 2025 11:41:01 -0400 Subject: [PATCH 4/4] fix: windows test failure --- src/tools/runTerminalCommand.test.ts | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/tools/runTerminalCommand.test.ts b/src/tools/runTerminalCommand.test.ts index 9266000aa..7b037c802 100644 --- a/src/tools/runTerminalCommand.test.ts +++ b/src/tools/runTerminalCommand.test.ts @@ -22,10 +22,18 @@ describe("runTerminalCommandTool", () => { expect(result.trim()).toMatch(/^\/.*$/); // Should be an absolute path }); - it("should execute ls command and return file listings", async () => { - const result = await runTerminalCommandTool.run({ command: "ls -la ." }); - expect(result).toContain("."); - expect(result).toContain(".."); + it("should execute directory listing command and return file listings", async () => { + // Use a cross-platform command that works on both Unix and Windows + const command = process.platform === 'win32' ? 'dir' : 'ls -la .'; + const result = await runTerminalCommandTool.run({ command }); + + // On Windows, look for entries, on Unix look for . and .. + if (process.platform === 'win32') { + expect(result).toContain("."); + } else { + expect(result).toContain("."); + expect(result).toContain(".."); + } }); it("should handle commands with multiple arguments", async () => {