Compare commits

..

21 Commits

Author SHA1 Message Date
Aishanee Shah 6f1970df81 refactor(core): use @google/genai Type enum in tool definitions 2026-02-11 19:02:22 +00:00
Aishanee Shah c4fe8f4ff1 feat(core): refactor session learnings as a builtin hook 2026-02-11 18:54:17 +00:00
Aishanee Shah b36e4eb1eb fix(core): add null check for recordingService in sessionLearningsService 2026-02-11 18:54:17 +00:00
Aishanee Shah 5f034e58af feat(core): enhance session learnings summary hook with configurable output and descriptive names 2026-02-11 18:54:17 +00:00
Aishanee Shah f72359efef feat(core): implement session learnings summary hook 2026-02-11 18:54:17 +00:00
Adib234 84ce53aafa feat(plan): allow skills to be enabled in plan mode (#18817)
Co-authored-by: Jerop Kipruto <jerop@google.com>
2026-02-11 17:59:03 +00:00
Sandy Tao b19b026f30 fix(cli): update F12 behavior to only open drawer if browser fails (#18829) 2026-02-11 17:45:43 +00:00
Jacob Richman eb9223b6a4 Fix pressing any key to exit select mode. (#18421) 2026-02-11 17:38:01 +00:00
Jerop Kipruto 65d26e73a2 feat(plan): document and validate Plan Mode policy overrides (#18825) 2026-02-11 17:32:02 +00:00
Brad Dux 0080589939 fix(cli): resolve double rendering in shpool and address vscode lint warnings (#18704) 2026-02-11 17:29:18 +00:00
Sehoon Shon 34a47a51f4 fix(core): cache CLI version to ensure consistency during sessions (#18793) 2026-02-11 17:01:50 +00:00
Dmitry Lyalin f5dd1068f6 fix(core): complete MCP discovery when configured servers are skipped (#18586)
Co-authored-by: christine betts <chrstn@uw.edu>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-02-11 16:30:46 +00:00
matt korwel c202cf3145 perf(cli): truncate large debug logs and limit message history (#18663) 2026-02-11 15:17:01 +00:00
Jack Wotherspoon 5baad108d9 feat: multi-line text answers in ask-user tool (#18741) 2026-02-11 14:14:53 +00:00
Dev Randalpura 63e9d5d15f perf(ui): optimize table rendering by memoizing styled characters (#18770) 2026-02-11 13:10:30 +00:00
Abhi 3776c4d613 feat(masking): enable tool output masking by default (#18564) 2026-02-11 06:21:55 +00:00
Sandy Tao 2af5a3a01e fix(cli): allow closing debug console after auto-open via flicker (#18795) 2026-02-11 05:37:23 +00:00
Christian Gunderman 0d034b8c18 Introduce limits for search results. (#18767) 2026-02-11 03:50:10 +00:00
Jerop Kipruto 49d55d972e feat(core): formalize 5-phase sequential planning workflow (#18759) 2026-02-11 03:02:20 +00:00
Dmitry Lyalin 7a02d7261a feat(cli): add setting to hide shortcuts hint UI (#18562) 2026-02-11 02:46:20 +00:00
Jerop Kipruto 9c11ff2d58 test(evals): mark all save_memory evals as USUALLY_PASSES due to unreliability (#18786) 2026-02-11 02:16:52 +00:00
58 changed files with 2024 additions and 388 deletions
-3
View File
@@ -1,8 +1,5 @@
{
"experimental": {
"toolOutputMasking": {
"enabled": true
},
"plan": true
},
"general": {
+2 -1
View File
@@ -131,7 +131,8 @@ available combinations.
- `!` on an empty prompt: Enter or exit shell mode.
- `?` on an empty prompt: Toggle the shortcuts panel above the input. Press
`Esc`, `Backspace`, or any printable key to close it. Press `?` again to close
the panel and insert a `?` into the prompt.
the panel and insert a `?` into the prompt. You can hide only the hint text
via `ui.showShortcutsHint`, without changing this keyboard behavior.
- `\` (at end of a line) + `Enter`: Insert a newline without leaving single-line
mode.
- `Esc` pressed twice quickly: Clear the input prompt if it is not empty,
+78 -2
View File
@@ -30,6 +30,8 @@ implementation strategy.
- [The Planning Workflow](#the-planning-workflow)
- [Exiting Plan Mode](#exiting-plan-mode)
- [Tool Restrictions](#tool-restrictions)
- [Customizing Planning with Skills](#customizing-planning-with-skills)
- [Customizing Policies](#customizing-policies)
## Starting in Plan Mode
@@ -68,8 +70,10 @@ You can enter Plan Mode in three ways:
1. **Requirements:** The agent clarifies goals using `ask_user`.
2. **Exploration:** The agent uses read-only tools (like [`read_file`]) to map
the codebase and validate assumptions.
3. **Planning:** A detailed plan is written to a temporary Markdown file.
4. **Review:** You review the plan.
3. **Design:** The agent proposes alternative approaches with a recommended
solution for you to choose from.
4. **Planning:** A detailed plan is written to a temporary Markdown file.
5. **Review:** You review the plan.
- **Approve:** Exit Plan Mode and start implementation (switching to
Auto-Edit or Default approval mode).
- **Iterate:** Provide feedback to refine the plan.
@@ -95,6 +99,75 @@ These are the only allowed tools:
`postgres_read_schema`) are allowed.
- **Planning (Write):** [`write_file`] and [`replace`] ONLY allowed for `.md`
files in the `~/.gemini/tmp/<project>/plans/` directory.
- **Skills:** [`activate_skill`] (allows loading specialized instructions and
resources in a read-only manner)
### Customizing Planning with Skills
You can leverage [Agent Skills](./skills.md) to customize how Gemini CLI
approaches planning for specific types of tasks. When a skill is activated
during Plan Mode, its specialized instructions and procedural workflows will
guide the research and design phases.
For example:
- A **"Database Migration"** skill could ensure the plan includes data safety
checks and rollback strategies.
- A **"Security Audit"** skill could prompt the agent to look for specific
vulnerabilities during codebase exploration.
- A **"Frontend Design"** skill could guide the agent to use specific UI
components and accessibility standards in its proposal.
To use a skill in Plan Mode, you can explicitly ask the agent to "use the
[skill-name] skill to plan..." or the agent may autonomously activate it based
on the task description.
### Customizing Policies
Plan Mode is designed to be read-only by default to ensure safety during the
research phase. However, you may occasionally need to allow specific tools to
assist in your planning.
Because user policies (Tier 2) have a higher base priority than built-in
policies (Tier 1), you can override Plan Mode's default restrictions by creating
a rule in your `~/.gemini/policies/` directory.
#### Example: Allow `git status` and `git diff` in Plan Mode
This rule allows you to check the repository status and see changes while in
Plan Mode.
`~/.gemini/policies/git-research.toml`
```toml
[[rule]]
toolName = "run_shell_command"
commandPrefix = ["git status", "git diff"]
decision = "allow"
priority = 100
modes = ["plan"]
```
#### Example: Enable research sub-agents in Plan Mode
You can enable [experimental research sub-agents] like `codebase_investigator`
to help gather architecture details during the planning phase.
`~/.gemini/policies/research-subagents.toml`
```toml
[[rule]]
toolName = "codebase_investigator"
decision = "allow"
priority = 100
modes = ["plan"]
```
Tell the agent it can use these tools in your prompt, for example: _"You can
check ongoing changes in git."_
For more information on how the policy engine works, see the [Policy Engine
Guide].
[`list_directory`]: /docs/tools/file-system.md#1-list_directory-readfolder
[`read_file`]: /docs/tools/file-system.md#2-read_file-readfile
@@ -104,3 +177,6 @@ These are the only allowed tools:
[`google_web_search`]: /docs/tools/web-search.md
[`replace`]: /docs/tools/file-system.md#6-replace-edit
[MCP tools]: /docs/tools/mcp-server.md
[`activate_skill`]: /docs/cli/skills.md
[experimental research sub-agents]: /docs/core/subagents.md
[Policy Engine Guide]: /docs/core/policy-engine.md
+6 -4
View File
@@ -49,6 +49,7 @@ they appear in the UI.
| Dynamic Window Title | `ui.dynamicWindowTitle` | Update the terminal window title with current status icons (Ready: ◇, Action Required: ✋, Working: ✦) | `true` |
| Show Home Directory Warning | `ui.showHomeDirectoryWarning` | Show a warning when running Gemini CLI in the home directory. | `true` |
| Hide Tips | `ui.hideTips` | Hide helpful tips in the UI | `false` |
| Show Shortcuts Hint | `ui.showShortcutsHint` | Show the "? for shortcuts" hint above the input. | `true` |
| Hide Banner | `ui.hideBanner` | Hide the application banner | `false` |
| Hide Context Summary | `ui.hideContextSummary` | Hide the context summary (GEMINI.md, MCP servers) above the input. | `false` |
| Hide CWD | `ui.footer.hideCWD` | Hide the current working directory path in the footer. | `false` |
@@ -124,10 +125,11 @@ they appear in the UI.
### Experimental
| UI Label | Setting | Description | Default |
| ---------------- | ---------------------------- | ----------------------------------------------------------------------------------- | ------- |
| Use OSC 52 Paste | `experimental.useOSC52Paste` | Use OSC 52 sequence for pasting instead of clipboardy (useful for remote sessions). | `false` |
| Plan | `experimental.plan` | Enable planning features (Plan Mode and tools). | `false` |
| UI Label | Setting | Description | Default |
| -------------------------- | ---------------------------------------- | ----------------------------------------------------------------------------------- | ------- |
| Enable Tool Output Masking | `experimental.toolOutputMasking.enabled` | Enables tool output masking to save tokens. | `true` |
| Use OSC 52 Paste | `experimental.useOSC52Paste` | Use OSC 52 sequence for pasting instead of clipboardy (useful for remote sessions). | `false` |
| Plan | `experimental.plan` | Enable planning features (Plan Mode and tools). | `false` |
### Skills
+13 -3
View File
@@ -119,9 +119,17 @@ For example:
Approval modes allow the policy engine to apply different sets of rules based on
the CLI's operational mode. A rule can be associated with one or more modes
(e.g., `yolo`, `autoEdit`). The rule will only be active if the CLI is running
in one of its specified modes. If a rule has no modes specified, it is always
active.
(e.g., `yolo`, `autoEdit`, `plan`). The rule will only be active if the CLI is
running in one of its specified modes. If a rule has no modes specified, it is
always active.
- `default`: The standard interactive mode where most write tools require
confirmation.
- `autoEdit`: Optimized for automated code editing; some write tools may be
auto-approved.
- `plan`: A strict, read-only mode for research and design. See [Customizing
Plan Mode Policies].
- `yolo`: A mode where all tools are auto-approved (use with extreme caution).
## Rule matching
@@ -303,3 +311,5 @@ out-of-the-box experience.
- In **`yolo`** mode, a high-priority rule allows all tools.
- In **`autoEdit`** mode, rules allow certain write operations to happen without
prompting.
[Customizing Plan Mode Policies]: /docs/cli/plan-mode.md#customizing-policies
+26
View File
@@ -220,6 +220,10 @@ their corresponding top-level category object in your `settings.json` file.
- **Description:** Hide helpful tips in the UI
- **Default:** `false`
- **`ui.showShortcutsHint`** (boolean):
- **Description:** Show the "? for shortcuts" hint above the input.
- **Default:** `true`
- **`ui.hideBanner`** (boolean):
- **Description:** Hide the application banner
- **Default:** `false`
@@ -848,6 +852,28 @@ their corresponding top-level category object in your `settings.json` file.
#### `experimental`
- **`experimental.toolOutputMasking.enabled`** (boolean):
- **Description:** Enables tool output masking to save tokens.
- **Default:** `true`
- **Requires restart:** Yes
- **`experimental.toolOutputMasking.toolProtectionThreshold`** (number):
- **Description:** Minimum number of tokens to protect from masking (most
recent tool outputs).
- **Default:** `50000`
- **Requires restart:** Yes
- **`experimental.toolOutputMasking.minPrunableTokensThreshold`** (number):
- **Description:** Minimum prunable tokens required to trigger a masking pass.
- **Default:** `30000`
- **Requires restart:** Yes
- **`experimental.toolOutputMasking.protectLatestTurn`** (boolean):
- **Description:** Ensures the absolute latest turn is never masked,
regardless of token count.
- **Default:** `true`
- **Requires restart:** Yes
- **`experimental.enableAgents`** (boolean):
- **Description:** Enable local and remote subagents. Warning: Experimental
feature, uses YOLO mode for subagents
+2 -2
View File
@@ -14,7 +14,7 @@ import {
describe('save_memory', () => {
const TEST_PREFIX = 'Save memory test: ';
const rememberingFavoriteColor = "Agent remembers user's favorite color";
evalTest('ALWAYS_PASSES', {
evalTest('USUALLY_PASSES', {
name: rememberingFavoriteColor,
params: {
settings: { tools: { core: ['save_memory'] } },
@@ -57,7 +57,7 @@ describe('save_memory', () => {
});
const rememberingWorkflow = 'Agent remembers workflow preferences';
evalTest('ALWAYS_PASSES', {
evalTest('USUALLY_PASSES', {
name: rememberingWorkflow,
params: {
settings: { tools: { core: ['save_memory'] } },
+2
View File
@@ -796,6 +796,8 @@ export async function loadCliConfig(
toolOutputMasking: settings.experimental?.toolOutputMasking,
noBrowser: !!process.env['NO_BROWSER'],
summarizeToolOutput: settings.model?.summarizeToolOutput,
sessionLearnings: settings.general?.sessionLearnings?.enabled,
sessionLearningsOutputPath: settings.general?.sessionLearnings?.outputPath,
ideMode,
disableLoopDetection: settings.model?.disableLoopDetection,
compressionThreshold: settings.model?.compressionThreshold,
@@ -186,6 +186,9 @@ describe('SettingsSchema', () => {
expect(getSettingsSchema().ui.properties.hideTips.showInDialog).toBe(
true,
);
expect(
getSettingsSchema().ui.properties.showShortcutsHint.showInDialog,
).toBe(true);
expect(getSettingsSchema().ui.properties.hideBanner.showInDialog).toBe(
true,
);
@@ -328,6 +331,28 @@ describe('SettingsSchema', () => {
).toBe('Enable debug logging of keystrokes to the console.');
});
it('should have showShortcutsHint setting in schema', () => {
expect(getSettingsSchema().ui.properties.showShortcutsHint).toBeDefined();
expect(getSettingsSchema().ui.properties.showShortcutsHint.type).toBe(
'boolean',
);
expect(getSettingsSchema().ui.properties.showShortcutsHint.category).toBe(
'UI',
);
expect(getSettingsSchema().ui.properties.showShortcutsHint.default).toBe(
true,
);
expect(
getSettingsSchema().ui.properties.showShortcutsHint.requiresRestart,
).toBe(false);
expect(
getSettingsSchema().ui.properties.showShortcutsHint.showInDialog,
).toBe(true);
expect(
getSettingsSchema().ui.properties.showShortcutsHint.description,
).toBe('Show the "? for shortcuts" hint above the input.');
});
it('should have enableAgents setting in schema', () => {
const setting = getSettingsSchema().experimental.properties.enableAgents;
expect(setting).toBeDefined();
+43 -3
View File
@@ -322,6 +322,37 @@ const SETTINGS_SCHEMA = {
},
description: 'Settings for automatic session cleanup.',
},
sessionLearnings: {
type: 'object',
label: 'Session Learnings',
category: 'General',
requiresRestart: false,
default: {},
description: 'Settings for session learning summaries.',
showInDialog: false,
properties: {
enabled: {
type: 'boolean',
label: 'Enable Session Learnings',
category: 'General',
requiresRestart: false,
default: false,
description:
'Automatically generate a session-learnings.md file when the session ends.',
showInDialog: true,
},
outputPath: {
type: 'string',
label: 'Output Path',
category: 'General',
requiresRestart: false,
default: undefined as string | undefined,
description:
'Directory where session-learnings files should be saved. Defaults to project root.',
showInDialog: true,
},
},
},
},
},
output: {
@@ -462,6 +493,15 @@ const SETTINGS_SCHEMA = {
description: 'Hide helpful tips in the UI',
showInDialog: true,
},
showShortcutsHint: {
type: 'boolean',
label: 'Show Shortcuts Hint',
category: 'UI',
requiresRestart: false,
default: true,
description: 'Show the "? for shortcuts" hint above the input.',
showInDialog: true,
},
hideBanner: {
type: 'boolean',
label: 'Hide Banner',
@@ -1462,7 +1502,7 @@ const SETTINGS_SCHEMA = {
label: 'Tool Output Masking',
category: 'Experimental',
requiresRestart: true,
ignoreInDocs: true,
ignoreInDocs: false,
default: {},
description:
'Advanced settings for tool output masking to manage context window efficiency.',
@@ -1473,9 +1513,9 @@ const SETTINGS_SCHEMA = {
label: 'Enable Tool Output Masking',
category: 'Experimental',
requiresRestart: true,
default: false,
default: true,
description: 'Enables tool output masking to save tokens.',
showInDialog: false,
showInDialog: true,
},
toolProtectionThreshold: {
type: 'number',
+10 -19
View File
@@ -238,18 +238,15 @@ vi.mock('./validateNonInterActiveAuth.js', () => ({
}));
describe('gemini.tsx main function', () => {
let originalEnvGeminiSandbox: string | undefined;
let originalEnvSandbox: string | undefined;
let originalIsTTY: boolean | undefined;
let initialUnhandledRejectionListeners: NodeJS.UnhandledRejectionListener[] =
[];
beforeEach(() => {
// Store and clear sandbox-related env variables to ensure a consistent test environment
originalEnvGeminiSandbox = process.env['GEMINI_SANDBOX'];
originalEnvSandbox = process.env['SANDBOX'];
delete process.env['GEMINI_SANDBOX'];
delete process.env['SANDBOX'];
vi.stubEnv('GEMINI_SANDBOX', '');
vi.stubEnv('SANDBOX', '');
vi.stubEnv('SHPOOL_SESSION_NAME', '');
initialUnhandledRejectionListeners =
process.listeners('unhandledRejection');
@@ -260,18 +257,6 @@ describe('gemini.tsx main function', () => {
});
afterEach(() => {
// Restore original env variables
if (originalEnvGeminiSandbox !== undefined) {
process.env['GEMINI_SANDBOX'] = originalEnvGeminiSandbox;
} else {
delete process.env['GEMINI_SANDBOX'];
}
if (originalEnvSandbox !== undefined) {
process.env['SANDBOX'] = originalEnvSandbox;
} else {
delete process.env['SANDBOX'];
}
const currentListeners = process.listeners('unhandledRejection');
currentListeners.forEach((listener) => {
if (!initialUnhandledRejectionListeners.includes(listener)) {
@@ -282,6 +267,7 @@ describe('gemini.tsx main function', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(process.stdin as any).isTTY = originalIsTTY;
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
@@ -1209,7 +1195,12 @@ describe('startInteractiveUI', () => {
registerTelemetryConfig: vi.fn(),
}));
beforeEach(() => {
vi.stubEnv('SHPOOL_SESSION_NAME', '');
});
afterEach(() => {
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
@@ -1308,7 +1299,7 @@ describe('startInteractiveUI', () => {
// Verify all startup tasks were called
expect(getVersion).toHaveBeenCalledTimes(1);
expect(registerCleanup).toHaveBeenCalledTimes(3);
expect(registerCleanup).toHaveBeenCalledTimes(4);
// Verify cleanup handler is registered with unmount function
const cleanupFn = vi.mocked(registerCleanup).mock.calls[0][0];
+33 -20
View File
@@ -57,8 +57,8 @@ import {
writeToStderr,
disableMouseEvents,
enableMouseEvents,
enterAlternateScreen,
disableLineWrapping,
enableLineWrapping,
shouldEnterAlternateScreen,
startupProfiler,
ExitCodes,
@@ -89,6 +89,7 @@ import { SessionStatsProvider } from './ui/contexts/SessionContext.js';
import { VimModeProvider } from './ui/contexts/VimModeContext.js';
import { KeypressProvider } from './ui/contexts/KeypressContext.js';
import { useKittyKeyboardProtocol } from './ui/hooks/useKittyKeyboardProtocol.js';
import { useTerminalSize } from './ui/hooks/useTerminalSize.js';
import {
relaunchAppInChildProcess,
relaunchOnExitCode,
@@ -214,9 +215,13 @@ export async function startInteractiveUI(
const { stdout: inkStdout, stderr: inkStderr } = createWorkingStdio();
const isShpool = !!process.env['SHPOOL_SESSION_NAME'];
// Create wrapper component to use hooks inside render
const AppWrapper = () => {
useKittyKeyboardProtocol();
const { columns, rows } = useTerminalSize();
return (
<SettingsContext.Provider value={settings}>
<KeypressProvider
@@ -234,6 +239,7 @@ export async function startInteractiveUI(
<SessionStatsProvider>
<VimModeProvider settings={settings}>
<AppContainer
key={`${columns}-${rows}`}
config={config}
startupWarnings={startupWarnings}
version={version}
@@ -250,6 +256,17 @@ export async function startInteractiveUI(
);
};
if (isShpool) {
// Wait a moment for shpool to stabilize terminal size and state.
// shpool is a persistence tool that restores terminal state by replaying it.
// This delay gives shpool time to finish its restoration replay and send
// the actual terminal size (often via an immediate SIGWINCH) before we
// render the first TUI frame. Without this, the first frame may be
// garbled or rendered at an incorrect size, which disabling incremental
// rendering alone cannot fix for the initial frame.
await new Promise((resolve) => setTimeout(resolve, 100));
}
const instance = render(
process.env['DEBUG'] ? (
<React.StrictMode>
@@ -273,10 +290,19 @@ export async function startInteractiveUI(
patchConsole: false,
alternateBuffer: useAlternateBuffer,
incrementalRendering:
settings.merged.ui.incrementalRendering !== false && useAlternateBuffer,
settings.merged.ui.incrementalRendering !== false &&
useAlternateBuffer &&
!isShpool,
},
);
if (useAlternateBuffer) {
disableLineWrapping();
registerCleanup(() => {
enableLineWrapping();
});
}
checkForUpdates(settings)
.then((info) => {
handleAutoUpdate(info, settings, config.getProjectRoot());
@@ -590,26 +616,13 @@ export async function main() {
// input showing up in the output.
process.stdin.setRawMode(true);
if (
shouldEnterAlternateScreen(
isAlternateBufferEnabled(settings),
config.getScreenReader(),
)
) {
enterAlternateScreen();
disableLineWrapping();
// Ink will cleanup so there is no need for us to manually cleanup.
}
// This cleanup isn't strictly needed but may help in certain situations.
const restoreRawMode = () => {
process.on('SIGTERM', () => {
process.stdin.setRawMode(wasRaw);
};
process.off('SIGTERM', restoreRawMode);
process.on('SIGTERM', restoreRawMode);
process.off('SIGINT', restoreRawMode);
process.on('SIGINT', restoreRawMode);
});
process.on('SIGINT', () => {
process.stdin.setRawMode(wasRaw);
});
}
await setupTerminalAndTheme(config, settings);
+102 -126
View File
@@ -84,7 +84,7 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
};
});
import ansiEscapes from 'ansi-escapes';
import { type LoadedSettings, mergeSettings } from '../config/settings.js';
import { mergeSettings, type LoadedSettings } from '../config/settings.js';
import type { InitializationResult } from '../core/initializer.js';
import { useQuotaAndFallback } from './hooks/useQuotaAndFallback.js';
import { UIStateContext, type UIState } from './contexts/UIStateContext.js';
@@ -92,6 +92,7 @@ import {
UIActionsContext,
type UIActions,
} from './contexts/UIActionsContext.js';
import { KeypressProvider } from './contexts/KeypressContext.js';
// Mock useStdout to capture terminal title writes
vi.mock('ink', async (importOriginal) => {
@@ -133,7 +134,6 @@ vi.mock('./hooks/useGeminiStream.js');
vi.mock('./hooks/vim.js');
vi.mock('./hooks/useFocus.js');
vi.mock('./hooks/useBracketedPaste.js');
vi.mock('./hooks/useKeypress.js');
vi.mock('./hooks/useLoadingIndicator.js');
vi.mock('./hooks/useFolderTrust.js');
vi.mock('./hooks/useIdeTrustListener.js');
@@ -197,7 +197,7 @@ import { useTextBuffer } from './components/shared/text-buffer.js';
import { useLogger } from './hooks/useLogger.js';
import { useLoadingIndicator } from './hooks/useLoadingIndicator.js';
import { useInputHistoryStore } from './hooks/useInputHistoryStore.js';
import { useKeypress, type Key } from './hooks/useKeypress.js';
import { useKeypress } from './hooks/useKeypress.js';
import { measureElement } from 'ink';
import { useTerminalSize } from './hooks/useTerminalSize.js';
import {
@@ -232,13 +232,15 @@ describe('AppContainer State Management', () => {
resumedSessionData?: ResumedSessionData;
} = {}) => (
<SettingsContext.Provider value={settings}>
<AppContainer
config={config}
version={version}
initializationResult={initResult}
startupWarnings={startupWarnings}
resumedSessionData={resumedSessionData}
/>
<KeypressProvider config={config}>
<AppContainer
config={config}
version={version}
initializationResult={initResult}
startupWarnings={startupWarnings}
resumedSessionData={resumedSessionData}
/>
</KeypressProvider>
</SettingsContext.Provider>
);
@@ -268,7 +270,6 @@ describe('AppContainer State Management', () => {
const mockedUseTextBuffer = useTextBuffer as Mock;
const mockedUseLogger = useLogger as Mock;
const mockedUseLoadingIndicator = useLoadingIndicator as Mock;
const mockedUseKeypress = useKeypress as Mock;
const mockedUseInputHistoryStore = useInputHistoryStore as Mock;
const mockedUseHookDisplayState = useHookDisplayState as Mock;
const mockedUseTerminalTheme = useTerminalTheme as Mock;
@@ -1770,47 +1771,36 @@ describe('AppContainer State Management', () => {
});
describe('Keyboard Input Handling (CTRL+C / CTRL+D)', () => {
let handleGlobalKeypress: (key: Key) => boolean;
let mockHandleSlashCommand: Mock;
let mockCancelOngoingRequest: Mock;
let rerender: () => void;
let unmount: () => void;
let stdin: ReturnType<typeof render>['stdin'];
// Helper function to reduce boilerplate in tests
const setupKeypressTest = async () => {
const renderResult = renderAppContainer();
stdin = renderResult.stdin;
await act(async () => {
vi.advanceTimersByTime(0);
});
rerender = () => renderResult.rerender(getAppContainer());
rerender = () => {
renderResult.rerender(getAppContainer());
};
unmount = renderResult.unmount;
};
const pressKey = (key: Partial<Key>, times = 1) => {
const pressKey = (sequence: string, times = 1) => {
for (let i = 0; i < times; i++) {
act(() => {
handleGlobalKeypress({
name: 'c',
shift: false,
alt: false,
ctrl: false,
cmd: false,
...key,
} as Key);
stdin.write(sequence);
});
rerender();
}
};
beforeEach(() => {
// Capture the keypress handler from the AppContainer
mockedUseKeypress.mockImplementation(
(callback: (key: Key) => boolean) => {
handleGlobalKeypress = callback;
},
);
// Mock slash command handler
mockHandleSlashCommand = vi.fn();
mockedUseSlashCommandProcessor.mockReturnValue({
@@ -1855,7 +1845,7 @@ describe('AppContainer State Management', () => {
});
await setupKeypressTest();
pressKey({ name: 'c', ctrl: true });
pressKey('\x03'); // Ctrl+C
expect(mockCancelOngoingRequest).toHaveBeenCalledTimes(1);
expect(mockHandleSlashCommand).not.toHaveBeenCalled();
@@ -1865,7 +1855,7 @@ describe('AppContainer State Management', () => {
it('should quit on second press', async () => {
await setupKeypressTest();
pressKey({ name: 'c', ctrl: true }, 2);
pressKey('\x03', 2); // Ctrl+C
expect(mockCancelOngoingRequest).toHaveBeenCalledTimes(2);
expect(mockHandleSlashCommand).toHaveBeenCalledWith(
@@ -1880,7 +1870,7 @@ describe('AppContainer State Management', () => {
it('should reset press count after a timeout', async () => {
await setupKeypressTest();
pressKey({ name: 'c', ctrl: true });
pressKey('\x03'); // Ctrl+C
expect(mockHandleSlashCommand).not.toHaveBeenCalled();
// Advance timer past the reset threshold
@@ -1888,7 +1878,7 @@ describe('AppContainer State Management', () => {
vi.advanceTimersByTime(WARNING_PROMPT_DURATION_MS + 1);
});
pressKey({ name: 'c', ctrl: true });
pressKey('\x03'); // Ctrl+C
expect(mockHandleSlashCommand).not.toHaveBeenCalled();
unmount();
});
@@ -1898,7 +1888,7 @@ describe('AppContainer State Management', () => {
it('should quit on second press if buffer is empty', async () => {
await setupKeypressTest();
pressKey({ name: 'd', ctrl: true }, 2);
pressKey('\x04', 2); // Ctrl+D
expect(mockHandleSlashCommand).toHaveBeenCalledWith(
'/quit',
@@ -1909,7 +1899,7 @@ describe('AppContainer State Management', () => {
unmount();
});
it('should NOT quit if buffer is not empty (bubbles from InputPrompt)', async () => {
it('should NOT quit if buffer is not empty', async () => {
mockedUseTextBuffer.mockReturnValue({
text: 'some text',
setText: vi.fn(),
@@ -1919,30 +1909,12 @@ describe('AppContainer State Management', () => {
});
await setupKeypressTest();
// Capture return value
let result = true;
const originalPressKey = (key: Partial<Key>) => {
act(() => {
result = handleGlobalKeypress({
name: 'd',
shift: false,
alt: false,
ctrl: true,
cmd: false,
...key,
} as Key);
});
rerender();
};
pressKey('\x04'); // Ctrl+D
originalPressKey({ name: 'd', ctrl: true });
// AppContainer's handler should return true if it reaches it
expect(result).toBe(true);
// But it should only be called once, so count is 1, not quitting yet.
// Should only be called once, so count is 1, not quitting yet.
expect(mockHandleSlashCommand).not.toHaveBeenCalled();
originalPressKey({ name: 'd', ctrl: true });
pressKey('\x04'); // Ctrl+D
// Now count is 2, it should quit.
expect(mockHandleSlashCommand).toHaveBeenCalledWith(
'/quit',
@@ -1956,7 +1928,7 @@ describe('AppContainer State Management', () => {
it('should reset press count after a timeout', async () => {
await setupKeypressTest();
pressKey({ name: 'd', ctrl: true });
pressKey('\x04'); // Ctrl+D
expect(mockHandleSlashCommand).not.toHaveBeenCalled();
// Advance timer past the reset threshold
@@ -1964,7 +1936,7 @@ describe('AppContainer State Management', () => {
vi.advanceTimersByTime(WARNING_PROMPT_DURATION_MS + 1);
});
pressKey({ name: 'd', ctrl: true });
pressKey('\x04'); // Ctrl+D
expect(mockHandleSlashCommand).not.toHaveBeenCalled();
unmount();
});
@@ -1982,7 +1954,7 @@ describe('AppContainer State Management', () => {
it('should focus shell input on Tab', async () => {
await setupKeypressTest();
pressKey({ name: 'tab', shift: false });
pressKey('\t');
expect(capturedUIState.embeddedShellFocused).toBe(true);
unmount();
@@ -1992,11 +1964,11 @@ describe('AppContainer State Management', () => {
await setupKeypressTest();
// Focus first
pressKey({ name: 'tab', shift: false });
pressKey('\t');
expect(capturedUIState.embeddedShellFocused).toBe(true);
// Unfocus via Shift+Tab
pressKey({ name: 'tab', shift: true });
pressKey('\x1b[Z');
expect(capturedUIState.embeddedShellFocused).toBe(false);
unmount();
});
@@ -2015,13 +1987,7 @@ describe('AppContainer State Management', () => {
// Focus it
act(() => {
handleGlobalKeypress({
name: 'tab',
shift: false,
alt: false,
ctrl: false,
cmd: false,
} as Key);
renderResult.stdin.write('\t');
});
expect(capturedUIState.embeddedShellFocused).toBe(true);
@@ -2056,7 +2022,7 @@ describe('AppContainer State Management', () => {
expect(capturedUIState.embeddedShellFocused).toBe(false);
// Press Tab
pressKey({ name: 'tab', shift: false });
pressKey('\t');
// Should be focused
expect(capturedUIState.embeddedShellFocused).toBe(true);
@@ -2084,7 +2050,7 @@ describe('AppContainer State Management', () => {
expect(capturedUIState.embeddedShellFocused).toBe(false);
// Press Ctrl+B
pressKey({ name: 'b', ctrl: true });
pressKey('\x02');
// Should have toggled (closed) the shell
expect(mockToggleBackgroundShell).toHaveBeenCalled();
@@ -2113,7 +2079,7 @@ describe('AppContainer State Management', () => {
});
// Press Ctrl+B
pressKey({ name: 'b', ctrl: true });
pressKey('\x02');
// Should have toggled (shown) the shell
expect(mockToggleBackgroundShell).toHaveBeenCalled();
@@ -2126,11 +2092,14 @@ describe('AppContainer State Management', () => {
});
describe('Copy Mode (CTRL+S)', () => {
let handleGlobalKeypress: (key: Key) => boolean;
let rerender: () => void;
let unmount: () => void;
let stdin: ReturnType<typeof render>['stdin'];
const setupCopyModeTest = async (isAlternateMode = false) => {
const setupCopyModeTest = async (
isAlternateMode = false,
childHandler?: Mock,
) => {
// Update settings for this test run
const defaultMergedSettings = mergeSettings({}, {}, {}, {}, true);
const testSettings = {
@@ -2144,23 +2113,39 @@ describe('AppContainer State Management', () => {
},
} as unknown as LoadedSettings;
const renderResult = renderAppContainer({ settings: testSettings });
function TestChild() {
useKeypress(childHandler || (() => {}), {
isActive: !!childHandler,
priority: true,
});
return null;
}
const getTree = (settings: LoadedSettings) => (
<SettingsContext.Provider value={settings}>
<KeypressProvider config={mockConfig}>
<AppContainer
config={mockConfig}
version="1.0.0"
initializationResult={mockInitResult}
/>
<TestChild />
</KeypressProvider>
</SettingsContext.Provider>
);
const renderResult = render(getTree(testSettings));
stdin = renderResult.stdin;
await act(async () => {
vi.advanceTimersByTime(0);
});
rerender = () =>
renderResult.rerender(getAppContainer({ settings: testSettings }));
rerender = () => renderResult.rerender(getTree(testSettings));
unmount = renderResult.unmount;
};
beforeEach(() => {
mocks.mockStdout.write.mockClear();
mockedUseKeypress.mockImplementation(
(callback: (key: Key) => boolean) => {
handleGlobalKeypress = callback;
},
);
vi.useFakeTimers();
});
@@ -2186,15 +2171,7 @@ describe('AppContainer State Management', () => {
mocks.mockStdout.write.mockClear(); // Clear initial enable call
act(() => {
handleGlobalKeypress({
name: 's',
shift: false,
alt: false,
ctrl: true,
cmd: false,
insertable: false,
sequence: '\x13',
});
stdin.write('\x13'); // Ctrl+S
});
rerender();
@@ -2213,30 +2190,14 @@ describe('AppContainer State Management', () => {
// Turn it on (disable mouse)
act(() => {
handleGlobalKeypress({
name: 's',
shift: false,
alt: false,
ctrl: true,
cmd: false,
insertable: false,
sequence: '\x13',
});
stdin.write('\x13'); // Ctrl+S
});
rerender();
expect(disableMouseEvents).toHaveBeenCalled();
// Turn it off (enable mouse)
act(() => {
handleGlobalKeypress({
name: 'any', // Any key should exit copy mode
shift: false,
alt: false,
ctrl: false,
cmd: false,
insertable: true,
sequence: 'a',
});
stdin.write('a'); // Any key should exit copy mode
});
rerender();
@@ -2249,15 +2210,7 @@ describe('AppContainer State Management', () => {
// Enter copy mode
act(() => {
handleGlobalKeypress({
name: 's',
shift: false,
alt: false,
ctrl: true,
cmd: false,
insertable: false,
sequence: '\x13',
});
stdin.write('\x13'); // Ctrl+S
});
rerender();
@@ -2265,15 +2218,7 @@ describe('AppContainer State Management', () => {
// Press any other key
act(() => {
handleGlobalKeypress({
name: 'a',
shift: false,
alt: false,
ctrl: false,
cmd: false,
insertable: true,
sequence: 'a',
});
stdin.write('a');
});
rerender();
@@ -2281,6 +2226,37 @@ describe('AppContainer State Management', () => {
expect(enableMouseEvents).toHaveBeenCalled();
unmount();
});
it('should have higher priority than other priority listeners when enabled', async () => {
// 1. Initial state with a child component's priority listener (already subscribed)
// It should NOT handle Ctrl+S so we can enter copy mode.
const childHandler = vi.fn().mockReturnValue(false);
await setupCopyModeTest(true, childHandler);
// 2. Enter copy mode
act(() => {
stdin.write('\x13'); // Ctrl+S
});
rerender();
// 3. Verify we are in copy mode
expect(disableMouseEvents).toHaveBeenCalled();
// 4. Press any key
childHandler.mockClear();
// Now childHandler should return true for other keys, simulating a greedy listener
childHandler.mockReturnValue(true);
act(() => {
stdin.write('a');
});
rerender();
// 5. Verify that the exit handler took priority and childHandler was NOT called
expect(childHandler).not.toHaveBeenCalled();
expect(enableMouseEvents).toHaveBeenCalled();
unmount();
});
}
});
});
+28 -31
View File
@@ -101,6 +101,7 @@ import { type LoadableSettingScope, SettingScope } from '../config/settings.js';
import { type InitializationResult } from '../core/initializer.js';
import { useFocus } from './hooks/useFocus.js';
import { useKeypress, type Key } from './hooks/useKeypress.js';
import { KeypressPriority } from './contexts/KeypressContext.js';
import { keyMatchers, Command } from './keyMatchers.js';
import { useLoadingIndicator } from './hooks/useLoadingIndicator.js';
import { useShellInactivityStatus } from './hooks/useShellInactivityStatus.js';
@@ -363,7 +364,9 @@ export const AppContainer = (props: AppContainerProps) => {
(async () => {
// Note: the program will not work if this fails so let errors be
// handled by the global catch.
await config.initialize();
if (!config.isInitialized()) {
await config.initialize();
}
setConfigInitialized(true);
startupProfiler.flush(config);
@@ -1481,13 +1484,6 @@ Logging in with Google... Restarting Gemini CLI to continue.
const handleGlobalKeypress = useCallback(
(key: Key): boolean => {
if (copyModeEnabled) {
setCopyModeEnabled(false);
enableMouseEvents();
// We don't want to process any other keys if we're in copy mode.
return true;
}
// Debug log keystrokes if enabled
if (settings.merged.general.debugKeystrokeLogging) {
debugLogger.log('[DEBUG] Keystroke:', JSON.stringify(key));
@@ -1520,28 +1516,15 @@ Logging in with Google... Restarting Gemini CLI to continue.
if (keyMatchers[Command.SHOW_ERROR_DETAILS](key)) {
if (settings.merged.general.devtools) {
void (async () => {
try {
const { startDevToolsServer } = await import(
'../utils/devtoolsService.js'
);
const { openBrowserSecurely, shouldLaunchBrowser } = await import(
'@google/gemini-cli-core'
);
const url = await startDevToolsServer(config);
if (shouldLaunchBrowser()) {
try {
await openBrowserSecurely(url);
} catch (e) {
setShowErrorDetails((prev) => !prev);
debugLogger.warn('Failed to open browser securely:', e);
}
} else {
setShowErrorDetails((prev) => !prev);
}
} catch (e) {
setShowErrorDetails(true);
debugLogger.error('Failed to start DevTools server:', e);
}
const { toggleDevToolsPanel } = await import(
'../utils/devtoolsService.js'
);
await toggleDevToolsPanel(
config,
showErrorDetails,
() => setShowErrorDetails((prev) => !prev),
() => setShowErrorDetails(true),
);
})();
} else {
setShowErrorDetails((prev) => !prev);
@@ -1668,7 +1651,6 @@ Logging in with Google... Restarting Gemini CLI to continue.
settings.merged.general.debugKeystrokeLogging,
refreshStatic,
setCopyModeEnabled,
copyModeEnabled,
isAlternateBuffer,
backgroundCurrentShell,
toggleBackgroundShell,
@@ -1679,11 +1661,26 @@ Logging in with Google... Restarting Gemini CLI to continue.
tabFocusTimeoutRef,
showTransientMessage,
settings.merged.general.devtools,
showErrorDetails,
],
);
useKeypress(handleGlobalKeypress, { isActive: true, priority: true });
useKeypress(
() => {
setCopyModeEnabled(false);
enableMouseEvents();
return true;
},
{
isActive: copyModeEnabled,
// We need to receive keypresses first so they do not bubble to other
// handlers.
priority: KeypressPriority.Critical,
},
);
useEffect(() => {
// Respect hideWindowTitle settings
if (settings.merged.ui.hideWindowTitle) return;
@@ -110,6 +110,7 @@ describe('ApiAuthDialog', () => {
keypressHandler({
name: keyName,
shift: false,
alt: false,
ctrl: false,
cmd: false,
sequence,
@@ -4,7 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { act } from 'react';
import { renderWithProviders } from '../../test-utils/render.js';
import { waitFor } from '../../test-utils/async.js';
@@ -21,6 +21,14 @@ const writeKey = (stdin: { write: (data: string) => void }, key: string) => {
};
describe('AskUserDialog', () => {
// Ensure keystrokes appear spaced in time to avoid bufferFastReturn
// converting Enter into Shift+Enter during synchronous test execution.
let mockTime: number;
beforeEach(() => {
mockTime = 0;
vi.spyOn(Date, 'now').mockImplementation(() => (mockTime += 50));
});
afterEach(() => {
vi.restoreAllMocks();
});
@@ -158,6 +166,57 @@ describe('AskUserDialog', () => {
});
});
it('supports multi-line input for "Other" option in choice questions', async () => {
const authQuestionWithOther: Question[] = [
{
question: 'Which authentication method?',
header: 'Auth',
options: [{ label: 'OAuth 2.0', description: '' }],
multiSelect: false,
},
];
const onSubmit = vi.fn();
const { stdin, lastFrame } = renderWithProviders(
<AskUserDialog
questions={authQuestionWithOther}
onSubmit={onSubmit}
onCancel={vi.fn()}
width={120}
/>,
{ width: 120 },
);
// Navigate to "Other" option
writeKey(stdin, '\x1b[B'); // Down to "Other"
// Type first line
for (const char of 'Line 1') {
writeKey(stdin, char);
}
// Insert newline using \ + Enter (handled by bufferBackslashEnter)
writeKey(stdin, '\\');
writeKey(stdin, '\r');
// Type second line
for (const char of 'Line 2') {
writeKey(stdin, char);
}
await waitFor(() => {
expect(lastFrame()).toContain('Line 1');
expect(lastFrame()).toContain('Line 2');
});
// Press Enter to submit
writeKey(stdin, '\r');
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith({ '0': 'Line 1\nLine 2' });
});
});
describe.each([
{ useAlternateBuffer: true, expectedArrows: false },
{ useAlternateBuffer: false, expectedArrows: true },
@@ -763,7 +822,7 @@ describe('AskUserDialog', () => {
});
});
it('does not submit empty text', () => {
it('submits empty text as unanswered', async () => {
const textQuestion: Question[] = [
{
question: 'Enter the class name:',
@@ -785,8 +844,9 @@ describe('AskUserDialog', () => {
writeKey(stdin, '\r');
// onSubmit should not be called for empty text
expect(onSubmit).not.toHaveBeenCalled();
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith({});
});
});
it('clears text on Ctrl+C', async () => {
@@ -93,6 +93,7 @@ type AskUserDialogAction =
payload: {
index: number;
answer: string;
submit?: boolean;
};
}
| { type: 'SET_EDITING_CUSTOM'; payload: { isEditing: boolean } }
@@ -114,7 +115,7 @@ function askUserDialogReducerLogic(
switch (action.type) {
case 'SET_ANSWER': {
const { index, answer } = action.payload;
const { index, answer, submit } = action.payload;
const hasAnswer =
answer !== undefined && answer !== null && answer.trim() !== '';
const newAnswers = { ...state.answers };
@@ -128,6 +129,7 @@ function askUserDialogReducerLogic(
return {
...state,
answers: newAnswers,
submitted: submit ? true : state.submitted,
};
}
case 'SET_EDITING_CUSTOM': {
@@ -283,8 +285,8 @@ const TextQuestionView: React.FC<TextQuestionViewProps> = ({
const buffer = useTextBuffer({
initialText: initialAnswer,
viewport: { width: Math.max(1, bufferWidth), height: 1 },
singleLine: true,
viewport: { width: Math.max(1, bufferWidth), height: 3 },
singleLine: false,
});
const { text: textValue } = buffer;
@@ -317,9 +319,7 @@ const TextQuestionView: React.FC<TextQuestionViewProps> = ({
const handleSubmit = useCallback(
(val: string) => {
if (val.trim()) {
onAnswer(val.trim());
}
onAnswer(val.trim());
},
[onAnswer],
);
@@ -561,8 +561,8 @@ const ChoiceQuestionView: React.FC<ChoiceQuestionViewProps> = ({
const customBuffer = useTextBuffer({
initialText: initialCustomText,
viewport: { width: Math.max(1, bufferWidth), height: 1 },
singleLine: true,
viewport: { width: Math.max(1, bufferWidth), height: 3 },
singleLine: false,
});
const customOptionText = customBuffer.text;
@@ -850,9 +850,22 @@ const ChoiceQuestionView: React.FC<ChoiceQuestionViewProps> = ({
buffer={customBuffer}
placeholder={placeholder}
focus={context.isSelected}
onSubmit={() => handleSelect(optionItem)}
onSubmit={(val) => {
if (question.multiSelect) {
const fullAnswer = buildAnswerString(
selectedIndices,
true,
val,
);
if (fullAnswer) {
onAnswer(fullAnswer);
}
} else if (val.trim()) {
onAnswer(val.trim());
}
}}
/>
{isChecked && !question.multiSelect && (
{isChecked && !question.multiSelect && !context.isSelected && (
<Text color={theme.status.success}> </Text>
)}
</Box>
@@ -1012,21 +1025,27 @@ export const AskUserDialog: React.FC<AskUserDialogProps> = ({
(answer: string) => {
if (submitted) return;
dispatch({
type: 'SET_ANSWER',
payload: {
index: currentQuestionIndex,
answer,
},
});
if (questions.length > 1) {
dispatch({
type: 'SET_ANSWER',
payload: {
index: currentQuestionIndex,
answer,
},
});
goToNextTab();
} else {
dispatch({ type: 'SUBMIT' });
dispatch({
type: 'SET_ANSWER',
payload: {
index: currentQuestionIndex,
answer,
submit: true,
},
});
}
},
[currentQuestionIndex, questions.length, submitted, goToNextTab],
[currentQuestionIndex, questions, submitted, goToNextTab],
);
const handleReviewSubmit = useCallback(() => {
@@ -650,6 +650,19 @@ describe('Composer', () => {
});
describe('Shortcuts Hint', () => {
it('hides shortcuts hint when showShortcutsHint setting is false', () => {
const uiState = createMockUIState();
const settings = createMockSettings({
ui: {
showShortcutsHint: false,
},
});
const { lastFrame } = renderComposer(uiState, settings);
expect(lastFrame()).not.toContain('ShortcutsHint');
});
it('hides shortcuts hint when a action is required (e.g. dialog is open)', () => {
const uiState = createMockUIState({
customDialog: (
+2 -1
View File
@@ -133,7 +133,8 @@ export const Composer = ({ isFocused = true }: { isFocused?: boolean }) => {
flexDirection="column"
alignItems={isNarrow ? 'flex-start' : 'flex-end'}
>
{!hasPendingActionRequired && <ShortcutsHint />}
{settings.merged.ui.showShortcutsHint &&
!hasPendingActionRequired && <ShortcutsHint />}
</Box>
</Box>
{uiState.shortcutsHelpVisible && <ShortcutsHelp />}
@@ -47,6 +47,13 @@ const writeKey = (stdin: { write: (data: string) => void }, key: string) => {
act(() => {
stdin.write(key);
});
// Advance timers to simulate time passing between keystrokes.
// This avoids bufferFastReturn converting Enter to Shift+Enter.
if (vi.isFakeTimers()) {
act(() => {
vi.advanceTimersByTime(50);
});
}
};
describe('ExitPlanModeDialog', () => {
@@ -234,7 +241,6 @@ Implement a comprehensive authentication system with multiple providers.
// Navigate to feedback option
writeKey(stdin, '\x1b[B'); // Down arrow
writeKey(stdin, '\x1b[B'); // Down arrow
writeKey(stdin, '\r'); // Select to focus input
// Type feedback
for (const char of 'Add tests') {
@@ -512,7 +518,6 @@ Implement a comprehensive authentication system with multiple providers.
// Navigate to feedback option and start typing
writeKey(stdin, '\x1b[B'); // Down arrow
writeKey(stdin, '\x1b[B'); // Down arrow
writeKey(stdin, '\r'); // Select to focus input
// Type some feedback
for (const char of 'test') {
@@ -4296,6 +4296,30 @@ describe('InputPrompt', () => {
});
describe('shortcuts help visibility', () => {
it('opens shortcuts help with ? on empty prompt even when showShortcutsHint is false', async () => {
const setShortcutsHelpVisible = vi.fn();
const settings = createMockSettings({
ui: { showShortcutsHint: false },
});
const { stdin, unmount } = renderWithProviders(
<InputPrompt {...props} />,
{
settings,
uiActions: { setShortcutsHelpVisible },
},
);
await act(async () => {
stdin.write('?');
});
await waitFor(() => {
expect(setShortcutsHelpVisible).toHaveBeenCalledWith(true);
});
unmount();
});
it.each([
{
name: 'terminal paste event occurs',
@@ -54,14 +54,3 @@ exports[`<BackgroundShellDisplay /> > scrolls to active shell when list opens 1`
│ ● 2. tail -f log.txt (PID: 1002) │
└──────────────────────────────────────────────────────────────────────────────────────────────────┘"
`;
exports[`<BackgroundShellDisplay /> > selects the current process and closes the list when Ctrl+L is pressed in list view 1`] = `
"┌──────────────────────────────────────────────────────────────────────────────────────────────────┐
│ 1: npm sta... (PID: 1001) (Focused) Close (Ctrl+B) | Kill (Ctrl+K) | List (Ctrl+L) │
│ │
│ Select Process (Enter to select, Ctrl+K to kill, Esc to cancel): │
│ │
│ ● 1. npm start (PID: 1001) │
│ 2. tail -f log.txt (PID: 1002) │
└──────────────────────────────────────────────────────────────────────────────────────────────────┘"
`;
@@ -21,7 +21,7 @@ Files to Modify
Approves plan and allows tools to run automatically
2. Yes, manually accept edits
Approves plan but requires confirmation for each tool
● 3. Type your feedback...
● 3. Type your feedback...
Enter to submit · Esc to cancel"
`;
@@ -47,7 +47,7 @@ Files to Modify
Approves plan and allows tools to run automatically
2. Yes, manually accept edits
Approves plan but requires confirmation for each tool
● 3. Add tests
● 3. Add tests
Enter to submit · Esc to cancel"
`;
@@ -127,7 +127,7 @@ Files to Modify
Approves plan and allows tools to run automatically
2. Yes, manually accept edits
Approves plan but requires confirmation for each tool
● 3. Type your feedback...
● 3. Type your feedback...
Enter to submit · Esc to cancel"
`;
@@ -153,7 +153,7 @@ Files to Modify
Approves plan and allows tools to run automatically
2. Yes, manually accept edits
Approves plan but requires confirmation for each tool
● 3. Add tests
● 3. Add tests
Enter to submit · Esc to cancel"
`;
@@ -13,6 +13,7 @@ import chalk from 'chalk';
import { theme } from '../../semantic-colors.js';
import type { TextBuffer } from './text-buffer.js';
import { cpSlice, cpIndexToOffset } from '../../utils/textUtils.js';
import { keyMatchers, Command } from '../../keyMatchers.js';
export interface TextInputProps {
buffer: TextBuffer;
@@ -45,7 +46,7 @@ export function TextInput({
return true;
}
if (key.name === 'return' && onSubmit) {
if (keyMatchers[Command.SUBMIT](key) && onSubmit) {
onSubmit(text);
return true;
}
@@ -6,6 +6,7 @@
import { debugLogger, type Config } from '@google/gemini-cli-core';
import { useStdin } from 'ink';
import { MultiMap } from 'mnemonist';
import type React from 'react';
import {
createContext,
@@ -26,6 +27,13 @@ export const ESC_TIMEOUT = 50;
export const PASTE_TIMEOUT = 30_000;
export const FAST_RETURN_TIMEOUT = 30;
export enum KeypressPriority {
Low = -100,
Normal = 0,
High = 100,
Critical = 200,
}
// Parse the key itself
const KEY_INFO_MAP: Record<
string,
@@ -645,7 +653,10 @@ export interface Key {
export type KeypressHandler = (key: Key) => boolean | void;
interface KeypressContextValue {
subscribe: (handler: KeypressHandler, priority?: boolean) => void;
subscribe: (
handler: KeypressHandler,
priority?: KeypressPriority | boolean,
) => void;
unsubscribe: (handler: KeypressHandler) => void;
}
@@ -674,44 +685,75 @@ export function KeypressProvider({
}) {
const { stdin, setRawMode } = useStdin();
const prioritySubscribers = useRef<Set<KeypressHandler>>(new Set()).current;
const normalSubscribers = useRef<Set<KeypressHandler>>(new Set()).current;
const subscribersToPriority = useRef<Map<KeypressHandler, number>>(
new Map(),
).current;
const subscribers = useRef(
new MultiMap<number, KeypressHandler>(Set),
).current;
const sortedPriorities = useRef<number[]>([]);
const subscribe = useCallback(
(handler: KeypressHandler, priority = false) => {
const set = priority ? prioritySubscribers : normalSubscribers;
set.add(handler);
(
handler: KeypressHandler,
priority: KeypressPriority | boolean = KeypressPriority.Normal,
) => {
const p =
typeof priority === 'boolean'
? priority
? KeypressPriority.High
: KeypressPriority.Normal
: priority;
subscribersToPriority.set(handler, p);
const hadPriority = subscribers.has(p);
subscribers.set(p, handler);
if (!hadPriority) {
// Cache sorted priorities only when a new priority level is added
sortedPriorities.current = Array.from(subscribers.keys()).sort(
(a, b) => b - a,
);
}
},
[prioritySubscribers, normalSubscribers],
[subscribers, subscribersToPriority],
);
const unsubscribe = useCallback(
(handler: KeypressHandler) => {
prioritySubscribers.delete(handler);
normalSubscribers.delete(handler);
const p = subscribersToPriority.get(handler);
if (p !== undefined) {
subscribers.remove(p, handler);
subscribersToPriority.delete(handler);
if (!subscribers.has(p)) {
// Cache sorted priorities only when a priority level is completely removed
sortedPriorities.current = Array.from(subscribers.keys()).sort(
(a, b) => b - a,
);
}
}
},
[prioritySubscribers, normalSubscribers],
[subscribers, subscribersToPriority],
);
const broadcast = useCallback(
(key: Key) => {
// Process priority subscribers first, in reverse order (stack behavior: last subscribed is first to handle)
const priorityHandlers = Array.from(prioritySubscribers).reverse();
for (const handler of priorityHandlers) {
if (handler(key) === true) {
return;
}
}
// Use cached sorted priorities to avoid sorting on every keypress
for (const p of sortedPriorities.current) {
const set = subscribers.get(p);
if (!set) continue;
// Then process normal subscribers, also in reverse order
const normalHandlers = Array.from(normalSubscribers).reverse();
for (const handler of normalHandlers) {
if (handler(key) === true) {
return;
// Within a priority level, use stack behavior (last subscribed is first to handle)
const handlers = Array.from(set).reverse();
for (const handler of handlers) {
if (handler(key) === true) {
return;
}
}
}
},
[prioritySubscribers, normalSubscribers],
[subscribers],
);
useEffect(() => {
@@ -31,6 +31,7 @@ function consoleMessagesReducer(
state: ConsoleMessageItem[],
action: Action,
): ConsoleMessageItem[] {
const MAX_CONSOLE_MESSAGES = 1000;
switch (action.type) {
case 'ADD_MESSAGES': {
const newMessages = [...state];
@@ -51,6 +52,12 @@ function consoleMessagesReducer(
newMessages.push({ ...queuedMessage, count: 1 });
}
}
// Limit the number of messages to prevent memory issues
if (newMessages.length > MAX_CONSOLE_MESSAGES) {
return newMessages.slice(newMessages.length - MAX_CONSOLE_MESSAGES);
}
return newMessages;
}
case 'CLEAR':
@@ -91,9 +98,17 @@ export function useConsoleMessages(): UseConsoleMessagesReturn {
useEffect(() => {
const handleConsoleLog = (payload: ConsoleLogPayload) => {
let content = payload.content;
const MAX_CONSOLE_MSG_LENGTH = 10000;
if (content.length > MAX_CONSOLE_MSG_LENGTH) {
content =
content.slice(0, MAX_CONSOLE_MSG_LENGTH) +
`... [Truncated ${content.length - MAX_CONSOLE_MSG_LENGTH} characters]`;
}
handleNewMessage({
type: payload.type,
content: payload.content,
content,
count: 1,
});
};
@@ -102,10 +117,18 @@ export function useConsoleMessages(): UseConsoleMessagesReturn {
isStderr: boolean;
chunk: Uint8Array | string;
}) => {
const content =
let content =
typeof payload.chunk === 'string'
? payload.chunk
: new TextDecoder().decode(payload.chunk);
const MAX_OUTPUT_CHUNK_LENGTH = 10000;
if (content.length > MAX_OUTPUT_CHUNK_LENGTH) {
content =
content.slice(0, MAX_OUTPUT_CHUNK_LENGTH) +
`... [Truncated ${content.length - MAX_OUTPUT_CHUNK_LENGTH} characters]`;
}
// It would be nice if we could show stderr as 'warn' but unfortunately
// we log non warning info to stderr before the app starts so that would
// be misleading.
+11 -4
View File
@@ -5,8 +5,12 @@
*/
import { useEffect } from 'react';
import type { KeypressHandler, Key } from '../contexts/KeypressContext.js';
import { useKeypressContext } from '../contexts/KeypressContext.js';
import {
useKeypressContext,
type KeypressHandler,
type Key,
type KeypressPriority,
} from '../contexts/KeypressContext.js';
export type { Key };
@@ -16,11 +20,14 @@ export type { Key };
* @param onKeypress - The callback function to execute on each keypress.
* @param options - Options to control the hook's behavior.
* @param options.isActive - Whether the hook should be actively listening for input.
* @param options.priority - Whether the hook should have priority over normal subscribers.
* @param options.priority - Priority level (integer or KeypressPriority enum) or boolean for backward compatibility.
*/
export function useKeypress(
onKeypress: KeypressHandler,
{ isActive, priority }: { isActive: boolean; priority?: boolean },
{
isActive,
priority,
}: { isActive: boolean; priority?: KeypressPriority | boolean },
) {
const { subscribe, unsubscribe } = useKeypressContext();
@@ -314,4 +314,35 @@ describe('TableRenderer', () => {
});
expect(output).toMatchSnapshot();
});
it.each([
{
name: 'renders correctly when headers are empty but rows have data',
headers: [] as string[],
rows: [['Data 1', 'Data 2']],
expected: ['Data 1', 'Data 2'],
},
{
name: 'renders correctly when there are more headers than columns in rows',
headers: ['Header 1', 'Header 2', 'Header 3'],
rows: [['Data 1', 'Data 2']],
expected: ['Header 1', 'Header 2', 'Header 3', 'Data 1', 'Data 2'],
},
])('$name', ({ headers, rows, expected }) => {
const terminalWidth = 50;
const { lastFrame } = renderWithProviders(
<TableRenderer
headers={headers}
rows={rows}
terminalWidth={terminalWidth}
/>,
);
const output = lastFrame();
expected.forEach((text) => {
expect(output).toContain(text);
});
expect(output).toMatchSnapshot();
});
});
+44 -28
View File
@@ -28,8 +28,7 @@ const MIN_COLUMN_WIDTH = 5;
const COLUMN_PADDING = 2;
const TABLE_MARGIN = 2;
const calculateWidths = (text: string) => {
const styledChars = toStyledCharacters(text);
const calculateWidths = (styledChars: StyledChar[]) => {
const contentWidth = styledCharsWidth(styledChars);
const words: StyledChar[][] = wordBreakStyledChars(styledChars);
@@ -60,31 +59,48 @@ export const TableRenderer: React.FC<TableRendererProps> = ({
[headers],
);
const styledHeaders = useMemo(
() => cleanedHeaders.map((header) => toStyledCharacters(header)),
[cleanedHeaders],
);
const styledRows = useMemo(
() => rows.map((row) => row.map((cell) => toStyledCharacters(cell))),
[rows],
);
const { wrappedHeaders, wrappedRows, adjustedWidths } = useMemo(() => {
const numColumns = styledRows.reduce(
(max, row) => Math.max(max, row.length),
styledHeaders.length,
);
// --- Define Constraints per Column ---
const constraints = cleanedHeaders.map((header, colIndex) => {
let { contentWidth: maxContentWidth, maxWordWidth } =
calculateWidths(header);
const constraints = Array.from({ length: numColumns }).map(
(_, colIndex) => {
const headerStyledChars = styledHeaders[colIndex] || [];
let { contentWidth: maxContentWidth, maxWordWidth } =
calculateWidths(headerStyledChars);
rows.forEach((row) => {
const cell = row[colIndex] || '';
const { contentWidth: cellWidth, maxWordWidth: cellWordWidth } =
calculateWidths(cell);
styledRows.forEach((row) => {
const cellStyledChars = row[colIndex] || [];
const { contentWidth: cellWidth, maxWordWidth: cellWordWidth } =
calculateWidths(cellStyledChars);
maxContentWidth = Math.max(maxContentWidth, cellWidth);
maxWordWidth = Math.max(maxWordWidth, cellWordWidth);
});
maxContentWidth = Math.max(maxContentWidth, cellWidth);
maxWordWidth = Math.max(maxWordWidth, cellWordWidth);
});
const minWidth = maxWordWidth;
const maxWidth = Math.max(minWidth, maxContentWidth);
const minWidth = maxWordWidth;
const maxWidth = Math.max(minWidth, maxContentWidth);
return { minWidth, maxWidth };
});
return { minWidth, maxWidth };
},
);
// --- Calculate Available Space ---
// Fixed overhead: borders (n+1) + padding (2n)
const fixedOverhead =
cleanedHeaders.length + 1 + cleanedHeaders.length * COLUMN_PADDING;
const fixedOverhead = numColumns + 1 + numColumns * COLUMN_PADDING;
const availableWidth = Math.max(
0,
terminalWidth - fixedOverhead - TABLE_MARGIN,
@@ -136,17 +152,18 @@ export const TableRenderer: React.FC<TableRendererProps> = ({
}
// --- Pre-wrap and Optimize Widths ---
const actualColumnWidths = new Array(cleanedHeaders.length).fill(0);
const actualColumnWidths = new Array(numColumns).fill(0);
const wrapAndProcessRow = (row: string[]) => {
const wrapAndProcessRow = (row: StyledChar[][]) => {
const rowResult: ProcessedLine[][] = [];
row.forEach((cell, colIndex) => {
// Ensure we iterate up to numColumns, filling with empty cells if needed
for (let colIndex = 0; colIndex < numColumns; colIndex++) {
const cellStyledChars = row[colIndex] || [];
const allocatedWidth = finalContentWidths[colIndex];
const contentWidth = Math.max(1, allocatedWidth);
const contentStyledChars = toStyledCharacters(cell);
const wrappedStyledLines = wrapStyledChars(
contentStyledChars,
cellStyledChars,
contentWidth,
);
@@ -161,19 +178,18 @@ export const TableRenderer: React.FC<TableRendererProps> = ({
width: styledCharsWidth(line),
}));
rowResult.push(lines);
});
}
return rowResult;
};
const wrappedHeaders = wrapAndProcessRow(cleanedHeaders);
const wrappedRows = rows.map((row) => wrapAndProcessRow(row));
const wrappedHeaders = wrapAndProcessRow(styledHeaders);
const wrappedRows = styledRows.map((row) => wrapAndProcessRow(row));
// Use the TIGHTEST widths that fit the wrapped content + padding
const adjustedWidths = actualColumnWidths.map((w) => w + COLUMN_PADDING);
return { wrappedHeaders, wrappedRows, adjustedWidths };
}, [cleanedHeaders, rows, terminalWidth]);
}, [styledHeaders, styledRows, terminalWidth]);
// Helper function to render a cell with proper width
const renderCell = (
content: ProcessedLine,
@@ -44,6 +44,26 @@ exports[`TableRenderer > 'renders a table with only emojis and …' 1`] = `
"
`;
exports[`TableRenderer > 'renders correctly when headers are em…' 1`] = `
"
┌────────┬────────┐
│ │ │
├────────┼────────┤
│ Data 1 │ Data 2 │
└────────┴────────┘
"
`;
exports[`TableRenderer > 'renders correctly when there are more…' 1`] = `
"
┌──────────┬──────────┬──────────┐
│ Header 1 │ Header 2 │ Header 3 │
├──────────┼──────────┼──────────┤
│ Data 1 │ Data 2 │ │
└──────────┴──────────┴──────────┘
"
`;
exports[`TableRenderer > handles wrapped bold headers without showing markers 1`] = `
"
┌─────────────┬───────┬─────────┐
@@ -70,12 +70,20 @@ vi.mock('./activityLogger.js', () => ({
},
}));
const mockShouldLaunchBrowser = vi.hoisted(() => vi.fn(() => true));
const mockOpenBrowserSecurely = vi.hoisted(() =>
vi.fn(() => Promise.resolve()),
);
vi.mock('@google/gemini-cli-core', () => ({
debugLogger: {
log: vi.fn(),
debug: vi.fn(),
error: vi.fn(),
warn: vi.fn(),
},
shouldLaunchBrowser: mockShouldLaunchBrowser,
openBrowserSecurely: mockOpenBrowserSecurely,
}));
vi.mock('ws', () => ({
@@ -92,6 +100,7 @@ vi.mock('gemini-cli-devtools', () => ({
import {
setupInitialActivityLogger,
startDevToolsServer,
toggleDevToolsPanel,
resetForTesting,
} from './devtoolsService.js';
@@ -426,4 +435,98 @@ describe('devtoolsService', () => {
expect(mockAddNetworkTransport).toHaveBeenCalledTimes(3);
});
});
describe('toggleDevToolsPanel', () => {
it('calls toggle (to close) when already open', async () => {
const config = createMockConfig();
const toggle = vi.fn();
const setOpen = vi.fn();
const promise = toggleDevToolsPanel(config, true, toggle, setOpen);
await promise;
expect(toggle).toHaveBeenCalledTimes(1);
expect(setOpen).not.toHaveBeenCalled();
});
it('does NOT call toggle or setOpen when browser opens successfully', async () => {
const config = createMockConfig();
const toggle = vi.fn();
const setOpen = vi.fn();
mockShouldLaunchBrowser.mockReturnValue(true);
mockOpenBrowserSecurely.mockResolvedValue(undefined);
mockDevToolsInstance.start.mockResolvedValue('http://127.0.0.1:25417');
mockDevToolsInstance.getPort.mockReturnValue(25417);
const promise = toggleDevToolsPanel(config, false, toggle, setOpen);
await vi.waitFor(() => expect(MockWebSocket.instances.length).toBe(1));
MockWebSocket.instances[0].simulateError();
await promise;
expect(toggle).not.toHaveBeenCalled();
expect(setOpen).not.toHaveBeenCalled();
});
it('calls setOpen when browser fails to open', async () => {
const config = createMockConfig();
const toggle = vi.fn();
const setOpen = vi.fn();
mockShouldLaunchBrowser.mockReturnValue(true);
mockOpenBrowserSecurely.mockRejectedValue(new Error('no browser'));
mockDevToolsInstance.start.mockResolvedValue('http://127.0.0.1:25417');
mockDevToolsInstance.getPort.mockReturnValue(25417);
const promise = toggleDevToolsPanel(config, false, toggle, setOpen);
await vi.waitFor(() => expect(MockWebSocket.instances.length).toBe(1));
MockWebSocket.instances[0].simulateError();
await promise;
expect(toggle).not.toHaveBeenCalled();
expect(setOpen).toHaveBeenCalledTimes(1);
});
it('calls setOpen when shouldLaunchBrowser returns false', async () => {
const config = createMockConfig();
const toggle = vi.fn();
const setOpen = vi.fn();
mockShouldLaunchBrowser.mockReturnValue(false);
mockDevToolsInstance.start.mockResolvedValue('http://127.0.0.1:25417');
mockDevToolsInstance.getPort.mockReturnValue(25417);
const promise = toggleDevToolsPanel(config, false, toggle, setOpen);
await vi.waitFor(() => expect(MockWebSocket.instances.length).toBe(1));
MockWebSocket.instances[0].simulateError();
await promise;
expect(toggle).not.toHaveBeenCalled();
expect(setOpen).toHaveBeenCalledTimes(1);
});
it('calls setOpen when DevTools server fails to start', async () => {
const config = createMockConfig();
const toggle = vi.fn();
const setOpen = vi.fn();
mockDevToolsInstance.start.mockRejectedValue(new Error('fail'));
const promise = toggleDevToolsPanel(config, false, toggle, setOpen);
await vi.waitFor(() => expect(MockWebSocket.instances.length).toBe(1));
MockWebSocket.instances[0].simulateError();
await promise;
expect(toggle).not.toHaveBeenCalled();
expect(setOpen).toHaveBeenCalledTimes(1);
});
});
});
+42
View File
@@ -210,6 +210,48 @@ async function startDevToolsServerImpl(config: Config): Promise<string> {
return url;
}
/**
* Handles the F12 key toggle for the DevTools panel.
* Starts the DevTools server, attempts to open the browser.
* If the panel is already open, it closes it.
* If the panel is closed:
* - Attempts to open the browser.
* - If browser opening is successful, the panel remains closed.
* - If browser opening fails or is not possible, the panel is opened.
*/
export async function toggleDevToolsPanel(
config: Config,
isOpen: boolean,
toggle: () => void,
setOpen: () => void,
): Promise<void> {
if (isOpen) {
toggle();
return;
}
try {
const { openBrowserSecurely, shouldLaunchBrowser } = await import(
'@google/gemini-cli-core'
);
const url = await startDevToolsServer(config);
if (shouldLaunchBrowser()) {
try {
await openBrowserSecurely(url);
// Browser opened successfully, don't open drawer.
return;
} catch (e) {
debugLogger.warn('Failed to open browser securely:', e);
}
}
// If we can't launch browser or it failed, open drawer.
setOpen();
} catch (e) {
setOpen();
debugLogger.error('Failed to start DevTools server:', e);
}
}
/** Reset module-level state — test only. */
export function resetForTesting() {
promotionAttempts = 0;
+19 -1
View File
@@ -477,6 +477,8 @@ export interface ConfigParameters {
experimentalJitContext?: boolean;
toolOutputMasking?: Partial<ToolOutputMaskingConfig>;
disableLLMCorrection?: boolean;
sessionLearnings?: boolean;
sessionLearningsOutputPath?: string;
plan?: boolean;
onModelChange?: (model: string) => void;
mcpEnabled?: boolean;
@@ -662,6 +664,8 @@ export class Config {
private readonly experimentalJitContext: boolean;
private readonly disableLLMCorrection: boolean;
private readonly sessionLearnings: boolean;
private readonly sessionLearningsOutputPath: string | undefined;
private readonly planEnabled: boolean;
private contextManager?: ContextManager;
private terminalBackground: string | undefined = undefined;
@@ -750,6 +754,8 @@ export class Config {
this.enableAgents = params.enableAgents ?? false;
this.agents = params.agents ?? {};
this.disableLLMCorrection = params.disableLLMCorrection ?? true;
this.sessionLearnings = params.sessionLearnings ?? false;
this.sessionLearningsOutputPath = params.sessionLearningsOutputPath;
this.planEnabled = params.plan ?? false;
this.enableEventDrivenScheduler = params.enableEventDrivenScheduler ?? true;
this.skillsSupport = params.skillsSupport ?? true;
@@ -758,7 +764,7 @@ export class Config {
this.modelAvailabilityService = new ModelAvailabilityService();
this.experimentalJitContext = params.experimentalJitContext ?? false;
this.toolOutputMasking = {
enabled: params.toolOutputMasking?.enabled ?? false,
enabled: params.toolOutputMasking?.enabled ?? true,
toolProtectionThreshold:
params.toolOutputMasking?.toolProtectionThreshold ??
DEFAULT_TOOL_PROTECTION_THRESHOLD,
@@ -905,6 +911,10 @@ export class Config {
);
}
isInitialized(): boolean {
return this.initialized;
}
/**
* Must only be called once, throws if called again.
*/
@@ -1949,6 +1959,14 @@ export class Config {
return this.disableLLMCorrection;
}
isSessionLearningsEnabled(): boolean {
return this.sessionLearnings;
}
getSessionLearningsOutputPath(): string | undefined {
return this.sessionLearningsOutputPath;
}
isPlanEnabled(): boolean {
return this.planEnabled;
}
@@ -18,6 +18,7 @@ import { LoggingContentGenerator } from './loggingContentGenerator.js';
import { loadApiKey } from './apiKeyCredentialStorage.js';
import { FakeContentGenerator } from './fakeContentGenerator.js';
import { RecordingContentGenerator } from './recordingContentGenerator.js';
import { resetVersionCache } from '../utils/version.js';
vi.mock('../code_assist/codeAssist.js');
vi.mock('@google/genai');
@@ -35,6 +36,7 @@ const mockConfig = {
describe('createContentGenerator', () => {
beforeEach(() => {
resetVersionCache();
vi.clearAllMocks();
});
@@ -74,6 +74,7 @@ describe('HookRegistry', () => {
getDisabledHooks: vi.fn().mockReturnValue([]),
isTrustedFolder: vi.fn().mockReturnValue(true),
getProjectRoot: vi.fn().mockReturnValue('/project'),
isSessionLearningsEnabled: vi.fn().mockReturnValue(false),
} as unknown as Config;
hookRegistry = new HookRegistry(mockConfig);
@@ -279,6 +280,21 @@ describe('HookRegistry', () => {
hookRegistry.getHooksForEvent(HookEventName.BeforeTool),
).toHaveLength(0);
});
it('should register builtin session-learnings hook when enabled', async () => {
vi.mocked(mockConfig.isSessionLearningsEnabled).mockReturnValue(true);
await hookRegistry.initialize();
const hooks = hookRegistry.getHooksForEvent(HookEventName.SessionEnd);
expect(hooks).toHaveLength(1);
expect(hooks[0].config.type).toBe(HookType.Builtin);
expect((hooks[0].config as BuiltinHookConfig).builtin_id).toBe(
'session-learnings',
);
expect(hooks[0].source).toBe(ConfigSource.System);
});
});
describe('getHooksForEvent', () => {
+29 -1
View File
@@ -6,7 +6,12 @@
import type { Config } from '../config/config.js';
import type { HookDefinition, HookConfig } from './types.js';
import { HookEventName, ConfigSource, HOOKS_CONFIG_FIELDS } from './types.js';
import {
HookEventName,
ConfigSource,
HOOKS_CONFIG_FIELDS,
HookType,
} from './types.js';
import { debugLogger } from '../utils/debugLogger.js';
import { TrustedHooksManager } from './trustedHooks.js';
import { coreEvents } from '../utils/events.js';
@@ -137,6 +142,8 @@ please review the project settings (.gemini/settings.json) and remove them.`;
this.checkProjectHooksTrust();
}
this.registerBuiltinHooks();
// Get hooks from the main config (this comes from the merged settings)
const configHooks = this.config.getHooks();
if (configHooks) {
@@ -161,6 +168,27 @@ please review the project settings (.gemini/settings.json) and remove them.`;
}
}
/**
* Register system-level builtin hooks
*/
private registerBuiltinHooks(): void {
if (this.config.isSessionLearningsEnabled()) {
debugLogger.debug('Registering builtin session-learnings hook');
this.entries.push({
config: {
type: HookType.Builtin,
builtin_id: 'session-learnings',
name: 'session-learnings',
description: 'Automatically generate session learning summaries',
source: ConfigSource.System,
},
source: ConfigSource.System,
eventName: HookEventName.SessionEnd,
enabled: true,
});
}
}
/**
* Process hooks configuration and add entries
*/
@@ -0,0 +1,109 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HookRunner } from './hookRunner.js';
import {
HookEventName,
HookType,
SessionEndReason,
type BuiltinHookConfig,
type SessionEndInput,
} from './types.js';
import type { Config } from '../config/config.js';
describe('HookRunner (Builtin Hooks)', () => {
let hookRunner: HookRunner;
let mockConfig: Config;
beforeEach(() => {
vi.resetAllMocks();
mockConfig = {
sanitizationConfig: {},
isSessionLearningsEnabled: vi.fn().mockReturnValue(true),
getGeminiClient: vi.fn().mockReturnValue({
getChatRecordingService: vi.fn().mockReturnValue({
getConversation: vi.fn().mockReturnValue({ messages: [] }),
getConversationFilePath: vi
.fn()
.mockReturnValue('/tmp/transcript.json'),
}),
}),
getContentGenerator: vi.fn(),
getActiveModel: vi.fn().mockReturnValue('gemini-pro'),
getWorkingDir: vi.fn().mockReturnValue('/work'),
} as unknown as Config;
hookRunner = new HookRunner(mockConfig);
});
it('should execute session-learnings builtin hook on SessionEnd', async () => {
const hookConfig: BuiltinHookConfig = {
type: HookType.Builtin,
builtin_id: 'session-learnings',
name: 'test-learnings',
};
const input: SessionEndInput = {
session_id: 'test-session',
transcript_path: '/tmp/transcript.json',
cwd: '/work',
hook_event_name: HookEventName.SessionEnd,
timestamp: new Date().toISOString(),
reason: SessionEndReason.Exit,
};
// Spy on the service
const serviceSpy = vi
.spyOn(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(hookRunner as any).sessionLearningsService,
'generateAndSaveLearnings',
)
.mockResolvedValue(undefined);
const result = await hookRunner.executeHook(
hookConfig,
HookEventName.SessionEnd,
input,
);
expect(result.success).toBe(true);
expect(serviceSpy).toHaveBeenCalled();
});
it('should not execute session-learnings if reason is not exit/logout', async () => {
const hookConfig: BuiltinHookConfig = {
type: HookType.Builtin,
builtin_id: 'session-learnings',
};
const input: SessionEndInput = {
session_id: 'test-session',
transcript_path: '/tmp/transcript.json',
cwd: '/work',
hook_event_name: HookEventName.SessionEnd,
timestamp: new Date().toISOString(),
reason: SessionEndReason.Clear,
};
const serviceSpy = vi.spyOn(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(hookRunner as any).sessionLearningsService,
'generateAndSaveLearnings',
);
const result = await hookRunner.executeHook(
hookConfig,
HookEventName.SessionEnd,
input,
);
expect(result.success).toBe(true);
expect(serviceSpy).not.toHaveBeenCalled();
});
});
+71 -7
View File
@@ -6,7 +6,7 @@
import { spawn } from 'node:child_process';
import type { HookConfig } from './types.js';
import { HookEventName, ConfigSource } from './types.js';
import { HookEventName, ConfigSource, HookType } from './types.js';
import type { Config } from '../config/config.js';
import type {
HookInput,
@@ -16,7 +16,9 @@ import type {
BeforeModelInput,
BeforeModelOutput,
BeforeToolInput,
SessionEndInput,
} from './types.js';
import { SessionEndReason } from './types.js';
import type { LLMRequest } from './hookTranslator.js';
import { debugLogger } from '../utils/debugLogger.js';
import { sanitizeEnvironment } from '../services/environmentSanitization.js';
@@ -25,6 +27,7 @@ import {
getShellConfiguration,
type ShellType,
} from '../utils/shell-utils.js';
import { SessionLearningsService } from '../services/sessionLearningsService.js';
/**
* Default timeout for hook execution (60 seconds)
@@ -43,9 +46,11 @@ const EXIT_CODE_NON_BLOCKING_ERROR = 1;
*/
export class HookRunner {
private readonly config: Config;
private readonly sessionLearningsService: SessionLearningsService;
constructor(config: Config) {
this.config = config;
this.sessionLearningsService = new SessionLearningsService(config);
}
/**
@@ -76,12 +81,25 @@ export class HookRunner {
}
try {
return await this.executeCommandHook(
hookConfig,
eventName,
input,
startTime,
);
if (hookConfig.type === HookType.Command) {
return await this.executeCommandHook(
hookConfig,
eventName,
input,
startTime,
);
} else if (hookConfig.type === HookType.Builtin) {
return await this.executeBuiltinHook(
hookConfig,
eventName,
input,
startTime,
);
} else {
throw new Error(
`Unsupported hook type: ${(hookConfig as HookConfig).type}`,
);
}
} catch (error) {
const duration = Date.now() - startTime;
const hookId = hookConfig.name || hookConfig.command || 'unknown';
@@ -231,6 +249,52 @@ export class HookRunner {
return modifiedInput;
}
/**
* Execute a builtin hook
*/
private async executeBuiltinHook(
hookConfig: HookConfig,
eventName: HookEventName,
input: HookInput,
startTime: number,
): Promise<HookExecutionResult> {
if (hookConfig.type !== HookType.Builtin) {
throw new Error('Expected builtin hook configuration');
}
try {
if (hookConfig.builtin_id === 'session-learnings') {
if (eventName === HookEventName.SessionEnd) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const sessionEndInput = input as SessionEndInput;
if (
sessionEndInput.reason === SessionEndReason.Exit ||
sessionEndInput.reason === SessionEndReason.Logout
) {
await this.sessionLearningsService.generateAndSaveLearnings();
}
}
}
return {
hookConfig,
eventName,
success: true,
duration: Date.now() - startTime,
exitCode: EXIT_CODE_SUCCESS,
output: {},
};
} catch (error) {
return {
hookConfig,
eventName,
success: false,
error: error instanceof Error ? error : new Error(String(error)),
duration: Date.now() - startTime,
};
}
}
/**
* Execute a command hook
*/
+14 -3
View File
@@ -62,7 +62,16 @@ export interface CommandHookConfig {
env?: Record<string, string>;
}
export type HookConfig = CommandHookConfig;
export interface BuiltinHookConfig {
type: HookType.Builtin;
builtin_id: string;
name?: string;
description?: string;
timeout?: number;
source?: ConfigSource;
}
export type HookConfig = CommandHookConfig | BuiltinHookConfig;
/**
* Hook definition with matcher
@@ -78,6 +87,7 @@ export interface HookDefinition {
*/
export enum HookType {
Command = 'command',
Builtin = 'builtin',
}
/**
@@ -85,8 +95,9 @@ export enum HookType {
*/
export function getHookKey(hook: HookConfig): string {
const name = hook.name || '';
const command = hook.command || '';
return `${name}:${command}`;
const identifier =
hook.type === HookType.Command ? hook.command : hook.builtin_id;
return `${name}:${identifier}`;
}
/**
+103
View File
@@ -951,4 +951,107 @@ name = "invalid-name"
vi.doUnmock('node:fs/promises');
});
it('should allow overriding Plan Mode deny with user policy', async () => {
const actualFs =
await vi.importActual<typeof import('node:fs/promises')>(
'node:fs/promises',
);
const mockReaddir = vi.fn(
async (
path: string | Buffer | URL,
options?: Parameters<typeof actualFs.readdir>[1],
) => {
const normalizedPath = nodePath.normalize(path.toString());
if (normalizedPath.includes(nodePath.normalize('.gemini/policies'))) {
return [
{
name: 'user-plan.toml',
isFile: () => true,
isDirectory: () => false,
},
] as unknown as Awaited<ReturnType<typeof actualFs.readdir>>;
}
return actualFs.readdir(
path,
options as Parameters<typeof actualFs.readdir>[1],
);
},
);
const mockReadFile = vi.fn(
async (
path: Parameters<typeof actualFs.readFile>[0],
options: Parameters<typeof actualFs.readFile>[1],
) => {
const normalizedPath = nodePath.normalize(path.toString());
if (normalizedPath.includes('user-plan.toml')) {
return `
[[rule]]
toolName = "run_shell_command"
commandPrefix = ["git status", "git diff"]
decision = "allow"
priority = 100
modes = ["plan"]
[[rule]]
toolName = "codebase_investigator"
decision = "allow"
priority = 100
modes = ["plan"]
`;
}
return actualFs.readFile(path, options);
},
);
vi.doMock('node:fs/promises', () => ({
...actualFs,
default: { ...actualFs, readFile: mockReadFile, readdir: mockReaddir },
readFile: mockReadFile,
readdir: mockReaddir,
}));
vi.resetModules();
const { createPolicyEngineConfig } = await import('./config.js');
const settings: PolicySettings = {};
const config = await createPolicyEngineConfig(
settings,
ApprovalMode.PLAN,
nodePath.join(__dirname, 'policies'),
);
const shellRules = config.rules?.filter(
(r) =>
r.toolName === 'run_shell_command' &&
r.decision === PolicyDecision.ALLOW &&
r.modes?.includes(ApprovalMode.PLAN) &&
r.argsPattern,
);
expect(shellRules).toHaveLength(2);
expect(
shellRules?.some((r) => r.argsPattern?.test('{"command":"git status"}')),
).toBe(true);
expect(
shellRules?.some((r) => r.argsPattern?.test('{"command":"git diff"}')),
).toBe(true);
expect(
shellRules?.every(
(r) => !r.argsPattern?.test('{"command":"git commit"}'),
),
).toBe(true);
const subagentRule = config.rules?.find(
(r) =>
r.toolName === 'codebase_investigator' &&
r.decision === PolicyDecision.ALLOW &&
r.modes?.includes(ApprovalMode.PLAN),
);
expect(subagentRule).toBeDefined();
expect(subagentRule?.priority).toBeCloseTo(2.1, 5);
vi.doUnmock('node:fs/promises');
});
});
+2 -2
View File
@@ -31,12 +31,12 @@
decision = "deny"
priority = 60
modes = ["plan"]
deny_message = "You are in Plan Mode - adjust your prompt to only use read and search tools."
deny_message = "You are in Plan Mode with access to read-only tools. Execution of scripts (including those from skills) is blocked."
# Explicitly Allow Read-Only Tools in Plan mode.
[[rule]]
toolName = ["glob", "grep_search", "list_directory", "read_file", "google_web_search"]
toolName = ["glob", "grep_search", "list_directory", "read_file", "google_web_search", "activate_skill"]
decision = "allow"
priority = 70
modes = ["plan"]
@@ -2086,4 +2086,44 @@ describe('PolicyEngine', () => {
expect(result.decision).toBe(PolicyDecision.ALLOW);
});
});
describe('Plan Mode', () => {
it('should allow activate_skill but deny shell commands in Plan Mode', async () => {
const rules: PolicyRule[] = [
{
decision: PolicyDecision.DENY,
priority: 60,
modes: [ApprovalMode.PLAN],
denyMessage:
'You are in Plan Mode with access to read-only tools. Execution of scripts (including those from skills) is blocked.',
},
{
toolName: 'activate_skill',
decision: PolicyDecision.ALLOW,
priority: 70,
modes: [ApprovalMode.PLAN],
},
];
engine = new PolicyEngine({
rules,
approvalMode: ApprovalMode.PLAN,
});
const skillResult = await engine.check(
{ name: 'activate_skill', args: { name: 'test' } },
undefined,
);
expect(skillResult.decision).toBe(PolicyDecision.ALLOW);
const shellResult = await engine.check(
{ name: 'run_shell_command', args: { command: 'ls' } },
undefined,
);
expect(shellResult.decision).toBe(PolicyDecision.DENY);
expect(shellResult.rule?.denyMessage).toContain(
'Execution of scripts (including those from skills) is blocked',
);
});
});
});
+37 -21
View File
@@ -428,34 +428,50 @@ ${options.planModeToolsList}
- You are restricted to writing files within this directory while in Plan Mode.
- Use descriptive filenames: \`feature-name.md\` or \`bugfix-description.md\`
## Workflow Rules
1. Sequential Execution: Complete ONE phase at a time. Do NOT skip ahead or combine phases.
2. User Confirmation: Wait for user input/approval before proceeding to the next phase.
3. Step Back Protocol: If new information discovered during Exploration or Design invalidates previous assumptions or requirements, you MUST pause, inform the user, and request to return to the appropriate previous phase.
## Workflow Phases
**IMPORTANT: Complete ONE phase at a time. Do NOT skip ahead or combine phases. Wait for user input before proceeding to the next phase.**
### Phase 1: Requirements
- Analyze the user's request to identify core requirements and constraints.
- Proactively identify ambiguities, implicit assumptions, and edge cases.
- Categorize questions: functional requirements, non-functional constraints (performance, compatibility), and scope boundaries.
- Use the ${formatToolName(ASK_USER_TOOL_NAME)} tool with well-structured options to clarify ambiguities. Prefer providing multiple-choice options for the user to select from when possible.
### Phase 1: Requirements Understanding
- Analyze the user's request to identify core requirements and constraints
- If critical information is missing or ambiguous, ask clarifying questions using the ${formatToolName(ASK_USER_TOOL_NAME)} tool
- When using ${formatToolName(ASK_USER_TOOL_NAME)}, prefer providing multiple-choice options for the user to select from when possible
- Do NOT explore the project or create a plan yet
### Phase 2: Exploration
- Only begin this phase after requirements are clear.
- Use the available read-only tools to explore the project.
- Map relevant code paths, dependencies, and architectural patterns.
- Identify existing utilities, patterns, and abstractions that can be reused.
- Note potential constraints (e.g., existing conventions, test infrastructure).
- Output: Summarize key findings to the user before proceeding to design.
### Phase 2: Project Exploration
- Only begin this phase after requirements are clear
- Use the available read-only tools to explore the project
- Identify existing patterns, conventions, and architectural decisions
### Phase 3: Design
- Only begin this phase after exploration is complete.
- **Identify Approaches:**
- For Complex Tasks: Identify at least 2 viable implementation approaches. Document the approach summary, pros, cons, complexity estimate, and risk factors for each.
- For Canonical Tasks: If there is only one reasonable, standard approach (e.g., a standard library pattern or specific bug fix), detail it and explicitly explain why no other viable alternatives were considered.
- Mandatory User Interaction: Present the analysis to the user via ${formatToolName(ASK_USER_TOOL_NAME)} and recommend a preferred approach.
- Wait for Selection: You MUST pause and wait for the user to select an approach before proceeding. Do NOT assume the user will agree with your recommendation.
### Phase 3: Design & Planning
- Only begin this phase after exploration is complete
- Create a detailed implementation plan with clear steps
- The plan MUST include:
- Iterative development steps (e.g., "Implement X, then verify with test Y")
- Specific verification steps (unit tests, manual checks, build commands)
- File paths, function signatures, and code snippets where helpful
- Save the implementation plan to the designated plans directory
### Phase 4: Planning
- Pre-requisite: You MUST have a user-selected approach from Phase 3 before generating the plan.
- Create a detailed implementation plan and save it to the designated plans directory.
- **Document Structure:** The plan MUST be a structured Markdown document (focused on implementation guidance, not workflow logging) using exactly these H2 headings:
- \`## Problem Statement\` - Describe the problem or need this change addresses.
- \`## Proposed Solution\` - Provide technical details of the implementation.
- \`## Implementation Plan\` - List ordered steps with specific file paths and the nature of each change.
- \`## Verification Plan\` - Define specific tests or manual steps to verify the change works and breaks nothing else.
- \`## Risks & Mitigations\` - Identify potential failure modes and mitigation strategies.
- \`## Alternatives Considered\` - Provide a brief analysis of other approaches considered and why they were rejected.
### Phase 4: Review & Approval
### Phase 5: Approval
- Present the plan and request approval for the finalized plan using the ${formatToolName(EXIT_PLAN_MODE_TOOL_NAME)} tool
- If plan is approved, you can begin implementation
- If plan is rejected, address the feedback and iterate on the plan
- If plan is approved, you can begin implementation.
- If plan is rejected, address the feedback and iterate on the plan.
${renderApprovedPlanSection(options.approvedPlanPath)}
@@ -0,0 +1,182 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { SessionLearningsService } from './sessionLearningsService.js';
import type { Config } from '../config/config.js';
import type { GenerateContentResponse } from '@google/genai';
import fs from 'node:fs/promises';
import path from 'node:path';
describe('SessionLearningsService', () => {
let service: SessionLearningsService;
let mockConfig: unknown;
let mockRecordingService: any;
let mockGeminiClient: any;
let mockContentGenerator: any;
let mockGenerateContent: any;
beforeEach(() => {
vi.clearAllMocks();
mockGenerateContent = vi.fn().mockImplementation((_params, promptId) => {
if (promptId === 'session-learnings-generation') {
return Promise.resolve({
candidates: [
{
content: {
parts: [{ text: '# Session Learnings\nSummary text here.' }],
},
},
],
} as unknown as GenerateContentResponse);
} else if (promptId === 'session-summary-generation') {
return Promise.resolve({
candidates: [
{
content: {
parts: [{ text: 'Mock Session Title' }],
},
},
],
} as unknown as GenerateContentResponse);
}
return Promise.reject(new Error(`Unexpected promptId: ${promptId}`));
});
mockContentGenerator = {
generateContent: mockGenerateContent,
};
mockRecordingService = {
getConversation: vi.fn().mockReturnValue({
messages: [
{ type: 'user', content: [{ text: 'Question' }] },
{ type: 'gemini', content: [{ text: 'Answer' }] },
],
}),
};
mockGeminiClient = {
getChatRecordingService: () => mockRecordingService,
};
mockConfig = {
isSessionLearningsEnabled: vi.fn().mockReturnValue(true),
getSessionLearningsOutputPath: vi.fn().mockReturnValue(undefined),
getGeminiClient: () => mockGeminiClient,
getContentGenerator: () => mockContentGenerator,
getWorkingDir: () => '/mock/cwd',
getActiveModel: () => 'gemini-1.5-flash',
getModel: () => 'gemini-1.5-flash',
isInteractive: () => true,
setActiveModel: vi.fn(),
getUserTier: () => 'free',
getContentGeneratorConfig: () => ({ authType: 'apiKey' }),
getModelAvailabilityService: () => ({
selectFirstAvailable: (models: string[]) => ({
selectedModel: models[0],
}),
consumeStickyAttempt: vi.fn(),
markHealthy: vi.fn(),
}),
modelConfigService: {
getResolvedConfig: vi
.fn()
.mockReturnValue({ model: 'gemini-1.5-flash', config: {} }),
},
};
service = new SessionLearningsService(mockConfig as Config);
vi.spyOn(fs, 'writeFile').mockResolvedValue(undefined);
vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as any);
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should generate and save learnings with descriptive filename', async () => {
const dateStr = new Date().toISOString().split('T')[0];
await service.generateAndSaveLearnings();
expect(mockGenerateContent).toHaveBeenCalledTimes(2);
expect(fs.writeFile).toHaveBeenCalledWith(
path.join('/mock/cwd', `learnings-Mock-Session-Title-${dateStr}.md`),
'# Session Learnings\nSummary text here.',
'utf-8',
);
});
it('should use custom output path if configured', async () => {
const dateStr = new Date().toISOString().split('T')[0];
(mockConfig as any).getSessionLearningsOutputPath.mockReturnValue(
'custom/path',
);
await service.generateAndSaveLearnings();
expect(fs.mkdir).toHaveBeenCalledWith(
path.join('/mock/cwd', 'custom/path'),
{ recursive: true },
);
expect(fs.writeFile).toHaveBeenCalledWith(
path.join(
'/mock/cwd',
'custom/path',
`learnings-Mock-Session-Title-${dateStr}.md`,
),
'# Session Learnings\nSummary text here.',
'utf-8',
);
});
it('should use absolute output path if configured', async () => {
const dateStr = new Date().toISOString().split('T')[0];
(mockConfig as any).getSessionLearningsOutputPath.mockReturnValue(
'/absolute/path',
);
await service.generateAndSaveLearnings();
expect(fs.mkdir).toHaveBeenCalledWith('/absolute/path', {
recursive: true,
});
expect(fs.writeFile).toHaveBeenCalledWith(
path.join('/absolute/path', `learnings-Mock-Session-Title-${dateStr}.md`),
'# Session Learnings\nSummary text here.',
'utf-8',
);
});
it('should not generate learnings if disabled', async () => {
(mockConfig as any).isSessionLearningsEnabled.mockReturnValue(false);
await service.generateAndSaveLearnings();
expect(mockGenerateContent).not.toHaveBeenCalled();
expect(fs.writeFile).not.toHaveBeenCalled();
});
it('should not generate learnings if not enough messages', async () => {
mockRecordingService.getConversation.mockReturnValue({
messages: [{ type: 'user', content: [{ text: 'Single message' }] }],
});
await service.generateAndSaveLearnings();
expect(mockGenerateContent).not.toHaveBeenCalled();
});
it('should handle errors gracefully', async () => {
mockGenerateContent.mockRejectedValue(new Error('LLM Error'));
// Should not throw
await expect(service.generateAndSaveLearnings()).resolves.not.toThrow();
});
});
@@ -0,0 +1,158 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type { Config } from '../config/config.js';
import { BaseLlmClient } from '../core/baseLlmClient.js';
import { debugLogger } from '../utils/debugLogger.js';
import { partListUnionToString } from '../core/geminiRequest.js';
import { getResponseText } from '../utils/partUtils.js';
import { SessionSummaryService } from './sessionSummaryService.js';
import { sanitizeFilenamePart } from '../utils/fileUtils.js';
import type { Content } from '@google/genai';
import fs from 'node:fs/promises';
import path from 'node:path';
const MIN_MESSAGES = 2;
const TIMEOUT_MS = 60000; // Increased timeout for potentially larger context
const LEARNINGS_PROMPT = `It's time to pause on this development. Looking back at what you have done so far:
Prepare a summary of the problem you were trying to solve, the analysis synthesized, and information you would need to implement this request if you were to start again
Don't focus on unnecessary details - keep the abstraction at a level that allows a senior engineer for example, to take it from you.
Do focus on gotchas, explored paths that didn't go anywhere with a why, and what you'd do differently.
Also note down other issues you might have found as future project ideas.
Conversation transcript follows:
---
{transcript}
---
Provide your response in Markdown format.`;
/**
* Service to generate and save session learnings summaries.
*/
export class SessionLearningsService {
constructor(private readonly config: Config) {}
/**
* Generates a summary of the session learnings and saves it to a file.
*/
async generateAndSaveLearnings(): Promise<void> {
try {
// Check if enabled in settings
if (!this.config.isSessionLearningsEnabled()) {
return;
}
const geminiClient = this.config.getGeminiClient();
const recordingService = geminiClient.getChatRecordingService();
if (!recordingService) {
debugLogger.debug('[SessionLearnings] Recording service not available');
return;
}
const conversation = recordingService.getConversation();
if (!conversation || conversation.messages.length < MIN_MESSAGES) {
debugLogger.debug(
`[SessionLearnings] Skipping summary, not enough messages (${conversation?.messages.length || 0})`,
);
return;
}
// Prepare transcript (no max messages, no max length)
const transcript = conversation.messages
.map((msg) => {
const role = msg.type === 'user' ? 'User' : 'Assistant';
const content = partListUnionToString(msg.content);
return `[${role}]: ${content}`;
})
.join('\n\n');
const prompt = LEARNINGS_PROMPT.replace('{transcript}', transcript);
const contentGenerator = this.config.getContentGenerator();
if (!contentGenerator) {
debugLogger.debug('[SessionLearnings] Content generator not available');
return;
}
const baseLlmClient = new BaseLlmClient(contentGenerator, this.config);
const abortController = new AbortController();
const timeoutId = setTimeout(() => abortController.abort(), TIMEOUT_MS);
try {
const contents: Content[] = [
{
role: 'user',
parts: [{ text: prompt }],
},
];
debugLogger.debug('[SessionLearnings] Generating summary...');
const response = await baseLlmClient.generateContent({
modelConfigKey: { model: 'summarizer-default' },
contents,
abortSignal: abortController.signal,
promptId: 'session-learnings-generation',
});
const summaryText = getResponseText(response);
if (!summaryText) {
debugLogger.warn(
'[SessionLearnings] Failed to generate summary (empty response)',
);
return;
}
// Generate descriptive filename
const summaryService = new SessionSummaryService(baseLlmClient);
const sessionTitle = await summaryService.generateSummary({
messages: conversation.messages,
});
const dateStr = new Date().toISOString().split('T')[0];
const sanitizedTitle = sessionTitle
? sanitizeFilenamePart(sessionTitle.trim().replace(/\s+/g, '-'))
: 'untitled';
const fileName = `learnings-${sanitizedTitle}-${dateStr}.md`;
// Determine output directory
const configOutputPath = this.config.getSessionLearningsOutputPath();
let outputDir = this.config.getWorkingDir();
if (configOutputPath) {
if (path.isAbsolute(configOutputPath)) {
outputDir = configOutputPath;
} else {
outputDir = path.join(
this.config.getWorkingDir(),
configOutputPath,
);
}
}
// Ensure directory exists
await fs.mkdir(outputDir, { recursive: true });
const filePath = path.join(outputDir, fileName);
await fs.writeFile(filePath, summaryText, 'utf-8');
debugLogger.log(
`[SessionLearnings] Saved session learnings to ${filePath}`,
);
} finally {
clearTimeout(timeoutId);
}
} catch (error) {
debugLogger.warn(
`[SessionLearnings] Error generating learnings: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
}
+5 -1
View File
@@ -207,7 +207,11 @@ export class AskUserInvocation extends BaseToolInvocation<
.map(([index, answer]) => {
const question = this.params.questions[parseInt(index, 10)];
const category = question?.header ?? `Q${index}`;
return ` ${category}${answer}`;
const prefix = ` ${category}`;
const indent = ' '.repeat(prefix.length);
const lines = answer.split('\n');
return prefix + lines.join('\n' + indent);
})
.join('\n')}`
: 'User submitted without answering questions.';
@@ -49,10 +49,20 @@ exports[`coreTools snapshots for specific models > Model: gemini-2.5-pro > snaps
"description": "Optional: A glob pattern to filter which files are searched (e.g., '*.js', '*.{ts,tsx}', 'src/**'). If omitted, searches all files (respecting potential global ignores).",
"type": "string",
},
"max_matches_per_file": {
"description": "Optional: Maximum number of matches to return per file. Use this to prevent being overwhelmed by repetitive matches in large files.",
"minimum": 1,
"type": "integer",
},
"pattern": {
"description": "The regular expression (regex) pattern to search for within file contents (e.g., 'function\\s+myFunction', 'import\\s+\\{.*\\}\\s+from\\s+.*').",
"type": "string",
},
"total_max_matches": {
"description": "Optional: Maximum number of total matches to return. Use this to limit the overall size of the response. Defaults to 100 if omitted.",
"minimum": 1,
"type": "integer",
},
},
"required": [
"pattern",
@@ -248,10 +258,20 @@ exports[`coreTools snapshots for specific models > Model: gemini-3-pro-preview >
"description": "Optional: A glob pattern to filter which files are searched (e.g., '*.js', '*.{ts,tsx}', 'src/**'). If omitted, searches all files (respecting potential global ignores).",
"type": "string",
},
"max_matches_per_file": {
"description": "Optional: Maximum number of matches to return per file. Use this to prevent being overwhelmed by repetitive matches in large files.",
"minimum": 1,
"type": "integer",
},
"pattern": {
"description": "The regular expression (regex) pattern to search for within file contents (e.g., 'function\\s+myFunction', 'import\\s+\\{.*\\}\\s+from\\s+.*').",
"type": "string",
},
"total_max_matches": {
"description": "Optional: Maximum number of total matches to return. Use this to limit the overall size of the response. Defaults to 100 if omitted.",
"minimum": 1,
"type": "integer",
},
},
"required": [
"pattern",
@@ -5,6 +5,7 @@
*/
import type { ToolDefinition } from './types.js';
import { Type } from '@google/genai';
import * as os from 'node:os';
// Centralized tool names to avoid circular dependencies
@@ -24,21 +25,21 @@ export const READ_FILE_DEFINITION: ToolDefinition = {
name: READ_FILE_TOOL_NAME,
description: `Reads and returns the content of a specified file. If the file is large, the content will be truncated. The tool's response will clearly indicate if truncation has occurred and will provide details on how to read more of the file using the 'offset' and 'limit' parameters. Handles text, images (PNG, JPG, GIF, WEBP, SVG, BMP), audio files (MP3, WAV, AIFF, AAC, OGG, FLAC), and PDF files. For text files, it can read specific line ranges.`,
parametersJsonSchema: {
type: 'object',
type: Type.OBJECT,
properties: {
file_path: {
description: 'The path to the file to read.',
type: 'string',
type: Type.STRING,
},
offset: {
description:
"Optional: For text files, the 0-based line number to start reading from. Requires 'limit' to be set. Use for paginating through large files.",
type: 'number',
type: Type.NUMBER,
},
limit: {
description:
"Optional: For text files, maximum number of lines to read. Use with 'offset' to paginate through large files. If omitted, reads the entire file (if feasible, up to a default limit).",
type: 'number',
type: Type.NUMBER,
},
},
required: ['file_path'],
@@ -57,15 +58,15 @@ export const WRITE_FILE_DEFINITION: ToolDefinition = {
The user has the ability to modify \`content\`. If modified, this will be stated in the response.`,
parametersJsonSchema: {
type: 'object',
type: Type.OBJECT,
properties: {
file_path: {
description: 'The path to the file to write to.',
type: 'string',
type: Type.STRING,
},
content: {
description: 'The content to write to the file.',
type: 'string',
type: Type.STRING,
},
},
required: ['file_path', 'content'],
@@ -83,20 +84,32 @@ export const GREP_DEFINITION: ToolDefinition = {
description:
'Searches for a regular expression pattern within file contents. Max 100 matches.',
parametersJsonSchema: {
type: 'object',
type: Type.OBJECT,
properties: {
pattern: {
description: `The regular expression (regex) pattern to search for within file contents (e.g., 'function\\s+myFunction', 'import\\s+\\{.*\\}\\s+from\\s+.*').`,
type: 'string',
type: Type.STRING,
},
dir_path: {
description:
'Optional: The absolute path to the directory to search within. If omitted, searches the current working directory.',
type: 'string',
type: Type.STRING,
},
include: {
description: `Optional: A glob pattern to filter which files are searched (e.g., '*.js', '*.{ts,tsx}', 'src/**'). If omitted, searches all files (respecting potential global ignores).`,
type: 'string',
type: Type.STRING,
},
max_matches_per_file: {
description:
'Optional: Maximum number of matches to return per file. Use this to prevent being overwhelmed by repetitive matches in large files.',
type: Type.INTEGER,
minimum: 1,
},
total_max_matches: {
description:
'Optional: Maximum number of total matches to return. Use this to limit the overall size of the response. Defaults to 100 if omitted.',
type: Type.INTEGER,
minimum: 1,
},
},
required: ['pattern'],
@@ -114,32 +127,32 @@ export const GLOB_DEFINITION: ToolDefinition = {
description:
'Efficiently finds files matching specific glob patterns (e.g., `src/**/*.ts`, `**/*.md`), returning absolute paths sorted by modification time (newest first). Ideal for quickly locating files based on their name or path structure, especially in large codebases.',
parametersJsonSchema: {
type: 'object',
type: Type.OBJECT,
properties: {
pattern: {
description:
"The glob pattern to match against (e.g., '**/*.py', 'docs/*.md').",
type: 'string',
type: Type.STRING,
},
dir_path: {
description:
'Optional: The absolute path to the directory to search within. If omitted, searches the root directory.',
type: 'string',
type: Type.STRING,
},
case_sensitive: {
description:
'Optional: Whether the search should be case-sensitive. Defaults to false.',
type: 'boolean',
type: Type.BOOLEAN,
},
respect_git_ignore: {
description:
'Optional: Whether to respect .gitignore patterns when finding files. Only available in git repositories. Defaults to true.',
type: 'boolean',
type: Type.BOOLEAN,
},
respect_gemini_ignore: {
description:
'Optional: Whether to respect .geminiignore patterns when finding files. Defaults to true.',
type: 'boolean',
type: Type.BOOLEAN,
},
},
required: ['pattern'],
@@ -157,33 +170,33 @@ export const LS_DEFINITION: ToolDefinition = {
description:
'Lists the names of files and subdirectories directly within a specified directory path. Can optionally ignore entries matching provided glob patterns.',
parametersJsonSchema: {
type: 'object',
type: Type.OBJECT,
properties: {
dir_path: {
description: 'The path to the directory to list',
type: 'string',
type: Type.STRING,
},
ignore: {
description: 'List of glob patterns to ignore',
items: {
type: 'string',
type: Type.STRING,
},
type: 'array',
type: Type.ARRAY,
},
file_filtering_options: {
description:
'Optional: Whether to respect ignore patterns from .gitignore or .geminiignore',
type: 'object',
type: Type.OBJECT,
properties: {
respect_git_ignore: {
description:
'Optional: Whether to respect .gitignore patterns when listing files. Only available in git repositories. Defaults to true.',
type: 'boolean',
type: Type.BOOLEAN,
},
respect_gemini_ignore: {
description:
'Optional: Whether to respect .geminiignore patterns when listing files. Defaults to true.',
type: 'boolean',
type: Type.BOOLEAN,
},
},
},
@@ -261,24 +274,24 @@ export function getShellDefinition(
enableEfficiency,
),
parametersJsonSchema: {
type: 'object',
type: Type.OBJECT,
properties: {
command: {
type: 'string',
type: Type.STRING,
description: getCommandDescription(),
},
description: {
type: 'string',
type: Type.STRING,
description:
'Brief description of the command for the user. Be specific and concise. Ideally a single sentence. Can be up to 3 sentences for clarity. No line breaks.',
},
dir_path: {
type: 'string',
type: Type.STRING,
description:
'(OPTIONAL) The path of the directory to run the command in. If not provided, the project root directory is used. Must be a directory within the workspace and must already exist.',
},
is_background: {
type: 'boolean',
type: Type.BOOLEAN,
description:
'Set to true if this command should be run in the background (e.g. for long-running servers or watchers). The command will be started, allowed to run for a brief moment to check for immediate errors, and then moved to the background.',
},
+40
View File
@@ -458,6 +458,46 @@ describe('GrepTool', () => {
// Clean up
await fs.rm(secondDir, { recursive: true, force: true });
});
it('should respect total_max_matches and truncate results', async () => {
// Use 'world' pattern which has 3 matches across fileA.txt and sub/fileC.txt
const params: GrepToolParams = {
pattern: 'world',
total_max_matches: 2,
};
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain('Found 2 matches');
expect(result.llmContent).toContain(
'results limited to 2 matches for performance',
);
// It should find matches in fileA.txt first (2 matches)
expect(result.llmContent).toContain('File: fileA.txt');
expect(result.llmContent).toContain('L1: hello world');
expect(result.llmContent).toContain('L2: second line with world');
// And sub/fileC.txt should be excluded because limit reached
expect(result.llmContent).not.toContain('File: sub/fileC.txt');
expect(result.returnDisplay).toBe('Found 2 matches (limited)');
});
it('should respect max_matches_per_file in JS fallback', async () => {
const params: GrepToolParams = {
pattern: 'world',
max_matches_per_file: 1,
};
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
// fileA.txt has 2 worlds, but should only return 1.
// sub/fileC.txt has 1 world, so total matches = 2.
expect(result.llmContent).toContain('Found 2 matches');
expect(result.llmContent).toContain('File: fileA.txt');
expect(result.llmContent).toContain('L1: hello world');
expect(result.llmContent).not.toContain('L2: second line with world');
expect(result.llmContent).toContain('File: sub/fileC.txt');
expect(result.llmContent).toContain('L1: another world in sub dir');
});
});
describe('getDescription', () => {
+49 -2
View File
@@ -48,6 +48,16 @@ export interface GrepToolParams {
* File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")
*/
include?: string;
/**
* Optional: Maximum number of matches to return per file. Use this to prevent being overwhelmed by repetitive matches in large files.
*/
max_matches_per_file?: number;
/**
* Optional: Maximum number of total matches to return. Use this to limit the overall size of the response. Defaults to 100 if omitted.
*/
total_max_matches?: number;
}
/**
@@ -189,7 +199,8 @@ class GrepToolInvocation extends BaseToolInvocation<
// Collect matches from all search directories
let allMatches: GrepMatch[] = [];
const totalMaxMatches = DEFAULT_TOTAL_MAX_MATCHES;
const totalMaxMatches =
this.params.total_max_matches ?? DEFAULT_TOTAL_MAX_MATCHES;
// Create a timeout controller to prevent indefinitely hanging searches
const timeoutController = new AbortController();
@@ -215,6 +226,7 @@ class GrepToolInvocation extends BaseToolInvocation<
path: searchDir,
include: this.params.include,
maxMatches: remainingLimit,
max_matches_per_file: this.params.max_matches_per_file,
signal: timeoutController.signal,
});
@@ -343,9 +355,16 @@ class GrepToolInvocation extends BaseToolInvocation<
path: string; // Expects absolute path
include?: string;
maxMatches: number;
max_matches_per_file?: number;
signal: AbortSignal;
}): Promise<GrepMatch[]> {
const { pattern, path: absolutePath, include, maxMatches } = options;
const {
pattern,
path: absolutePath,
include,
maxMatches,
max_matches_per_file,
} = options;
let strategyUsed = 'none';
try {
@@ -363,6 +382,9 @@ class GrepToolInvocation extends BaseToolInvocation<
'--ignore-case',
pattern,
];
if (max_matches_per_file) {
gitArgs.push('--max-count', max_matches_per_file.toString());
}
if (include) {
gitArgs.push('--', include);
}
@@ -425,6 +447,9 @@ class GrepToolInvocation extends BaseToolInvocation<
})
.filter((dir): dir is string => !!dir);
commonExcludes.forEach((dir) => grepArgs.push(`--exclude-dir=${dir}`));
if (max_matches_per_file) {
grepArgs.push('--max-count', max_matches_per_file.toString());
}
if (include) {
grepArgs.push(`--include=${include}`);
}
@@ -499,6 +524,7 @@ class GrepToolInvocation extends BaseToolInvocation<
try {
const content = await fsPromises.readFile(fileAbsolutePath, 'utf8');
const lines = content.split(/\r?\n/);
let matchesInFile = 0;
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
if (regex.test(line)) {
@@ -509,7 +535,14 @@ class GrepToolInvocation extends BaseToolInvocation<
lineNumber: index + 1,
line,
});
matchesInFile++;
if (allMatches.length >= maxMatches) break;
if (
max_matches_per_file &&
matchesInFile >= max_matches_per_file
) {
break;
}
}
}
} catch (readError: unknown) {
@@ -604,6 +637,20 @@ export class GrepTool extends BaseDeclarativeTool<GrepToolParams, ToolResult> {
return `Invalid regular expression pattern provided: ${params.pattern}. Error: ${getErrorMessage(error)}`;
}
if (
params.max_matches_per_file !== undefined &&
params.max_matches_per_file < 1
) {
return 'max_matches_per_file must be at least 1.';
}
if (
params.total_max_matches !== undefined &&
params.total_max_matches < 1
) {
return 'total_max_matches must be at least 1.';
}
// Only validate dir_path if one is provided
if (params.dir_path) {
const resolvedPath = path.resolve(
@@ -103,6 +103,43 @@ describe('McpClientManager', () => {
expect(manager.getDiscoveryState()).toBe(MCPDiscoveryState.COMPLETED);
});
it('should mark discovery completed when all configured servers are user-disabled', async () => {
mockConfig.getMcpServers.mockReturnValue({
'test-server': {},
});
mockConfig.getMcpEnablementCallbacks.mockReturnValue({
isSessionDisabled: vi.fn().mockReturnValue(false),
isFileEnabled: vi.fn().mockResolvedValue(false),
});
const manager = new McpClientManager('0.0.1', toolRegistry, mockConfig);
const promise = manager.startConfiguredMcpServers();
expect(manager.getDiscoveryState()).toBe(MCPDiscoveryState.IN_PROGRESS);
await promise;
expect(manager.getDiscoveryState()).toBe(MCPDiscoveryState.COMPLETED);
expect(manager.getMcpServerCount()).toBe(0);
expect(mockedMcpClient.connect).not.toHaveBeenCalled();
expect(mockedMcpClient.discover).not.toHaveBeenCalled();
});
it('should mark discovery completed when all configured servers are blocked', async () => {
mockConfig.getMcpServers.mockReturnValue({
'test-server': {},
});
mockConfig.getBlockedMcpServers.mockReturnValue(['test-server']);
const manager = new McpClientManager('0.0.1', toolRegistry, mockConfig);
const promise = manager.startConfiguredMcpServers();
expect(manager.getDiscoveryState()).toBe(MCPDiscoveryState.IN_PROGRESS);
await promise;
expect(manager.getDiscoveryState()).toBe(MCPDiscoveryState.COMPLETED);
expect(manager.getMcpServerCount()).toBe(0);
expect(mockedMcpClient.connect).not.toHaveBeenCalled();
expect(mockedMcpClient.discover).not.toHaveBeenCalled();
});
it('should not discover tools if folder is not trusted', async () => {
mockConfig.getMcpServers.mockReturnValue({
'test-server': {},
@@ -337,6 +337,15 @@ export class McpClientManager {
this.maybeDiscoverMcpServer(name, config),
),
);
// If every configured server was skipped (for example because all are
// disabled by user settings), no discovery promise is created. In that
// case we must still mark discovery complete or the UI will wait forever.
if (this.discoveryState === MCPDiscoveryState.IN_PROGRESS) {
this.discoveryState = MCPDiscoveryState.COMPLETED;
this.eventEmitter?.emit('mcp-client-update', this.clients);
}
await this.cliConfig.refreshMcpContext();
}
+83
View File
@@ -1848,6 +1848,89 @@ describe('RipGrepTool', () => {
expect(invocation.getDescription()).toContain(path.join('src', 'app'));
});
});
describe('new parameters', () => {
it('should pass --max-count when max_matches_per_file is provided', async () => {
mockSpawn.mockImplementationOnce(
createMockSpawn({
outputData:
JSON.stringify({
type: 'match',
data: {
path: { text: 'fileA.txt' },
line_number: 1,
lines: { text: 'hello world\n' },
},
}) + '\n',
exitCode: 0,
}),
);
const params: RipGrepToolParams = {
pattern: 'world',
max_matches_per_file: 1,
};
const invocation = grepTool.build(params);
await invocation.execute(abortSignal);
const spawnArgs = mockSpawn.mock.calls[0][1];
expect(spawnArgs).toContain('--max-count');
expect(spawnArgs).toContain('1');
});
it('should respect total_max_matches and truncate results', async () => {
// Return 3 matches, but set total_max_matches to 2
mockSpawn.mockImplementationOnce(
createMockSpawn({
outputData:
JSON.stringify({
type: 'match',
data: {
path: { text: 'fileA.txt' },
line_number: 1,
lines: { text: 'match 1\n' },
},
}) +
'\n' +
JSON.stringify({
type: 'match',
data: {
path: { text: 'fileA.txt' },
line_number: 2,
lines: { text: 'match 2\n' },
},
}) +
'\n' +
JSON.stringify({
type: 'match',
data: {
path: { text: 'fileA.txt' },
line_number: 3,
lines: { text: 'match 3\n' },
},
}) +
'\n',
exitCode: 0,
}),
);
const params: RipGrepToolParams = {
pattern: 'match',
total_max_matches: 2,
};
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain('Found 2 matches');
expect(result.llmContent).toContain(
'results limited to 2 matches for performance',
);
expect(result.llmContent).toContain('L1: match 1');
expect(result.llmContent).toContain('L2: match 2');
expect(result.llmContent).not.toContain('L3: match 3');
expect(result.returnDisplay).toBe('Found 2 matches (limited)');
});
});
});
afterAll(() => {
+45 -1
View File
@@ -131,6 +131,16 @@ export interface RipGrepToolParams {
* If true, does not respect .gitignore or default ignores (like build/dist).
*/
no_ignore?: boolean;
/**
* Optional: Maximum number of matches to return per file. Use this to prevent being overwhelmed by repetitive matches in large files.
*/
max_matches_per_file?: number;
/**
* Optional: Maximum number of total matches to return. Use this to limit the overall size of the response. Defaults to 100 if omitted.
*/
total_max_matches?: number;
}
/**
@@ -208,7 +218,8 @@ class GrepToolInvocation extends BaseToolInvocation<
const searchDirDisplay = pathParam;
const totalMaxMatches = DEFAULT_TOTAL_MAX_MATCHES;
const totalMaxMatches =
this.params.total_max_matches ?? DEFAULT_TOTAL_MAX_MATCHES;
if (this.config.getDebugMode()) {
debugLogger.log(`[GrepTool] Total result limit: ${totalMaxMatches}`);
}
@@ -240,6 +251,7 @@ class GrepToolInvocation extends BaseToolInvocation<
before: this.params.before,
no_ignore: this.params.no_ignore,
maxMatches: totalMaxMatches,
max_matches_per_file: this.params.max_matches_per_file,
signal: timeoutController.signal,
});
} finally {
@@ -325,6 +337,7 @@ class GrepToolInvocation extends BaseToolInvocation<
before?: number;
no_ignore?: boolean;
maxMatches: number;
max_matches_per_file?: number;
signal: AbortSignal;
}): Promise<GrepMatch[]> {
const {
@@ -338,6 +351,7 @@ class GrepToolInvocation extends BaseToolInvocation<
before,
no_ignore,
maxMatches,
max_matches_per_file,
} = options;
const rgArgs = ['--json'];
@@ -366,6 +380,10 @@ class GrepToolInvocation extends BaseToolInvocation<
rgArgs.push('--no-ignore');
}
if (max_matches_per_file) {
rgArgs.push('--max-count', max_matches_per_file.toString());
}
if (include) {
rgArgs.push('--glob', include);
}
@@ -558,6 +576,18 @@ export class RipGrepTool extends BaseDeclarativeTool<
'If true, searches all files including those usually ignored (like in .gitignore, build/, dist/, etc). Defaults to false if omitted.',
type: 'boolean',
},
max_matches_per_file: {
description:
'Optional: Maximum number of matches to return per file. Use this to prevent being overwhelmed by repetitive matches in large files.',
type: 'integer',
minimum: 1,
},
total_max_matches: {
description:
'Optional: Maximum number of total matches to return. Use this to limit the overall size of the response. Defaults to 100 if omitted.',
type: 'integer',
minimum: 1,
},
},
required: ['pattern'],
type: 'object',
@@ -588,6 +618,20 @@ export class RipGrepTool extends BaseDeclarativeTool<
}
}
if (
params.max_matches_per_file !== undefined &&
params.max_matches_per_file < 1
) {
return 'max_matches_per_file must be at least 1.';
}
if (
params.total_max_matches !== undefined &&
params.total_max_matches < 1
) {
return 'total_max_matches must be at least 1.';
}
// Only validate path if one is provided
if (params.dir_path) {
const resolvedPath = path.resolve(
+1
View File
@@ -108,6 +108,7 @@ export const PLAN_MODE_TOOLS = [
LS_TOOL_NAME,
WEB_SEARCH_TOOL_NAME,
ASK_USER_TOOL_NAME,
ACTIVATE_SKILL_TOOL_NAME,
EXIT_PLAN_MODE_TOOL_NAME,
] as const;
+19 -1
View File
@@ -5,7 +5,7 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { getVersion } from './version.js';
import { getVersion, resetVersionCache } from './version.js';
import { getPackageJson } from './package.js';
vi.mock('./package.js', () => ({
@@ -17,6 +17,8 @@ describe('version', () => {
beforeEach(() => {
vi.resetModules();
vi.clearAllMocks();
resetVersionCache();
process.env = { ...originalEnv };
vi.mocked(getPackageJson).mockResolvedValue({ version: '1.0.0' });
});
@@ -43,4 +45,20 @@ describe('version', () => {
const version = await getVersion();
expect(version).toBe('unknown');
});
it('should cache the version and only call getPackageJson once', async () => {
delete process.env['CLI_VERSION'];
vi.mocked(getPackageJson).mockResolvedValue({ version: '1.2.3' });
const version1 = await getVersion();
expect(version1).toBe('1.2.3');
expect(getPackageJson).toHaveBeenCalledTimes(1);
// Change the mock value to simulate an update on disk
vi.mocked(getPackageJson).mockResolvedValue({ version: '2.0.0' });
const version2 = await getVersion();
expect(version2).toBe('1.2.3'); // Should still be the cached version
expect(getPackageJson).toHaveBeenCalledTimes(1); // Should not have been called again
});
});
+16 -3
View File
@@ -11,7 +11,20 @@ import path from 'node:path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export async function getVersion(): Promise<string> {
const pkgJson = await getPackageJson(__dirname);
return process.env['CLI_VERSION'] || pkgJson?.version || 'unknown';
let versionPromise: Promise<string> | undefined;
export function getVersion(): Promise<string> {
if (versionPromise) {
return versionPromise;
}
versionPromise = (async () => {
const pkgJson = await getPackageJson(__dirname);
return process.env['CLI_VERSION'] || pkgJson?.version || 'unknown';
})();
return versionPromise;
}
/** For testing purposes only */
export function resetVersionCache(): void {
versionPromise = undefined;
}
+9 -2
View File
@@ -245,6 +245,13 @@
"default": false,
"type": "boolean"
},
"showShortcutsHint": {
"title": "Show Shortcuts Hint",
"description": "Show the \"? for shortcuts\" hint above the input.",
"markdownDescription": "Show the \"? for shortcuts\" hint above the input.\n\n- Category: `UI`\n- Requires restart: `no`\n- Default: `true`",
"default": true,
"type": "boolean"
},
"hideBanner": {
"title": "Hide Banner",
"description": "Hide the application banner",
@@ -1432,8 +1439,8 @@
"enabled": {
"title": "Enable Tool Output Masking",
"description": "Enables tool output masking to save tokens.",
"markdownDescription": "Enables tool output masking to save tokens.\n\n- Category: `Experimental`\n- Requires restart: `yes`\n- Default: `false`",
"default": false,
"markdownDescription": "Enables tool output masking to save tokens.\n\n- Category: `Experimental`\n- Requires restart: `yes`\n- Default: `true`",
"default": true,
"type": "boolean"
},
"toolProtectionThreshold": {