Merge branch 'main' into fix-rerenders

This commit is contained in:
Nate 2025-08-10 11:21:15 -04:00
commit 3d383841b7
6 changed files with 327 additions and 7 deletions

View file

@ -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 <DIR> 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 () => {

View file

@ -95,6 +95,7 @@ const initializeCache = async (): Promise<void> => {
"**/*.tgz",
"**/*.rar",
"**/*.7z",
"**/*.next",
],
dot: true,
absolute: false,

View file

@ -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(<UpdateNotification />);
// 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(<UpdateNotification />);
// 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(<UpdateNotification />);
// 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(<UpdateNotification />);
// Wait a bit to ensure useEffect has run
await new Promise((resolve) => setTimeout(resolve, 50));
expect(mockVersionModule.getLatestVersion).toHaveBeenCalled();
}
});
});

View file

@ -23,6 +23,11 @@ const UpdateNotification: React.FC<UpdateNotificationProps> = ({
return;
}
// Skip update check for development versions
if (currentVersion.endsWith("-dev")) {
return;
}
const abortController = new AbortController();
const checkForUpdate = async () => {

View file

@ -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<UserInputProps> = ({
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

View file

@ -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();
});
});