Compare commits

..

7 Commits

Author SHA1 Message Date
Your Name 7677572662 ++ 2026-03-09 19:45:34 +00:00
Your Name d8d537cb64 hmm extra response 2026-03-09 03:48:29 +00:00
Your Name 9c7ed5c0b2 ++ 2026-03-09 03:31:32 +00:00
Your Name c8fb70edb8 ++ 2026-03-09 03:26:49 +00:00
Your Name c1f551f309 logs 2026-03-09 03:14:19 +00:00
Your Name 6d1c6a9b06 feat(core): distill tool 2026-03-09 03:05:54 +00:00
Your Name ca184a386e continuous session 2026-03-06 23:09:26 +00:00
326 changed files with 8842 additions and 10744 deletions
-99
View File
@@ -1,99 +0,0 @@
---
name: string-reviewer
description: >
Use this skill when asked to review text and user-facing strings within the codebase. It ensures that these strings follow rules on clarity,
usefulness, brevity and style.
---
# String Reviewer
## Instructions
Act as a Senior UX Writer. Look for user-facing strings that are too long,
unclear, or inconsistent. This includes inline text, error messages, and other
user-facing text.
Do NOT automatically change strings without user approval. You must only suggest
changes and do not attempt to rewrite them directly unless the user explicitly
asks you to do so.
## Core voice principles
The system prioritizes deterministic clarity over conversational fluff. We
provide telemetry, not etiquette, ensuring the user retains absolute agency..
1. **Deterministic clarity:** Distinguish between certain system/service states
(Cloud Billing, IAM, the System) and probabilistic AI analysis (Gemini).
2. **System transparency:** Replace "Loading..." with active technical telemetry
(e.g., Tracing stack traces...). Keep status updates under 5 words.
3. **Front-loaded actionability:** Always use the [Goal] + [Action] pattern.
Lead with intent so users can scan left-to-right.
4. **Agentic error recovery:** Every error must be a pivot point. Pair failures
with one-click recovery commands or suggested prompts.
5. **Contextual humility:** Reserve disclaimers and "be careful" warnings for P0
(destructive/irreversible) tasks only. Stop warning-fatigue.
## The writing checklist
Use this checklist to audit UI strings and AI responses.
### Identity and voice
- **Eliminate the "I":** Remove all first-person pronouns (I, me, my, mine).
- **Subject attribution:** Refer to the AI as Gemini and the infrastructure as
the - system or the CLI.
- **Active voice:** Ensure the subject (Gemini or the system) is clearly
performing the action.
- **Ownership rule:** Use the system for execution (doing) and Gemini for
analysis (thinking)
### Structural scannability
- **The skip test:** Do the first 3 words describe the users intent? If not,
rewrite.
- **Goal-first sequence:** Use the template: [To Accomplish X] + [Do Y].
- **The 5-word rule:** Keep status updates and loading states under 5 words.
- **Telemetry over etiquette:** Remove polite filler (Please wait, Thank you,
Certainly). Replace with raw data or progress indicators.
- **Micro-state cycles:** For tasks $> 3$ seconds, cycle through specific
sub-states (e.g., Parsing logs... ➔ Identifying patterns...) to show momentum.
### Technical accuracy and humility
- **Verb signal check:** Use deterministic verbs (is, will, must) for system
state/infrastructure.
- Use probabilistic verbs (suggests, appears, may, identifies) for AI output.
- **No 100% certainty:** Never attribute absolute certainty to model-generated
content.
- **Precision over fuzziness:** Use technical metrics (latency, tokens, compute) instead of "speed" or "cost."
- **Instructional warnings:** Every warning must include a specific corrective action (e.g., "Perform a dry-run first" or "Review line 42").
### Agentic error recovery
- **The one-step rule:** Pair every error message with exactly one immediate
path to a fix (command, link, or prompt).
- **Human-first:** Provide a human-readable explanation before machine error
codes (e.g., 404, 500).
- **Suggested prompts:** Offer specific text for the user to copy/click like
“Ask Gemini: 'Explain this port error.'”
### Use consistent terminology
Ensure all terminology aligns with the project [word
list](./references/word-list.md).
If a string uses a term marked "do not use" or "use with caution," provide a
correction based on the preferred terms.
## Ensure consistent style for settings
If `packages/cli/src/config/settingsSchema.ts` is modified, confirm labels and
descriptions specifically follow the unique [Settings
guidelines](./references/settings.md).
## Output format
When suggesting changes, always present your review using the following list
format. Do not provide suggestions outside of this list..
```
1. **{Rationale/Principle Violated}**
- ❌ "{incorrect phrase}"
- ✅ `"{corrected phrase}"`
```
@@ -1,28 +0,0 @@
# Settings
## Noun-First Labeling (Scannability)
Labels must start with the subject of the setting, not the action. This allows
users to scan for the feature they want to change.
- **Rule:** `[Noun]` `[Attribute/Action]`
- **Example:** `Show line numbers` becomes simply `Line numbers`
## Positive Boolean Logic (Cognitive Ease)
Eliminate "double negatives." Booleans should represent the presence of a
feature, not its absence.
- **Rule:** Replace `Disable {feature}` or `Hide {Feature}` with
`{Feature} enabled` or simply `{Feature}`.
- **Example:** Change "Disable auto update" to "Auto update".
- **Implementation:** Invert the boolean value in your config loader so true
always equals `On`
## Verb Stripping (Brevity)
Remove redundant leading verbs like "Enable," "Use," "Display," or "Show" unless
they are part of a specific technical term.
- **Rule**: If the label works without the verb, remove it
- **Example**: Change `Enable prompt completion` to `Prompt completion`
@@ -1,61 +0,0 @@
## Terms
### Preferred
- Use **create** when a user is creating or setting up something.
- Use **allow** instead of **may** to indicate that permission has been granted
to perform some action.
- Use **canceled**, not **cancelled**.
- Use **configure** to refer to the process of changing the attributes of a
feature, even if that includes turning on or off the feature.
- Use **delete** when the action being performed is destructive.
- Use **enable** for binary operations that turn a feature or API on. Use "turn
on" and "turn off" instead of "enable" and "disable" for other situations.
- Use **key combination** to refer to pressing multiple keys simultaneously.
- Use **key sequence** to refer to pressing multiple keys separately in order.
- Use **modify** to refer to something that has changed vs obtaining the latest
version of something.
- Use **remove** when the action being performed takes an item out of a larger
whole, but doesn't destroy the item itself.
- Use **set up** as a verb. Use **setup** as a noun or adjective.
- Use **show**. In general, use paired with **hide**.
- Use **sign in**, **sign out** as a verb. Use **sign-in** or **sign-out** as a
noun or adjective.
- Use **update** when you mean to obtain the latest version of something.
- Use **want** instead of **like** or **would like**.
#### Don't use
- Don't use **etc.** It's redundant. To convey that a series is incomplete,
introduce it with "such as" instead.
- Don't use **hostname**, use "host name" instead.
- Don't use **in order to**. It's too formal. "Before you can" is usually better
in UI text.
- Don't use **one or more**. Specify the quantity where possible. Use "at least
one" when the quantity is 1+ but you can't be sure of the number. Likewise,
use "at least one" when the user must choose a quantity of 1+.
- Don't use the terms **log in**, **log on**, **login**, **logout** or **log
out**.
- Don't use **like** or **would you like**. Use **want** instead. Better yet,
rephrase so that it's not referring to the user's emotional state, but rather
what is required.
#### Use with caution
- Avoid using **leverage**, especially as a verb. "Leverage" is considered a
buzzword largely devoid of meaning apart from the simpler "use".
- Avoid using **once** as a synonym for "after". Typically, when "once" is used
in this way, it is followed by a verb in the perfect tense.
- Don't use **e.g.** Use "example", "such as", "like", or "for example". The
phrase is always followed by a comma.
- Don't use **i.e.** unless absolutely essential to make text fit. Use "that is"
instead.
- Use **disable** for binary operations that turn a feature or API off. Use
"turn on" and "turn off" instead of "enable" and "disable" for other
situations. For UI elements that are not available, use "dimmed" instead of
"disabled".
- Use **please** only when you're asking the user to do something inconvenient,
not just following the instructions in a typical flow.
- Use **really** sparingly in such constructions as "Do you really want to..."
Because of the weight it puts on the decision, it should be used to confirm
actions that the user is extremely unlikely to make.
+1 -1
View File
@@ -169,7 +169,7 @@ jobs:
npm run test:ci --workspace @google/gemini-cli
else
# Explicitly list non-cli packages to ensure they are sharded correctly
npm run test:ci --workspace @google/gemini-cli-core --workspace @google/gemini-cli-a2a-server --workspace gemini-cli-vscode-ide-companion --workspace @google/gemini-cli-test-utils --if-present -- --coverage.enabled=false
npm run test:ci --workspace @google/gemini-cli-core --workspace @google/gemini-cli-a2a-server --workspace gemini-cli-vscode-ide-companion --workspace @google/gemini-cli-test-utils --if-present
npm run test:scripts
fi
+5 -3
View File
@@ -320,9 +320,11 @@ npm run lint
- Please adhere to the coding style, patterns, and conventions used throughout
the existing codebase.
- Consult [GEMINI.md](../GEMINI.md) (typically found in the project root) for
specific instructions related to AI-assisted development, including
conventions for React, comments, and Git usage.
- Consult
[GEMINI.md](https://github.com/google-gemini/gemini-cli/blob/main/GEMINI.md)
(typically found in the project root) for specific instructions related to
AI-assisted development, including conventions for React, comments, and Git
usage.
- **Imports:** Pay special attention to import paths. The project uses ESLint to
enforce restrictions on relative imports between packages.
+3 -3
View File
@@ -77,7 +77,7 @@ See [Releases](./docs/releases.md) for more details.
### Preview
New preview releases will be published each week at UTC 23:59 on Tuesdays. These
New preview releases will be published each week at UTC 2359 on Tuesdays. These
releases will not have been fully vetted and may contain regressions or other
outstanding issues. Please help us test and install with `preview` tag.
@@ -87,7 +87,7 @@ npm install -g @google/gemini-cli@preview
### Stable
- New stable releases will be published each week at UTC 20:00 on Tuesdays, this
- New stable releases will be published each week at UTC 2000 on Tuesdays, this
will be the full promotion of last week's `preview` release + any bug fixes
and validations. Use `latest` tag.
@@ -97,7 +97,7 @@ npm install -g @google/gemini-cli@latest
### Nightly
- New releases will be published each day at UTC 00:00. This will be all changes
- New releases will be published each day at UTC 0000. This will be all changes
from the main branch as represented at time of release. It should be assumed
there are pending validations and issues. Use `nightly` tag.
+71 -85
View File
@@ -1,6 +1,6 @@
# Preview release: v0.33.0-preview.4
# Preview release: v0.33.0-preview.1
Released: March 06, 2026
Released: March 04, 2026
Our preview release includes the latest, new, and experimental features. This
release may not be as stable as our [latest weekly release](latest.md).
@@ -29,173 +29,159 @@ npm install -g @google/gemini-cli@preview
## What's Changed
- fix(patch): cherry-pick 7ec477d to release/v0.33.0-preview.3-pr-21305 to patch
version v0.33.0-preview.3 and create version 0.33.0-preview.4 by
@gemini-cli-robot in
[#21349](https://github.com/google-gemini/gemini-cli/pull/21349)
- fix(patch): cherry-pick 0135b03 to release/v0.33.0-preview.2-pr-21171
[CONFLICTS] by @gemini-cli-robot in
[#21336](https://github.com/google-gemini/gemini-cli/pull/21336)
- fix(patch): cherry-pick 173376b to release/v0.33.0-preview.1-pr-21157 to patch
version v0.33.0-preview.1 and create version 0.33.0-preview.2 by
@gemini-cli-robot in
[#21300](https://github.com/google-gemini/gemini-cli/pull/21300)
- fix(patch): cherry-pick 173376b to release/v0.33.0-preview.1-pr-21157 to patch
version v0.33.0-preview.1 and create version 0.33.0-preview.2 by
@gemini-cli-robot in
[#21300](https://github.com/google-gemini/gemini-cli/pull/21300)
- fix(patch): cherry-pick 0659ad1 to release/v0.33.0-preview.0-pr-21042 to patch
version v0.33.0-preview.0 and create version 0.33.0-preview.1 by
@gemini-cli-robot in
[#21047](https://github.com/google-gemini/gemini-cli/pull/21047)
- Docs: Update model docs to remove Preview Features. by @jkcinouye in
* Docs: Update model docs to remove Preview Features. by @jkcinouye in
[#20084](https://github.com/google-gemini/gemini-cli/pull/20084)
- docs: fix typo in installation documentation by @AdityaSharma-Git3207 in
* docs: fix typo in installation documentation by @AdityaSharma-Git3207 in
[#20153](https://github.com/google-gemini/gemini-cli/pull/20153)
- docs: add Windows PowerShell equivalents for environments and scripting by
* docs: add Windows PowerShell equivalents for environments and scripting by
@scidomino in [#20333](https://github.com/google-gemini/gemini-cli/pull/20333)
- fix(core): parse raw ASCII buffer strings in Gaxios errors by @sehoon38 in
* fix(core): parse raw ASCII buffer strings in Gaxios errors by @sehoon38 in
[#20626](https://github.com/google-gemini/gemini-cli/pull/20626)
- chore(release): bump version to 0.33.0-nightly.20260227.ba149afa0 by @galz10
* chore(release): bump version to 0.33.0-nightly.20260227.ba149afa0 by @galz10
in [#20637](https://github.com/google-gemini/gemini-cli/pull/20637)
- fix(github): use robot PAT for automated PRs to pass CLA check by @galz10 in
* fix(github): use robot PAT for automated PRs to pass CLA check by @galz10 in
[#20641](https://github.com/google-gemini/gemini-cli/pull/20641)
- chore/release: bump version to 0.33.0-nightly.20260228.1ca5c05d0 by
* chore/release: bump version to 0.33.0-nightly.20260228.1ca5c05d0 by
@gemini-cli-robot in
[#20644](https://github.com/google-gemini/gemini-cli/pull/20644)
- Changelog for v0.31.0 by @gemini-cli-robot in
* Changelog for v0.31.0 by @gemini-cli-robot in
[#20634](https://github.com/google-gemini/gemini-cli/pull/20634)
- fix: use full paths for ACP diff payloads by @JagjeevanAK in
* fix: use full paths for ACP diff payloads by @JagjeevanAK in
[#19539](https://github.com/google-gemini/gemini-cli/pull/19539)
- Changelog for v0.32.0-preview.0 by @gemini-cli-robot in
* Changelog for v0.32.0-preview.0 by @gemini-cli-robot in
[#20627](https://github.com/google-gemini/gemini-cli/pull/20627)
- fix: acp/zed race condition between MCP initialisation and prompt by
* fix: acp/zed race condition between MCP initialisation and prompt by
@kartikangiras in
[#20205](https://github.com/google-gemini/gemini-cli/pull/20205)
- fix(cli): reset themeManager between tests to ensure isolation by
* fix(cli): reset themeManager between tests to ensure isolation by
@NTaylorMullen in
[#20598](https://github.com/google-gemini/gemini-cli/pull/20598)
- refactor(core): Extract tool parameter names as constants by @SandyTao520 in
* refactor(core): Extract tool parameter names as constants by @SandyTao520 in
[#20460](https://github.com/google-gemini/gemini-cli/pull/20460)
- fix(cli): resolve autoThemeSwitching when background hasn't changed but theme
* fix(cli): resolve autoThemeSwitching when background hasn't changed but theme
mismatches by @sehoon38 in
[#20706](https://github.com/google-gemini/gemini-cli/pull/20706)
- feat(skills): add github-issue-creator skill by @sehoon38 in
* feat(skills): add github-issue-creator skill by @sehoon38 in
[#20709](https://github.com/google-gemini/gemini-cli/pull/20709)
- fix(cli): allow sub-agent confirmation requests in UI while preventing
* fix(cli): allow sub-agent confirmation requests in UI while preventing
background flicker by @abhipatel12 in
[#20722](https://github.com/google-gemini/gemini-cli/pull/20722)
- Merge User and Agent Card Descriptions #20849 by @adamfweidman in
* Merge User and Agent Card Descriptions #20849 by @adamfweidman in
[#20850](https://github.com/google-gemini/gemini-cli/pull/20850)
- fix(core): reduce LLM-based loop detection false positives by @SandyTao520 in
* fix(core): reduce LLM-based loop detection false positives by @SandyTao520 in
[#20701](https://github.com/google-gemini/gemini-cli/pull/20701)
- fix(plan): deflake plan mode integration tests by @Adib234 in
* fix(plan): deflake plan mode integration tests by @Adib234 in
[#20477](https://github.com/google-gemini/gemini-cli/pull/20477)
- Add /unassign support by @scidomino in
* Add /unassign support by @scidomino in
[#20864](https://github.com/google-gemini/gemini-cli/pull/20864)
- feat(core): implement HTTP authentication support for A2A remote agents by
* feat(core): implement HTTP authentication support for A2A remote agents by
@SandyTao520 in
[#20510](https://github.com/google-gemini/gemini-cli/pull/20510)
- feat(core): centralize read_file limits and update gemini-3 description by
* feat(core): centralize read_file limits and update gemini-3 description by
@aishaneeshah in
[#20619](https://github.com/google-gemini/gemini-cli/pull/20619)
- Do not block CI on evals by @gundermanc in
* Do not block CI on evals by @gundermanc in
[#20870](https://github.com/google-gemini/gemini-cli/pull/20870)
- document node limitation for shift+tab by @scidomino in
* document node limitation for shift+tab by @scidomino in
[#20877](https://github.com/google-gemini/gemini-cli/pull/20877)
- Add install as an option when extension is selected. by @DavidAPierce in
* Add install as an option when extension is selected. by @DavidAPierce in
[#20358](https://github.com/google-gemini/gemini-cli/pull/20358)
- Update CODEOWNERS for README.md reviewers by @g-samroberts in
* Update CODEOWNERS for README.md reviewers by @g-samroberts in
[#20860](https://github.com/google-gemini/gemini-cli/pull/20860)
- feat(core): truncate large MCP tool output by @SandyTao520 in
* feat(core): truncate large MCP tool output by @SandyTao520 in
[#19365](https://github.com/google-gemini/gemini-cli/pull/19365)
- Subagent activity UX. by @gundermanc in
* Subagent activity UX. by @gundermanc in
[#17570](https://github.com/google-gemini/gemini-cli/pull/17570)
- style(cli) : Dialog pattern for /hooks Command by @AbdulTawabJuly in
* style(cli) : Dialog pattern for /hooks Command by @AbdulTawabJuly in
[#17930](https://github.com/google-gemini/gemini-cli/pull/17930)
- feat: redesign header to be compact with ASCII icon by @keithguerin in
* feat: redesign header to be compact with ASCII icon by @keithguerin in
[#18713](https://github.com/google-gemini/gemini-cli/pull/18713)
- fix(core): ensure subagents use qualified MCP tool names by @abhipatel12 in
* fix(core): ensure subagents use qualified MCP tool names by @abhipatel12 in
[#20801](https://github.com/google-gemini/gemini-cli/pull/20801)
- feat(core): support authenticated A2A agent card discovery by @SandyTao520 in
* feat(core): support authenticated A2A agent card discovery by @SandyTao520 in
[#20622](https://github.com/google-gemini/gemini-cli/pull/20622)
- refactor(cli): fully remove React anti patterns, improve type safety and fix
* refactor(cli): fully remove React anti patterns, improve type safety and fix
UX oversights in SettingsDialog.tsx by @psinha40898 in
[#18963](https://github.com/google-gemini/gemini-cli/pull/18963)
- Adding MCPOAuthProvider implementing the MCPSDK OAuthClientProvider by
* Adding MCPOAuthProvider implementing the MCPSDK OAuthClientProvider by
@Nayana-Parameswarappa in
[#20121](https://github.com/google-gemini/gemini-cli/pull/20121)
- feat(core): add tool name validation in TOML policy files by @allenhutchison
* feat(core): add tool name validation in TOML policy files by @allenhutchison
in [#19281](https://github.com/google-gemini/gemini-cli/pull/19281)
- docs: fix broken markdown links in main README.md by @Hamdanbinhashim in
* docs: fix broken markdown links in main README.md by @Hamdanbinhashim in
[#20300](https://github.com/google-gemini/gemini-cli/pull/20300)
- refactor(core): replace manual syncPlanModeTools with declarative policy rules
* refactor(core): replace manual syncPlanModeTools with declarative policy rules
by @jerop in [#20596](https://github.com/google-gemini/gemini-cli/pull/20596)
- fix(core): increase default headers timeout to 5 minutes by @gundermanc in
* fix(core): increase default headers timeout to 5 minutes by @gundermanc in
[#20890](https://github.com/google-gemini/gemini-cli/pull/20890)
- feat(admin): enable 30 day default retention for chat history & remove warning
* feat(admin): enable 30 day default retention for chat history & remove warning
by @skeshive in
[#20853](https://github.com/google-gemini/gemini-cli/pull/20853)
- feat(plan): support annotating plans with feedback for iteration by @Adib234
* feat(plan): support annotating plans with feedback for iteration by @Adib234
in [#20876](https://github.com/google-gemini/gemini-cli/pull/20876)
- Add some dos and don'ts to behavioral evals README. by @gundermanc in
* Add some dos and don'ts to behavioral evals README. by @gundermanc in
[#20629](https://github.com/google-gemini/gemini-cli/pull/20629)
- fix(core): skip telemetry logging for AbortError exceptions by @yunaseoul in
* fix(core): skip telemetry logging for AbortError exceptions by @yunaseoul in
[#19477](https://github.com/google-gemini/gemini-cli/pull/19477)
- fix(core): restrict "System: Please continue" invalid stream retry to Gemini 2
* fix(core): restrict "System: Please continue" invalid stream retry to Gemini 2
models by @SandyTao520 in
[#20897](https://github.com/google-gemini/gemini-cli/pull/20897)
- ci(evals): only run evals in CI if prompts or tools changed by @gundermanc in
* ci(evals): only run evals in CI if prompts or tools changed by @gundermanc in
[#20898](https://github.com/google-gemini/gemini-cli/pull/20898)
- Build binary by @aswinashok44 in
* Build binary by @aswinashok44 in
[#18933](https://github.com/google-gemini/gemini-cli/pull/18933)
- Code review fixes as a pr by @jacob314 in
* Code review fixes as a pr by @jacob314 in
[#20612](https://github.com/google-gemini/gemini-cli/pull/20612)
- fix(ci): handle empty APP_ID in stale PR closer by @bdmorgan in
* fix(ci): handle empty APP_ID in stale PR closer by @bdmorgan in
[#20919](https://github.com/google-gemini/gemini-cli/pull/20919)
- feat(cli): invert context window display to show usage by @keithguerin in
* feat(cli): invert context window display to show usage by @keithguerin in
[#20071](https://github.com/google-gemini/gemini-cli/pull/20071)
- fix(plan): clean up session directories and plans on deletion by @jerop in
* fix(plan): clean up session directories and plans on deletion by @jerop in
[#20914](https://github.com/google-gemini/gemini-cli/pull/20914)
- fix(core): enforce optionality for API response fields in code_assist by
* fix(core): enforce optionality for API response fields in code_assist by
@sehoon38 in [#20714](https://github.com/google-gemini/gemini-cli/pull/20714)
- feat(extensions): add support for plan directory in extension manifest by
* feat(extensions): add support for plan directory in extension manifest by
@mahimashanware in
[#20354](https://github.com/google-gemini/gemini-cli/pull/20354)
- feat(plan): enable built-in research subagents in plan mode by @Adib234 in
* feat(plan): enable built-in research subagents in plan mode by @Adib234 in
[#20972](https://github.com/google-gemini/gemini-cli/pull/20972)
- feat(agents): directly indicate auth required state by @adamfweidman in
* feat(agents): directly indicate auth required state by @adamfweidman in
[#20986](https://github.com/google-gemini/gemini-cli/pull/20986)
- fix(cli): wait for background auto-update before relaunching by @scidomino in
* fix(cli): wait for background auto-update before relaunching by @scidomino in
[#20904](https://github.com/google-gemini/gemini-cli/pull/20904)
- fix: pre-load @scripts/copy_files.js references from external editor prompts
* fix: pre-load @scripts/copy_files.js references from external editor prompts
by @kartikangiras in
[#20963](https://github.com/google-gemini/gemini-cli/pull/20963)
- feat(evals): add behavioral evals for ask_user tool by @Adib234 in
* feat(evals): add behavioral evals for ask_user tool by @Adib234 in
[#20620](https://github.com/google-gemini/gemini-cli/pull/20620)
- refactor common settings logic for skills,agents by @ishaanxgupta in
* refactor common settings logic for skills,agents by @ishaanxgupta in
[#17490](https://github.com/google-gemini/gemini-cli/pull/17490)
- Update docs-writer skill with new resource by @g-samroberts in
* Update docs-writer skill with new resource by @g-samroberts in
[#20917](https://github.com/google-gemini/gemini-cli/pull/20917)
- fix(cli): pin clipboardy to ~5.2.x by @scidomino in
* fix(cli): pin clipboardy to ~5.2.x by @scidomino in
[#21009](https://github.com/google-gemini/gemini-cli/pull/21009)
- feat: Implement slash command handling in ACP for
* feat: Implement slash command handling in ACP for
`/memory`,`/init`,`/extensions` and `/restore` by @sripasg in
[#20528](https://github.com/google-gemini/gemini-cli/pull/20528)
- Docs/add hooks reference by @AadithyaAle in
* Docs/add hooks reference by @AadithyaAle in
[#20961](https://github.com/google-gemini/gemini-cli/pull/20961)
- feat(plan): add copy subcommand to plan (#20491) by @ruomengz in
* feat(plan): add copy subcommand to plan (#20491) by @ruomengz in
[#20988](https://github.com/google-gemini/gemini-cli/pull/20988)
- fix(core): sanitize and length-check MCP tool qualified names by @abhipatel12
* fix(core): sanitize and length-check MCP tool qualified names by @abhipatel12
in [#20987](https://github.com/google-gemini/gemini-cli/pull/20987)
- Format the quota/limit style guide. by @g-samroberts in
* Format the quota/limit style guide. by @g-samroberts in
[#21017](https://github.com/google-gemini/gemini-cli/pull/21017)
- fix(core): send shell output to model on cancel by @devr0306 in
* fix(core): send shell output to model on cancel by @devr0306 in
[#20501](https://github.com/google-gemini/gemini-cli/pull/20501)
- remove hardcoded tiername when missing tier by @sehoon38 in
* remove hardcoded tiername when missing tier by @sehoon38 in
[#21022](https://github.com/google-gemini/gemini-cli/pull/21022)
- feat(acp): add set models interface by @skeshive in
* feat(acp): add set models interface by @skeshive in
[#20991](https://github.com/google-gemini/gemini-cli/pull/20991)
**Full Changelog**:
https://github.com/google-gemini/gemini-cli/compare/v0.32.0-preview.0...v0.33.0-preview.4
https://github.com/google-gemini/gemini-cli/compare/v0.32.0-preview.0...v0.33.0-preview.1
-15
View File
@@ -24,21 +24,6 @@ and parameters.
| -------- | ----------------- | ------------------------------------------------------------------------------------------------------------------ |
| `query` | string (variadic) | Positional prompt. Defaults to one-shot mode. Use `-i/--prompt-interactive` to execute and continue interactively. |
## Interactive commands
These commands are available within the interactive REPL.
| Command | Description |
| -------------------- | ---------------------------------------- |
| `/skills reload` | Reload discovered skills from disk |
| `/agents reload` | Reload the agent registry |
| `/commands reload` | Reload custom slash commands |
| `/memory reload` | Reload context files (e.g., `GEMINI.md`) |
| `/mcp reload` | Restart and reload MCP servers |
| `/extensions reload` | Reload all active extensions |
| `/help` | Show help for all commands |
| `/quit` | Exit the interactive session |
## CLI Options
| Option | Alias | Type | Default | Description |
+1 -1
View File
@@ -63,7 +63,7 @@ You can interact with the loaded context files by using the `/memory` command.
- **`/memory show`**: Displays the full, concatenated content of the current
hierarchical memory. This lets you inspect the exact instructional context
being provided to the model.
- **`/memory reload`**: Forces a re-scan and reload of all `GEMINI.md` files
- **`/memory refresh`**: Forces a re-scan and reload of all `GEMINI.md` files
from all configured locations.
- **`/memory add <text>`**: Appends your text to your global
`~/.gemini/GEMINI.md` file. This lets you add persistent memories on the fly.
-58
View File
@@ -1,58 +0,0 @@
# Notifications (experimental)
Gemini CLI can send system notifications to alert you when a session completes
or when it needs your attention, such as when it's waiting for you to approve a
tool call.
> **Note:** This is a preview feature currently under active development.
> Preview features may be available on the **Preview** channel or may need to be
> enabled under `/settings`.
Notifications are particularly useful when running long-running tasks or using
[Plan Mode](./plan-mode.md), letting you switch to other windows while Gemini
CLI works in the background.
## Requirements
Currently, system notifications are only supported on macOS.
### Terminal support
The CLI uses the OSC 9 terminal escape sequence to trigger system notifications.
This is supported by several modern terminal emulators. If your terminal does
not support OSC 9 notifications, Gemini CLI falls back to a system alert sound
to get your attention.
## Enable notifications
Notifications are disabled by default. You can enable them using the `/settings`
command or by updating your `settings.json` file.
1. Open the settings dialog by typing `/settings` in an interactive session.
2. Navigate to the **General** category.
3. Toggle the **Enable Notifications** setting to **On**.
Alternatively, add the following to your `settings.json`:
```json
{
"general": {
"enableNotifications": true
}
}
```
## Types of notifications
Gemini CLI sends notifications for the following events:
- **Action required:** Triggered when the model is waiting for user input or
tool approval. This helps you know when the CLI has paused and needs you to
intervene.
- **Session complete:** Triggered when a session finishes successfully. This is
useful for tracking the completion of automated tasks.
## Next steps
- Start planning with [Plan Mode](./plan-mode.md).
- Configure your experience with other [settings](./settings.md).
+2 -1
View File
@@ -102,7 +102,7 @@ they appear in the UI.
| UI Label | Setting | Description | Default |
| ------------------------------------ | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| Memory Discovery Max Dirs | `context.discoveryMaxDirs` | Maximum number of directories to search for memory. | `200` |
| Load Memory From Include Directories | `context.loadMemoryFromIncludeDirectories` | Controls how /memory reload loads GEMINI.md files. When true, include directories are scanned; when false, only the current directory is used. | `false` |
| Load Memory From Include Directories | `context.loadMemoryFromIncludeDirectories` | Controls how /memory refresh loads GEMINI.md files. When true, include directories are scanned; when false, only the current directory is used. | `false` |
| Respect .gitignore | `context.fileFiltering.respectGitIgnore` | Respect .gitignore files when searching. | `true` |
| Respect .geminiignore | `context.fileFiltering.respectGeminiIgnore` | Respect .geminiignore files when searching. | `true` |
| Enable Recursive File Search | `context.fileFiltering.enableRecursiveFileSearch` | Enable recursive file search functionality when completing @ references in the prompt. | `true` |
@@ -147,6 +147,7 @@ they appear in the UI.
| Plan | `experimental.plan` | Enable planning features (Plan Mode and tools). | `false` |
| Model Steering | `experimental.modelSteering` | Enable model steering (user hints) to guide the model during tool execution. | `false` |
| Direct Web Fetch | `experimental.directWebFetch` | Enable web fetch behavior that bypasses LLM summarization. | `false` |
| Enable Gemma Model Router | `experimental.gemmaModelRouter.enabled` | Enable the Gemma Model Router. Requires a local endpoint serving Gemma via the Gemini API using LiteRT-LM shim. | `false` |
### Skills
+2 -2
View File
@@ -101,8 +101,8 @@ The agent will:
- **Server won't start?** Try running the docker command manually in your
terminal to see if it prints an error (e.g., "image not found").
- **Tools not found?** Run `/mcp reload` to force the CLI to re-query the server
for its capabilities.
- **Tools not found?** Run `/mcp refresh` to force the CLI to re-query the
server for its capabilities.
## Next steps
+1 -1
View File
@@ -105,7 +105,7 @@ excellent for debugging why the agent might be ignoring a rule.
If you edit a `GEMINI.md` file while a session is running, the agent won't know
immediately. Force a reload with:
**Command:** `/memory reload`
**Command:** `/memory refresh`
## Best practices
+3 -4
View File
@@ -17,10 +17,9 @@ prefix.
**Example:** `!ls -la`
This executes `ls -la` immediately and prints the output to your terminal.
Gemini CLI also records the command and its output in the current session
context, so the model can reference it in follow-up prompts. Very large outputs
may be truncated.
This executes `ls -la` immediately and prints the output to your terminal. The
AI doesn't "see" this output unless you paste it back into the chat or use it in
a prompt.
### Scenario: Entering Shell mode
+1 -1
View File
@@ -75,7 +75,7 @@ Markdown file.
Users can manage subagents using the following commands within the Gemini CLI:
- `/agents list`: Displays all available local and remote subagents.
- `/agents reload`: Reloads the agent registry. Use this after adding or
- `/agents refresh`: Reloads the agent registry. Use this after adding or
modifying agent definition files.
- `/agents enable <agent_name>`: Enables a specific subagent.
- `/agents disable <agent_name>`: Disables a specific subagent.
+1 -1
View File
@@ -72,7 +72,7 @@ session's token usage, as well as your overall quota and usage for the supported
models.
For more information on the `/stats` command and its subcommands, see the
[Command Reference](../reference/commands.md#stats).
[Command Reference](../../reference/commands.md#stats).
## Next steps
+4 -4
View File
@@ -719,7 +719,7 @@ their corresponding top-level category object in your `settings.json` file.
- **Default:** `[]`
- **`context.loadMemoryFromIncludeDirectories`** (boolean):
- **Description:** Controls how /memory reload loads GEMINI.md files. When
- **Description:** Controls how /memory refresh loads GEMINI.md files. When
true, include directories are scanned; when false, only the current
directory is used.
- **Default:** `false`
@@ -1041,8 +1041,8 @@ their corresponding top-level category object in your `settings.json` file.
- **Requires restart:** Yes
- **`experimental.gemmaModelRouter.enabled`** (boolean):
- **Description:** Enable the Gemma Model Router (experimental). Requires a
local endpoint serving Gemma via the Gemini API using LiteRT-LM shim.
- **Description:** Enable the Gemma Model Router. Requires a local endpoint
serving Gemma via the Gemini API using LiteRT-LM shim.
- **Default:** `false`
- **Requires restart:** Yes
@@ -1705,7 +1705,7 @@ conventions and context.
loaded, allowing you to verify the hierarchy and content being used by the
AI.
- See the [Commands documentation](./commands.md#memory) for full details on
the `/memory` command and its sub-commands (`show` and `reload`).
the `/memory` command and its sub-commands (`show` and `refresh`).
By understanding and utilizing these configuration layers and the hierarchical
nature of context files, you can effectively manage the AI's memory and tailor
+84 -84
View File
@@ -8,119 +8,119 @@ available combinations.
#### Basic Controls
| Action | Keys |
| --------------------------------------------------------------- | ------------------- |
| Confirm the current selection or choice. | `Enter` |
| Dismiss dialogs or cancel the current focus. | `Esc`<br />`Ctrl+[` |
| Cancel the current request or quit the CLI when input is empty. | `Ctrl+C` |
| Exit the CLI when the input buffer is empty. | `Ctrl+D` |
| Action | Keys |
| --------------------------------------------------------------- | --------------------- |
| Confirm the current selection or choice. | `Enter` |
| Dismiss dialogs or cancel the current focus. | `Esc`<br />`Ctrl + [` |
| Cancel the current request or quit the CLI when input is empty. | `Ctrl + C` |
| Exit the CLI when the input buffer is empty. | `Ctrl + D` |
#### Cursor Movement
| Action | Keys |
| ------------------------------------------- | ------------------------------------------ |
| Move the cursor to the start of the line. | `Ctrl+A`<br />`Home` |
| Move the cursor to the end of the line. | `Ctrl+E`<br />`End` |
| Move the cursor up one line. | `Up` |
| Move the cursor down one line. | `Down` |
| Move the cursor one character to the left. | `Left` |
| Move the cursor one character to the right. | `Right`<br />`Ctrl+F` |
| Move the cursor one word to the left. | `Ctrl+Left`<br />`Alt+Left`<br />`Alt+B` |
| Move the cursor one word to the right. | `Ctrl+Right`<br />`Alt+Right`<br />`Alt+F` |
| Action | Keys |
| ------------------------------------------- | ------------------------------------------------------------ |
| Move the cursor to the start of the line. | `Ctrl + A`<br />`Home` |
| Move the cursor to the end of the line. | `Ctrl + E`<br />`End` |
| Move the cursor up one line. | `Up Arrow` |
| Move the cursor down one line. | `Down Arrow` |
| Move the cursor one character to the left. | `Left Arrow` |
| Move the cursor one character to the right. | `Right Arrow`<br />`Ctrl + F` |
| Move the cursor one word to the left. | `Ctrl + Left Arrow`<br />`Alt + Left Arrow`<br />`Alt + B` |
| Move the cursor one word to the right. | `Ctrl + Right Arrow`<br />`Alt + Right Arrow`<br />`Alt + F` |
#### Editing
| Action | Keys |
| ------------------------------------------------ | -------------------------------------------------------- |
| Delete from the cursor to the end of the line. | `Ctrl+K` |
| Delete from the cursor to the start of the line. | `Ctrl+U` |
| Clear all text in the input field. | `Ctrl+C` |
| Delete the previous word. | `Ctrl+Backspace`<br />`Alt+Backspace`<br />`Ctrl+W` |
| Delete the next word. | `Ctrl+Delete`<br />`Alt+Delete`<br />`Alt+D` |
| Delete the character to the left. | `Backspace`<br />`Ctrl+H` |
| Delete the character to the right. | `Delete`<br />`Ctrl+D` |
| Undo the most recent text edit. | `Cmd/Win+Z`<br />`Alt+Z` |
| Redo the most recent undone text edit. | `Ctrl+Shift+Z`<br />`Shift+Cmd/Win+Z`<br />`Alt+Shift+Z` |
| Action | Keys |
| ------------------------------------------------ | ---------------------------------------------------------------- |
| Delete from the cursor to the end of the line. | `Ctrl + K` |
| Delete from the cursor to the start of the line. | `Ctrl + U` |
| Clear all text in the input field. | `Ctrl + C` |
| Delete the previous word. | `Ctrl + Backspace`<br />`Alt + Backspace`<br />`Ctrl + W` |
| Delete the next word. | `Ctrl + Delete`<br />`Alt + Delete`<br />`Alt + D` |
| Delete the character to the left. | `Backspace`<br />`Ctrl + H` |
| Delete the character to the right. | `Delete`<br />`Ctrl + D` |
| Undo the most recent text edit. | `Cmd + Z`<br />`Alt + Z` |
| Redo the most recent undone text edit. | `Shift + Ctrl + Z`<br />`Shift + Cmd + Z`<br />`Shift + Alt + Z` |
#### Scrolling
| Action | Keys |
| ------------------------ | ----------------------------- |
| Scroll content up. | `Shift+Up` |
| Scroll content down. | `Shift+Down` |
| Scroll to the top. | `Ctrl+Home`<br />`Shift+Home` |
| Scroll to the bottom. | `Ctrl+End`<br />`Shift+End` |
| Scroll up by one page. | `Page Up` |
| Scroll down by one page. | `Page Down` |
| Action | Keys |
| ------------------------ | --------------------------------- |
| Scroll content up. | `Shift + Up Arrow` |
| Scroll content down. | `Shift + Down Arrow` |
| Scroll to the top. | `Ctrl + Home`<br />`Shift + Home` |
| Scroll to the bottom. | `Ctrl + End`<br />`Shift + End` |
| Scroll up by one page. | `Page Up` |
| Scroll down by one page. | `Page Down` |
#### History & Search
| Action | Keys |
| -------------------------------------------- | ------------ |
| Show the previous entry in history. | `Ctrl+P` |
| Show the next entry in history. | `Ctrl+N` |
| Start reverse search through history. | `Ctrl+R` |
| Show the previous entry in history. | `Ctrl + P` |
| Show the next entry in history. | `Ctrl + N` |
| Start reverse search through history. | `Ctrl + R` |
| Submit the selected reverse-search match. | `Enter` |
| Accept a suggestion while reverse searching. | `Tab` |
| Browse and rewind previous interactions. | `Double Esc` |
#### Navigation
| Action | Keys |
| -------------------------------------------------- | --------------- |
| Move selection up in lists. | `Up` |
| Move selection down in lists. | `Down` |
| Move up within dialog options. | `Up`<br />`K` |
| Move down within dialog options. | `Down`<br />`J` |
| Move to the next item or question in a dialog. | `Tab` |
| Move to the previous item or question in a dialog. | `Shift+Tab` |
| Action | Keys |
| -------------------------------------------------- | --------------------- |
| Move selection up in lists. | `Up Arrow` |
| Move selection down in lists. | `Down Arrow` |
| Move up within dialog options. | `Up Arrow`<br />`K` |
| Move down within dialog options. | `Down Arrow`<br />`J` |
| Move to the next item or question in a dialog. | `Tab` |
| Move to the previous item or question in a dialog. | `Shift + Tab` |
#### Suggestions & Completions
| Action | Keys |
| --------------------------------------- | -------------------- |
| Accept the inline suggestion. | `Tab`<br />`Enter` |
| Move to the previous completion option. | `Up`<br />`Ctrl+P` |
| Move to the next completion option. | `Down`<br />`Ctrl+N` |
| Expand an inline suggestion. | `Right` |
| Collapse an inline suggestion. | `Left` |
| Action | Keys |
| --------------------------------------- | ---------------------------- |
| Accept the inline suggestion. | `Tab`<br />`Enter` |
| Move to the previous completion option. | `Up Arrow`<br />`Ctrl + P` |
| Move to the next completion option. | `Down Arrow`<br />`Ctrl + N` |
| Expand an inline suggestion. | `Right Arrow` |
| Collapse an inline suggestion. | `Left Arrow` |
#### Text Input
| Action | Keys |
| ---------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| Submit the current prompt. | `Enter` |
| Insert a newline without submitting. | `Ctrl+Enter`<br />`Cmd/Win+Enter`<br />`Alt+Enter`<br />`Shift+Enter`<br />`Ctrl+J` |
| Open the current prompt or the plan in an external editor. | `Ctrl+X` |
| Paste from the clipboard. | `Ctrl+V`<br />`Cmd/Win+V`<br />`Alt+V` |
| Action | Keys |
| ---------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| Submit the current prompt. | `Enter` |
| Insert a newline without submitting. | `Ctrl + Enter`<br />`Cmd + Enter`<br />`Alt + Enter`<br />`Shift + Enter`<br />`Ctrl + J` |
| Open the current prompt or the plan in an external editor. | `Ctrl + X` |
| Paste from the clipboard. | `Ctrl + V`<br />`Cmd + V`<br />`Alt + V` |
#### App Controls
| Action | Keys |
| -------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
| Toggle detailed error information. | `F12` |
| Toggle the full TODO list. | `Ctrl+T` |
| Show IDE context details. | `Ctrl+G` |
| Toggle Markdown rendering. | `Alt+M` |
| Toggle copy mode when in alternate buffer mode. | `Ctrl+S` |
| Toggle YOLO (auto-approval) mode for tool calls. | `Ctrl+Y` |
| Cycle through approval modes: default (prompt), auto_edit (auto-approve edits), and plan (read-only). Plan mode is skipped when the agent is busy. | `Shift+Tab` |
| Expand and collapse blocks of content when not in alternate buffer mode. | `Ctrl+O` |
| Expand or collapse a paste placeholder when cursor is over placeholder. | `Ctrl+O` |
| Toggle current background shell visibility. | `Ctrl+B` |
| Toggle background shell list. | `Ctrl+L` |
| Kill the active background shell. | `Ctrl+K` |
| Confirm selection in background shell list. | `Enter` |
| Dismiss background shell list. | `Esc` |
| Move focus from background shell to Gemini. | `Shift+Tab` |
| Move focus from background shell list to Gemini. | `Tab` |
| Show warning when trying to move focus away from background shell. | `Tab` |
| Show warning when trying to move focus away from shell input. | `Tab` |
| Move focus from Gemini to the active shell. | `Tab` |
| Move focus from the shell back to Gemini. | `Shift+Tab` |
| Clear the terminal screen and redraw the UI. | `Ctrl+L` |
| Restart the application. | `R`<br />`Shift+R` |
| Suspend the CLI and move it to the background. | `Ctrl+Z` |
| Action | Keys |
| -------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| Toggle detailed error information. | `F12` |
| Toggle the full TODO list. | `Ctrl + T` |
| Show IDE context details. | `Ctrl + G` |
| Toggle Markdown rendering. | `Alt + M` |
| Toggle copy mode when in alternate buffer mode. | `Ctrl + S` |
| Toggle YOLO (auto-approval) mode for tool calls. | `Ctrl + Y` |
| Cycle through approval modes: default (prompt), auto_edit (auto-approve edits), and plan (read-only). Plan mode is skipped when the agent is busy. | `Shift + Tab` |
| Expand and collapse blocks of content when not in alternate buffer mode. | `Ctrl + O` |
| Expand or collapse a paste placeholder when cursor is over placeholder. | `Ctrl + O` |
| Toggle current background shell visibility. | `Ctrl + B` |
| Toggle background shell list. | `Ctrl + L` |
| Kill the active background shell. | `Ctrl + K` |
| Confirm selection in background shell list. | `Enter` |
| Dismiss background shell list. | `Esc` |
| Move focus from background shell to Gemini. | `Shift + Tab` |
| Move focus from background shell list to Gemini. | `Tab` |
| Show warning when trying to move focus away from background shell. | `Tab` |
| Show warning when trying to move focus away from shell input. | `Tab` |
| Move focus from Gemini to the active shell. | `Tab` |
| Move focus from the shell back to Gemini. | `Shift + Tab` |
| Clear the terminal screen and redraw the UI. | `Ctrl + L` |
| Restart the application. | `R`<br />`Shift + R` |
| Suspend the CLI and move it to the background. | `Ctrl + Z` |
<!-- KEYBINDINGS-AUTOGEN:END -->
+2 -29
View File
@@ -69,19 +69,6 @@ Learn more at
If you use up your initial number of requests, you can continue to benefit from
Gemini CLI by upgrading to one of the following subscriptions:
### Individuals
These tiers apply when you sign in with a personal account. To verify whether
you're on a personal account, visit
[Google One](https://one.google.com/about/plans?hl=en-US&g1_landing_page=0):
- If you are on a personal account, you will see your personal dashboard.
- If you are not on a personal account, you will see: "You're currently signed
in to your Google Workspace Account."
**Supported tiers:** _- Tiers not listed above, including Google AI Plus, are
not supported._
- [Google AI Pro and AI Ultra](https://gemini.google/subscriptions/). This is
recommended for individual developers. Quotas and pricing are based on a fixed
price subscription.
@@ -91,20 +78,6 @@ not supported._
Learn more at
[Gemini Code Assist Quotas and Limits](https://developers.google.com/gemini-code-assist/resources/quotas)
### Through your organization
These tiers are applicable when you are signing in with a Google Workspace
account.
- To verify your account type, visit
[the Google One page](https://one.google.com/about/plans?hl=en-US&g1_landing_page=0).
- You are on a workspace account if you see the message "You're currently signed
in to your Google Workspace Account".
**Supported tiers:** _- Tiers not listed above, including Workspace AI
Standard/Plus and AI Expanded, are not supported._
- [Workspace AI Ultra Access](https://workspace.google.com/products/ai-ultra/).
- [Purchase a Gemini Code Assist Subscription through Google Cloud](https://cloud.google.com/gemini/docs/codeassist/overview).
Quotas and pricing are based on a fixed price subscription with assigned
@@ -120,7 +93,7 @@ Standard/Plus and AI Expanded, are not supported._
- Model requests will be made across the Gemini model family as determined by
Gemini CLI.
[Learn more about Gemini Code Assist license limits](https://developers.google.com/gemini-code-assist/resources/quotas#quotas-for-agent-mode-gemini-cli).
[Learn more about Gemini Code Assist Standard and Enterprise license limits](https://developers.google.com/gemini-code-assist/resources/quotas#quotas-for-agent-mode-gemini-cli).
## Pay as you go
@@ -178,7 +151,7 @@ session's token usage, as well as information about the limits associated with
your current quota.
For more information on the `/stats` command and its subcommands, see the
[Command Reference](../reference/commands.md#stats).
[Command Reference](../../reference/commands.md#stats).
A summary of model usage is also presented on exit at the end of a session.
-5
View File
@@ -106,11 +106,6 @@
{ "label": "MCP servers", "slug": "docs/tools/mcp-server" },
{ "label": "Model routing", "slug": "docs/cli/model-routing" },
{ "label": "Model selection", "slug": "docs/cli/model" },
{
"label": "Notifications",
"badge": "🔬",
"slug": "docs/cli/notifications"
},
{ "label": "Plan mode", "badge": "🔬", "slug": "docs/cli/plan-mode" },
{
"label": "Subagents",
+1 -11
View File
@@ -132,16 +132,7 @@ export default tseslint.config(
'no-cond-assign': 'error',
'no-debugger': 'error',
'no-duplicate-case': 'error',
'no-restricted-syntax': [
'error',
...commonRestrictedSyntaxRules,
{
selector:
'UnaryExpression[operator="typeof"] > MemberExpression[computed=true][property.type="Literal"]',
message:
'Do not use typeof to check object properties. Define a TypeScript interface and a type guard function instead.',
},
],
'no-restricted-syntax': ['error', ...commonRestrictedSyntaxRules],
'no-unsafe-finally': 'error',
'no-unused-expressions': 'off', // Disable base rule
'@typescript-eslint/no-unused-expressions': [
@@ -272,7 +263,6 @@ export default tseslint.config(
...vitest.configs.recommended.rules,
'vitest/expect-expect': 'off',
'vitest/no-commented-out-tests': 'off',
'no-restricted-syntax': ['error', ...commonRestrictedSyntaxRules],
},
},
{
-56
View File
@@ -1,56 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { expect } from 'vitest';
import { evalTest } from './test-helper.js';
const MUTATION_AGENT_DEFINITION = `---
name: mutation-agent
description: An agent that modifies the workspace (writes, deletes, git operations, etc).
max_turns: 1
tools:
- write_file
---
You are the mutation agent. Do the mutation requested.
`;
describe('concurrency safety eval test cases', () => {
evalTest('USUALLY_PASSES', {
name: 'mutation agents are run in parallel when explicitly requested',
params: {
settings: {
experimental: {
enableAgents: true,
},
},
},
prompt:
'Update A.txt to say "A" and update B.txt to say "B". Delegate these tasks to two separate mutation-agent subagents. You MUST run these subagents in parallel at the same time.',
files: {
'.gemini/agents/mutation-agent.md': MUTATION_AGENT_DEFINITION,
},
assert: async (rig) => {
const logs = rig.readToolLogs();
const mutationCalls = logs.filter(
(log) => log.toolRequest?.name === 'mutation-agent',
);
expect(
mutationCalls.length,
'Agent should have called the mutation-agent at least twice',
).toBeGreaterThanOrEqual(2);
const firstPromptId = mutationCalls[0].toolRequest.prompt_id;
const secondPromptId = mutationCalls[1].toolRequest.prompt_id;
expect(
firstPromptId,
'mutation agents should be called in parallel (same turn / prompt_ids) when explicitly requested',
).toEqual(secondPromptId);
},
});
});
+49
View File
@@ -0,0 +1,49 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, expect } from 'vitest';
import { appEvalTest } from './app-test-helper.js';
describe('Continuous Session Behavioral Evals', () => {
appEvalTest('ALWAYS_PASSES', {
name: 'Continuous Session: Model preserves technical state across manual compression',
configOverrides: {
excludeTools: ['run_shell_command', 'write_file'],
modelSteering: true,
},
files: {
'src/offender.ts': `// Line 1
// Line 2
const x = process.env.SECRET_KEY; // Line 3
// Line 4`,
},
prompt:
'Audit src/ for process.env usage. When you find one, checkpoint your state with the line number and then manually compress the context to clear your history before giving me the final report.',
setup: async (rig) => {
// Pause on our new tools to observe the workflow
rig.setBreakpoint(['checkpoint_state', 'compress']);
},
assert: async (rig) => {
// 1. Wait for Checkpoint
await rig.waitForPendingConfirmation('checkpoint_state', 45000);
await rig.resolveAwaitedTool();
// 2. Wait for Compression
await rig.waitForPendingConfirmation('compress', 45000);
await rig.resolveAwaitedTool();
// 3. Final Verification
// The model should report the finding even though the initial read_file
// is gone from history due to compression.
await rig.waitForOutput(/process\.env\.SECRET_KEY/i, 60000);
//await rig.waitForOutput(/Line 3/i, 60000);
await rig.waitForIdle(30000);
const output = rig.getStaticOutput();
expect(output).toContain('SECRET_KEY');
},
});
});
+44
View File
@@ -0,0 +1,44 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, expect } from 'vitest';
import { appEvalTest } from './app-test-helper.js';
describe('Head Entropy Behavioral Evals', () => {
appEvalTest('ALWAYS_PASSES', {
name: 'Head Entropy: Model distills a high-noise tool output',
configOverrides: {
modelSteering: true,
continuousSession: true,
},
files: {
'src/big-file.ts': '// NOISE\n'.repeat(100) + 'const SECRET = "SIGNAL";\n' + '// NOISE\n'.repeat(100),
},
prompt:
'Grep for SECRET in src/. If the result is very noisy, use distill_result to replace it with just the signal you found before continuing.',
setup: async (rig) => {
// Pause on our new tools to observe the workflow
rig.setBreakpoint(['grep_search', 'distill_result']);
},
assert: async (rig) => {
// 1. Wait for Grep
await rig.waitForPendingConfirmation('grep_search', 45000);
await rig.resolveAwaitedTool();
// 2. Wait for Distillation
await rig.waitForPendingConfirmation('distill_result', 45000);
await rig.resolveAwaitedTool();
// 3. Final Verification
await rig.waitForOutput(/SIGNAL/i, 60000);
await rig.waitForIdle(30000);
const output = rig.getStaticOutput();
expect(output).toContain('SIGNAL');
expect(output).not.toContain('NOISE'); // Should be elided/replaced
},
});
});
-26
View File
@@ -71,30 +71,4 @@ describe('interactive_commands', () => {
).toMatch(/(?:^|\s)(--yes|-y|--template\s+\S+)(?:\s|$|\\|")/);
},
});
/**
* Validates that the agent does not hang when creating a vite app.
*/
evalTest('ALWAYS_PASSES', {
name: 'should not hang when creating a vite app',
prompt: 'create a hello world app with vite',
files: {
//'.npmrc': 'cache=./.npm-cache',
},
assert: async (rig, result) => {
await rig.waitForToolCall('run_shell_command');
const logs = rig.readToolLogs();
const viteCall = logs.find(
(l) =>
l.toolRequest.name === 'run_shell_command' &&
l.toolRequest.args.toLowerCase().includes('vite'),
);
expect(viteCall, 'Agent should have called vite').toBeDefined();
expect(
viteCall?.toolRequest.success,
'Vite tool call should finish successfully without hanging',
).toBe(true);
},
});
});
-1
View File
@@ -112,7 +112,6 @@ export function evalTest(policy: EvalPolicy, evalCase: EvalCase) {
// commands.
execSync('git config core.editor "true"', execOptions);
execSync('git config core.pager "cat"', execOptions);
execSync('git config commit.gpgsign false', execOptions);
execSync('git add .', execOptions);
execSync('git commit --allow-empty -m "Initial commit"', execOptions);
}
+2 -2
View File
@@ -104,7 +104,7 @@ describe('extension reloading', () => {
return (
output.includes(
'test-server (from test-extension) - Ready (1 tool)',
) && output.includes('- mcp_test-server_hello')
) && output.includes('- hello')
);
},
30000, // 30s timeout
@@ -148,7 +148,7 @@ describe('extension reloading', () => {
return (
output.includes(
'test-server (from test-extension) - Ready (1 tool)',
) && output.includes('- mcp_test-server_goodbye')
) && output.includes('- goodbye')
);
},
30000,
+9 -19
View File
@@ -182,22 +182,14 @@ describe('Hooks Agent Flow', () => {
);
const afterAgentScript = `
const fs = require('fs');
const input = JSON.parse(fs.readFileSync(0, 'utf-8'));
if (input.stop_hook_active) {
// Retry turn: allow execution to proceed (breaks the loop)
console.log(JSON.stringify({ decision: 'allow' }));
} else {
// First call: block and clear context to trigger the retry
console.log(JSON.stringify({
decision: 'block',
reason: 'Security policy triggered',
hookSpecificOutput: {
hookEventName: 'AfterAgent',
clearContext: true
}
}));
}
console.log(JSON.stringify({
decision: 'block',
reason: 'Security policy triggered',
hookSpecificOutput: {
hookEventName: 'AfterAgent',
clearContext: true
}
}));
`;
const afterAgentScriptPath = rig.createScript(
'after_agent_clear.cjs',
@@ -206,10 +198,8 @@ describe('Hooks Agent Flow', () => {
rig.setup('should process clearContext in AfterAgent hook output', {
settings: {
hooksConfig: {
enabled: true,
},
hooks: {
enabled: true,
BeforeModel: [
{
hooks: [
@@ -1,3 +1,2 @@
{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"Hi there!"}],"role":"model"},"finishReason":"STOP","index":0}]}]}
{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"Clarification: I am a bot."}],"role":"model"},"finishReason":"STOP","index":0}]}]}
{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"Security policy triggered"}],"role":"model"},"finishReason":"STOP","index":0}]}]}
+2 -15
View File
@@ -68,7 +68,6 @@ async function verifyToolExecution(
promptCommand: PromptCommand,
result: string,
expectAllowed: boolean,
expectedDenialString?: string,
) {
const log = await waitForToolCallLog(
rig,
@@ -79,13 +78,10 @@ async function verifyToolExecution(
if (expectAllowed) {
expect(log!.toolRequest.success).toBe(true);
expect(result).not.toContain('Tool execution denied by policy');
expect(result).not.toContain(`Tool "${promptCommand.tool}" not found`);
expect(result).toContain(promptCommand.expectedSuccessResult);
} else {
expect(log!.toolRequest.success).toBe(false);
expect(result).toContain(
expectedDenialString || 'Tool execution denied by policy',
);
expect(result).toContain('Tool execution denied by policy');
expect(result).toContain(promptCommand.expectedFailureResult);
}
}
@@ -96,7 +92,6 @@ interface TestCase {
promptCommand: PromptCommand;
policyContent?: string;
expectAllowed: boolean;
expectedDenialString?: string;
}
describe('Policy Engine Headless Mode', () => {
@@ -130,13 +125,7 @@ describe('Policy Engine Headless Mode', () => {
approvalMode: 'default',
});
await verifyToolExecution(
rig,
tc.promptCommand,
result,
tc.expectAllowed,
tc.expectedDenialString,
);
await verifyToolExecution(rig, tc.promptCommand, result, tc.expectAllowed);
};
const testCases = [
@@ -145,7 +134,6 @@ describe('Policy Engine Headless Mode', () => {
responsesFile: 'policy-headless-shell-denied.responses',
promptCommand: ECHO_PROMPT,
expectAllowed: false,
expectedDenialString: 'Tool "run_shell_command" not found',
},
{
name: 'should allow ASK_USER tools in headless mode if explicitly allowed via policy file',
@@ -190,7 +178,6 @@ describe('Policy Engine Headless Mode', () => {
priority = 100
`,
expectAllowed: false,
expectedDenialString: 'Tool execution denied by policy',
},
];
-2
View File
@@ -832,9 +832,7 @@ export class Task {
if (
part.kind !== 'data' ||
!part.data ||
// eslint-disable-next-line no-restricted-syntax
typeof part.data['callId'] !== 'string' ||
// eslint-disable-next-line no-restricted-syntax
typeof part.data['outcome'] !== 'string'
) {
return false;
+1
View File
@@ -120,6 +120,7 @@ export async function loadConfig(
await loadServerHierarchicalMemory(
workspaceDir,
[workspaceDir],
false,
fileService,
extensionLoader,
folderTrust,
+11 -28
View File
@@ -319,43 +319,26 @@ export class UninstallExtensionCommand implements Command {
};
}
const all = args.includes('--all');
const names = args.filter((a) => !a.startsWith('--')).map((a) => a.trim());
if (!all && names.length === 0) {
const name = args.join(' ').trim();
if (!name) {
return {
name: this.name,
data: `Usage: /extensions uninstall <extension-names...>|--all`,
data: `Usage: /extensions uninstall <extension-name>`,
};
}
let namesToUninstall: string[] = [];
if (all) {
namesToUninstall = extensionLoader.getExtensions().map((ext) => ext.name);
} else {
namesToUninstall = names;
}
if (namesToUninstall.length === 0) {
try {
await extensionLoader.uninstallExtension(name, false);
return {
name: this.name,
data: all ? 'No extensions installed.' : 'No extension name provided.',
data: `Extension "${name}" uninstalled successfully.`,
};
} catch (error) {
return {
name: this.name,
data: `Failed to uninstall extension "${name}": ${getErrorMessage(error)}`,
};
}
const output: string[] = [];
for (const extensionName of namesToUninstall) {
try {
await extensionLoader.uninstallExtension(extensionName, false);
output.push(`Extension "${extensionName}" uninstalled successfully.`);
} catch (error) {
output.push(
`Failed to uninstall extension "${extensionName}": ${getErrorMessage(error)}`,
);
}
}
return { name: this.name, data: output.join('\n') };
}
}
@@ -28,7 +28,6 @@ import { getErrorMessage } from '../../utils/errors.js';
// Hoisted mocks - these survive vi.clearAllMocks()
const mockUninstallExtension = vi.hoisted(() => vi.fn());
const mockLoadExtensions = vi.hoisted(() => vi.fn());
const mockGetExtensions = vi.hoisted(() => vi.fn());
// Mock dependencies with hoisted functions
vi.mock('../../config/extension-manager.js', async (importOriginal) => {
@@ -39,7 +38,6 @@ vi.mock('../../config/extension-manager.js', async (importOriginal) => {
ExtensionManager: vi.fn().mockImplementation(() => ({
uninstallExtension: mockUninstallExtension,
loadExtensions: mockLoadExtensions,
getExtensions: mockGetExtensions,
setRequestConsent: vi.fn(),
setRequestSetting: vi.fn(),
})),
@@ -95,7 +93,6 @@ describe('extensions uninstall command', () => {
afterEach(() => {
mockLoadExtensions.mockClear();
mockUninstallExtension.mockClear();
mockGetExtensions.mockClear();
vi.clearAllMocks();
});
@@ -148,41 +145,6 @@ describe('extensions uninstall command', () => {
mockCwd.mockRestore();
});
it('should uninstall all extensions when --all flag is used', async () => {
mockLoadExtensions.mockResolvedValue(undefined);
mockUninstallExtension.mockResolvedValue(undefined);
mockGetExtensions.mockReturnValue([{ name: 'ext1' }, { name: 'ext2' }]);
const mockCwd = vi.spyOn(process, 'cwd').mockReturnValue('/test/dir');
await handleUninstall({ all: true });
expect(mockUninstallExtension).toHaveBeenCalledTimes(2);
expect(mockUninstallExtension).toHaveBeenCalledWith('ext1', false);
expect(mockUninstallExtension).toHaveBeenCalledWith('ext2', false);
expect(emitConsoleLog).toHaveBeenCalledWith(
'log',
'Extension "ext1" successfully uninstalled.',
);
expect(emitConsoleLog).toHaveBeenCalledWith(
'log',
'Extension "ext2" successfully uninstalled.',
);
mockCwd.mockRestore();
});
it('should log a message if no extensions are installed and --all flag is used', async () => {
mockLoadExtensions.mockResolvedValue(undefined);
mockGetExtensions.mockReturnValue([]);
const mockCwd = vi.spyOn(process, 'cwd').mockReturnValue('/test/dir');
await handleUninstall({ all: true });
expect(mockUninstallExtension).not.toHaveBeenCalled();
expect(emitConsoleLog).toHaveBeenCalledWith(
'log',
'No extensions currently installed.',
);
mockCwd.mockRestore();
});
it('should report errors for failed uninstalls but continue with others', async () => {
mockLoadExtensions.mockResolvedValue(undefined);
const mockCwd = vi.spyOn(process, 'cwd').mockReturnValue('/test/dir');
@@ -274,14 +236,13 @@ describe('extensions uninstall command', () => {
const command = uninstallCommand;
it('should have correct command and describe', () => {
expect(command.command).toBe('uninstall [names..]');
expect(command.command).toBe('uninstall <names..>');
expect(command.describe).toBe('Uninstalls one or more extensions.');
});
describe('builder', () => {
interface MockYargs {
positional: Mock;
option: Mock;
check: Mock;
}
@@ -289,12 +250,11 @@ describe('extensions uninstall command', () => {
beforeEach(() => {
yargsMock = {
positional: vi.fn().mockReturnThis(),
option: vi.fn().mockReturnThis(),
check: vi.fn().mockReturnThis(),
};
});
it('should configure arguments and options', () => {
it('should configure positional argument', () => {
(command.builder as (yargs: Argv) => Argv)(
yargsMock as unknown as Argv,
);
@@ -304,31 +264,18 @@ describe('extensions uninstall command', () => {
type: 'string',
array: true,
});
expect(yargsMock.option).toHaveBeenCalledWith('all', {
type: 'boolean',
describe: 'Uninstall all installed extensions.',
default: false,
});
expect(yargsMock.check).toHaveBeenCalled();
});
it('check function should throw for missing names and no --all flag', () => {
it('check function should throw for missing names', () => {
(command.builder as (yargs: Argv) => Argv)(
yargsMock as unknown as Argv,
);
const checkCallback = yargsMock.check.mock.calls[0][0];
expect(() => checkCallback({ names: [], all: false })).toThrow(
'Please include at least one extension name to uninstall as a positional argument, or use the --all flag.',
expect(() => checkCallback({ names: [] })).toThrow(
'Please include at least one extension name to uninstall as a positional argument.',
);
});
it('check function should pass if --all flag is used even without names', () => {
(command.builder as (yargs: Argv) => Argv)(
yargsMock as unknown as Argv,
);
const checkCallback = yargsMock.check.mock.calls[0][0];
expect(() => checkCallback({ names: [], all: true })).not.toThrow();
});
});
it('handler should call handleUninstall', async () => {
@@ -336,17 +283,10 @@ describe('extensions uninstall command', () => {
mockUninstallExtension.mockResolvedValue(undefined);
const mockCwd = vi.spyOn(process, 'cwd').mockReturnValue('/test/dir');
interface TestArgv {
names?: string[];
all?: boolean;
_: string[];
$0: string;
names: string[];
[key: string]: unknown;
}
const argv: TestArgv = {
names: ['my-extension'],
all: false,
_: [],
$0: '',
};
const argv: TestArgv = { names: ['my-extension'], _: [], $0: '' };
await (command.handler as unknown as (args: TestArgv) => Promise<void>)(
argv,
);
@@ -14,8 +14,7 @@ import { promptForSetting } from '../../config/extensions/extensionSettings.js';
import { exitCli } from '../utils.js';
interface UninstallArgs {
names?: string[]; // can be extension names or source URLs.
all?: boolean;
names: string[]; // can be extension names or source URLs.
}
export async function handleUninstall(args: UninstallArgs) {
@@ -29,24 +28,8 @@ export async function handleUninstall(args: UninstallArgs) {
});
await extensionManager.loadExtensions();
let namesToUninstall: string[] = [];
if (args.all) {
namesToUninstall = extensionManager
.getExtensions()
.map((ext) => ext.name);
} else if (args.names) {
namesToUninstall = [...new Set(args.names)];
}
if (namesToUninstall.length === 0) {
if (args.all) {
debugLogger.log('No extensions currently installed.');
}
return;
}
const errors: Array<{ name: string; error: string }> = [];
for (const name of namesToUninstall) {
for (const name of [...new Set(args.names)]) {
try {
await extensionManager.uninstallExtension(name, false);
debugLogger.log(`Extension "${name}" successfully uninstalled.`);
@@ -68,7 +51,7 @@ export async function handleUninstall(args: UninstallArgs) {
}
export const uninstallCommand: CommandModule = {
command: 'uninstall [names..]',
command: 'uninstall <names..>',
describe: 'Uninstalls one or more extensions.',
builder: (yargs) =>
yargs
@@ -78,15 +61,10 @@ export const uninstallCommand: CommandModule = {
type: 'string',
array: true,
})
.option('all', {
type: 'boolean',
describe: 'Uninstall all installed extensions.',
default: false,
})
.check((argv) => {
if (!argv.all && (!argv.names || argv.names.length === 0)) {
if (!argv.names || argv.names.length === 0) {
throw new Error(
'Please include at least one extension name to uninstall as a positional argument, or use the --all flag.',
'Please include at least one extension name to uninstall as a positional argument.',
);
}
return true;
@@ -94,9 +72,7 @@ export const uninstallCommand: CommandModule = {
handler: async (argv) => {
await handleUninstall({
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
names: argv['names'] as string[] | undefined,
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
all: argv['all'] as boolean,
names: argv['names'] as string[],
});
await exitCli();
},
@@ -79,7 +79,6 @@ function migrateClaudeHook(claudeHook: unknown): unknown {
migrated['command'] = hook['command'];
// Replace CLAUDE_PROJECT_DIR with GEMINI_PROJECT_DIR in command
// eslint-disable-next-line no-restricted-syntax
if (typeof migrated['command'] === 'string') {
migrated['command'] = migrated['command'].replace(
/\$CLAUDE_PROJECT_DIR/g,
@@ -94,7 +93,6 @@ function migrateClaudeHook(claudeHook: unknown): unknown {
}
// Map timeout field (Claude uses seconds, Gemini uses seconds)
// eslint-disable-next-line no-restricted-syntax
if ('timeout' in hook && typeof hook['timeout'] === 'number') {
migrated['timeout'] = hook['timeout'];
}
@@ -142,7 +140,6 @@ function migrateClaudeHooks(claudeConfig: unknown): Record<string, unknown> {
// Transform matcher
if (
'matcher' in definition &&
// eslint-disable-next-line no-restricted-syntax
typeof definition['matcher'] === 'string'
) {
migratedDef['matcher'] = transformMatcher(definition['matcher']);
+7 -6
View File
@@ -116,16 +116,14 @@ vi.mock('@google/gemini-cli-core', async () => {
(
cwd,
dirs,
debug,
fileService,
extensionLoader: ExtensionLoader,
_folderTrust,
_importFormat,
_fileFilteringOptions,
_maxDirs,
) => {
const extensionPaths =
extensionLoader?.getExtensions?.()?.flatMap((e) => e.contextFiles) ||
[];
const extensionPaths = extensionLoader
.getExtensions()
.flatMap((e) => e.contextFiles);
return Promise.resolve({
memoryContent: extensionPaths.join(',') || '',
fileCount: extensionPaths?.length || 0,
@@ -849,6 +847,7 @@ describe('Hierarchical Memory Loading (config.ts) - Placeholder Suite', () => {
expect(ServerConfig.loadServerHierarchicalMemory).toHaveBeenCalledWith(
expect.any(String),
[],
false,
expect.any(Object),
expect.any(ExtensionManager),
true,
@@ -877,6 +876,7 @@ describe('Hierarchical Memory Loading (config.ts) - Placeholder Suite', () => {
expect(ServerConfig.loadServerHierarchicalMemory).toHaveBeenCalledWith(
expect.any(String),
[includeDir],
false,
expect.any(Object),
expect.any(ExtensionManager),
true,
@@ -904,6 +904,7 @@ describe('Hierarchical Memory Loading (config.ts) - Placeholder Suite', () => {
expect(ServerConfig.loadServerHierarchicalMemory).toHaveBeenCalledWith(
expect.any(String),
[],
false,
expect.any(Object),
expect.any(ExtensionManager),
true,
+2 -1
View File
@@ -499,6 +499,7 @@ export async function loadCliConfig(
settings.context?.loadMemoryFromIncludeDirectories || false
? includeDirectories
: [],
debugMode,
fileService,
extensionManager,
trustedFolder,
@@ -776,6 +777,7 @@ export async function loadCliConfig(
skillsSupport: settings.skills?.enabled ?? true,
disabledSkills: settings.skills?.disabled,
experimentalJitContext: settings.experimental?.jitContext,
continuousSession: settings.experimental?.continuousSession,
modelSteering: settings.experimental?.modelSteering,
toolOutputMasking: settings.experimental?.toolOutputMasking,
noBrowser: !!process.env['NO_BROWSER'],
@@ -805,7 +807,6 @@ export async function loadCliConfig(
fakeResponses: argv.fakeResponses,
recordResponses: argv.recordResponses,
retryFetchErrors: settings.general?.retryFetchErrors,
billing: settings.billing,
maxAttempts: settings.general?.maxAttempts,
ptyInfo: ptyInfo?.name,
disableLLMCorrection: settings.tools?.disableLLMCorrection,
@@ -93,13 +93,13 @@ describe('Policy Engine Integration Tests', () => {
// Tools from allowed server should be allowed
// Tools from allowed server should be allowed
expect(
(await engine.check({ name: 'mcp_allowed-server_tool1' }, undefined))
(await engine.check({ name: 'allowed-server__tool1' }, undefined))
.decision,
).toBe(PolicyDecision.ALLOW);
expect(
(
await engine.check(
{ name: 'mcp_allowed-server_another_tool' },
{ name: 'allowed-server__another_tool' },
undefined,
)
).decision,
@@ -107,13 +107,13 @@ describe('Policy Engine Integration Tests', () => {
// Tools from trusted server should be allowed
expect(
(await engine.check({ name: 'mcp_trusted-server_tool1' }, undefined))
(await engine.check({ name: 'trusted-server__tool1' }, undefined))
.decision,
).toBe(PolicyDecision.ALLOW);
expect(
(
await engine.check(
{ name: 'mcp_trusted-server_special_tool' },
{ name: 'trusted-server__special_tool' },
undefined,
)
).decision,
@@ -121,17 +121,17 @@ describe('Policy Engine Integration Tests', () => {
// Tools from blocked server should be denied
expect(
(await engine.check({ name: 'mcp_blocked-server_tool1' }, undefined))
(await engine.check({ name: 'blocked-server__tool1' }, undefined))
.decision,
).toBe(PolicyDecision.DENY);
expect(
(await engine.check({ name: 'mcp_blocked-server_any_tool' }, undefined))
(await engine.check({ name: 'blocked-server__any_tool' }, undefined))
.decision,
).toBe(PolicyDecision.DENY);
// Tools from unknown servers should use default
expect(
(await engine.check({ name: 'mcp_unknown-server_tool' }, undefined))
(await engine.check({ name: 'unknown-server__tool' }, undefined))
.decision,
).toBe(PolicyDecision.ASK_USER);
});
@@ -151,16 +151,12 @@ describe('Policy Engine Integration Tests', () => {
// ANY tool with a server name should be allowed
expect(
(await engine.check({ name: 'mcp_mcp-server_tool' }, 'mcp-server'))
(await engine.check({ name: 'mcp-server__tool' }, 'mcp-server'))
.decision,
).toBe(PolicyDecision.ALLOW);
expect(
(
await engine.check(
{ name: 'mcp_another-server_tool' },
'another-server',
)
).decision,
(await engine.check({ name: 'another-server__tool' }, 'another-server'))
.decision,
).toBe(PolicyDecision.ALLOW);
// Built-in tools should NOT be allowed by the MCP wildcard
@@ -175,7 +171,7 @@ describe('Policy Engine Integration Tests', () => {
allowed: ['my-server'],
},
tools: {
exclude: ['mcp_my-server_dangerous-tool'],
exclude: ['my-server__dangerous-tool'],
},
};
@@ -188,24 +184,20 @@ describe('Policy Engine Integration Tests', () => {
// MCP server allowed (priority 4.1) provides general allow for server
// MCP server allowed (priority 4.1) provides general allow for server
expect(
(await engine.check({ name: 'mcp_my-server_safe-tool' }, undefined))
(await engine.check({ name: 'my-server__safe-tool' }, undefined))
.decision,
).toBe(PolicyDecision.ALLOW);
// But specific tool exclude (priority 4.4) wins over server allow
expect(
(
await engine.check(
{ name: 'mcp_my-server_dangerous-tool' },
undefined,
)
).decision,
(await engine.check({ name: 'my-server__dangerous-tool' }, undefined))
.decision,
).toBe(PolicyDecision.DENY);
});
it('should handle complex mixed configurations', async () => {
const settings: Settings = {
tools: {
allowed: ['custom-tool', 'mcp_my-server_special-tool'],
allowed: ['custom-tool', 'my-server__special-tool'],
exclude: ['glob', 'dangerous-tool'],
},
mcp: {
@@ -250,21 +242,21 @@ describe('Policy Engine Integration Tests', () => {
(await engine.check({ name: 'custom-tool' }, undefined)).decision,
).toBe(PolicyDecision.ALLOW);
expect(
(await engine.check({ name: 'mcp_my-server_special-tool' }, undefined))
(await engine.check({ name: 'my-server__special-tool' }, undefined))
.decision,
).toBe(PolicyDecision.ALLOW);
// MCP server tools
expect(
(await engine.check({ name: 'mcp_allowed-server_tool' }, undefined))
(await engine.check({ name: 'allowed-server__tool' }, undefined))
.decision,
).toBe(PolicyDecision.ALLOW);
expect(
(await engine.check({ name: 'mcp_trusted-server_tool' }, undefined))
(await engine.check({ name: 'trusted-server__tool' }, undefined))
.decision,
).toBe(PolicyDecision.ALLOW);
expect(
(await engine.check({ name: 'mcp_blocked-server_tool' }, undefined))
(await engine.check({ name: 'blocked-server__tool' }, undefined))
.decision,
).toBe(PolicyDecision.DENY);
@@ -491,7 +483,7 @@ describe('Policy Engine Integration Tests', () => {
expect(blockedToolRule?.priority).toBe(4.4); // Command line exclude
const blockedServerRule = rules.find(
(r) => r.toolName === 'mcp_blocked-server_*',
(r) => r.toolName === 'blocked-server__*',
);
expect(blockedServerRule?.priority).toBe(4.9); // MCP server exclude
@@ -501,13 +493,11 @@ describe('Policy Engine Integration Tests', () => {
expect(specificToolRule?.priority).toBe(4.3); // Command line allow
const trustedServerRule = rules.find(
(r) => r.toolName === 'mcp_trusted-server_*',
(r) => r.toolName === 'trusted-server__*',
);
expect(trustedServerRule?.priority).toBe(4.2); // MCP trusted server
const mcpServerRule = rules.find(
(r) => r.toolName === 'mcp_mcp-server_*',
);
const mcpServerRule = rules.find((r) => r.toolName === 'mcp-server__*');
expect(mcpServerRule?.priority).toBe(4.1); // MCP allowed server
const readOnlyToolRule = rules.find((r) => r.toolName === 'glob');
@@ -519,19 +509,18 @@ describe('Policy Engine Integration Tests', () => {
(await engine.check({ name: 'blocked-tool' }, undefined)).decision,
).toBe(PolicyDecision.DENY);
expect(
(await engine.check({ name: 'mcp_blocked-server_any' }, undefined))
(await engine.check({ name: 'blocked-server__any' }, undefined))
.decision,
).toBe(PolicyDecision.DENY);
expect(
(await engine.check({ name: 'specific-tool' }, undefined)).decision,
).toBe(PolicyDecision.ALLOW);
expect(
(await engine.check({ name: 'mcp_trusted-server_any' }, undefined))
(await engine.check({ name: 'trusted-server__any' }, undefined))
.decision,
).toBe(PolicyDecision.ALLOW);
expect(
(await engine.check({ name: 'mcp_mcp-server_any' }, undefined))
.decision,
(await engine.check({ name: 'mcp-server__any' }, undefined)).decision,
).toBe(PolicyDecision.ALLOW);
expect((await engine.check({ name: 'glob' }, undefined)).decision).toBe(
PolicyDecision.ALLOW,
@@ -560,7 +549,7 @@ describe('Policy Engine Integration Tests', () => {
// Exclusion (195) should win over trust (90)
expect(
(await engine.check({ name: 'mcp_conflicted-server_tool' }, undefined))
(await engine.check({ name: 'conflicted-server__tool' }, undefined))
.decision,
).toBe(PolicyDecision.DENY);
});
@@ -571,7 +560,7 @@ describe('Policy Engine Integration Tests', () => {
excluded: ['my-server'], // Priority 195 - DENY
},
tools: {
allowed: ['mcp_my-server_special-tool'], // Priority 100 - ALLOW
allowed: ['my-server__special-tool'], // Priority 100 - ALLOW
},
};
@@ -584,11 +573,11 @@ describe('Policy Engine Integration Tests', () => {
// Server exclusion (195) wins over specific tool allow (100)
// This might be counterintuitive but follows the priority system
expect(
(await engine.check({ name: 'mcp_my-server_special-tool' }, undefined))
(await engine.check({ name: 'my-server__special-tool' }, undefined))
.decision,
).toBe(PolicyDecision.DENY);
expect(
(await engine.check({ name: 'mcp_my-server_other-tool' }, undefined))
(await engine.check({ name: 'my-server__other-tool' }, undefined))
.decision,
).toBe(PolicyDecision.DENY);
});
@@ -658,13 +647,13 @@ describe('Policy Engine Integration Tests', () => {
const tool3Rule = rules.find((r) => r.toolName === 'tool3');
expect(tool3Rule?.priority).toBe(4.4); // Excluded tools (user tier)
const server2Rule = rules.find((r) => r.toolName === 'mcp_server2_*');
const server2Rule = rules.find((r) => r.toolName === 'server2__*');
expect(server2Rule?.priority).toBe(4.9); // Excluded servers (user tier)
const tool1Rule = rules.find((r) => r.toolName === 'tool1');
expect(tool1Rule?.priority).toBe(4.3); // Allowed tools (user tier)
const server1Rule = rules.find((r) => r.toolName === 'mcp_server1_*');
const server1Rule = rules.find((r) => r.toolName === 'server1__*');
expect(server1Rule?.priority).toBe(4.1); // Allowed servers (user tier)
const globRule = rules.find((r) => r.toolName === 'glob');
+1
View File
@@ -183,6 +183,7 @@ describe('resolveWorkspacePolicyState', () => {
setAutoAcceptWorkspacePolicies(originalValue);
}
});
it('should not return workspace policies if cwd is the home directory', async () => {
const policiesDir = path.join(tempDir, '.gemini', 'policies');
fs.mkdirSync(policiesDir, { recursive: true });
@@ -461,7 +461,7 @@ describe('SettingsSchema', () => {
expect(gemmaModelRouter.category).toBe('Experimental');
expect(gemmaModelRouter.default).toEqual({});
expect(gemmaModelRouter.requiresRestart).toBe(true);
expect(gemmaModelRouter.showInDialog).toBe(false);
expect(gemmaModelRouter.showInDialog).toBe(true);
expect(gemmaModelRouter.description).toBe(
'Enable Gemma model router (experimental).',
);
@@ -472,9 +472,9 @@ describe('SettingsSchema', () => {
expect(enabled.category).toBe('Experimental');
expect(enabled.default).toBe(false);
expect(enabled.requiresRestart).toBe(true);
expect(enabled.showInDialog).toBe(false);
expect(enabled.showInDialog).toBe(true);
expect(enabled.description).toBe(
'Enable the Gemma Model Router (experimental). Requires a local endpoint serving Gemma via the Gemini API using LiteRT-LM shim.',
'Enable the Gemma Model Router. Requires a local endpoint serving Gemma via the Gemini API using LiteRT-LM shim.',
);
const classifier = gemmaModelRouter.properties.classifier;
+13 -4
View File
@@ -1169,7 +1169,7 @@ const SETTINGS_SCHEMA = {
requiresRestart: false,
default: false,
description: oneLine`
Controls how /memory reload loads GEMINI.md files.
Controls how /memory refresh loads GEMINI.md files.
When true, include directories are scanned; when false, only the current directory is used.
`,
showInDialog: true,
@@ -1846,6 +1846,15 @@ const SETTINGS_SCHEMA = {
'Enable model steering (user hints) to guide the model during tool execution.',
showInDialog: true,
},
continuousSession: {
type: 'boolean',
label: 'Continuous Session',
category: 'Experimental',
requiresRestart: false,
default: false,
description: 'Enables tool and prompts for a continuous session effect.',
showInDialog: true,
},
directWebFetch: {
type: 'boolean',
label: 'Direct Web Fetch',
@@ -1863,7 +1872,7 @@ const SETTINGS_SCHEMA = {
requiresRestart: true,
default: {},
description: 'Enable Gemma model router (experimental).',
showInDialog: false,
showInDialog: true,
properties: {
enabled: {
type: 'boolean',
@@ -1872,8 +1881,8 @@ const SETTINGS_SCHEMA = {
requiresRestart: true,
default: false,
description:
'Enable the Gemma Model Router (experimental). Requires a local endpoint serving Gemma via the Gemini API using LiteRT-LM shim.',
showInDialog: false,
'Enable the Gemma Model Router. Requires a local endpoint serving Gemma via the Gemini API using LiteRT-LM shim.',
showInDialog: true,
},
classifier: {
type: 'object',
+7 -66
View File
@@ -747,60 +747,6 @@ describe('gemini.tsx main function kitty protocol', () => {
emitFeedbackSpy.mockRestore();
});
it('should start normally with a warning when no sessions found for resume', async () => {
const { SessionSelector, SessionError } = await import(
'./utils/sessionUtils.js'
);
vi.mocked(SessionSelector).mockImplementation(
() =>
({
resolveSession: vi
.fn()
.mockRejectedValue(SessionError.noSessionsFound()),
}) as unknown as InstanceType<typeof SessionSelector>,
);
const processExitSpy = vi
.spyOn(process, 'exit')
.mockImplementation((code) => {
throw new MockProcessExitError(code);
});
const emitFeedbackSpy = vi.spyOn(coreEvents, 'emitFeedback');
vi.mocked(loadSettings).mockReturnValue(
createMockSettings({
merged: { advanced: {}, security: { auth: {} }, ui: { theme: 'test' } },
workspace: { settings: {} },
setValue: vi.fn(),
forScope: () => ({ settings: {}, originalSettings: {}, path: '' }),
}),
);
vi.mocked(parseArguments).mockResolvedValue({
promptInteractive: false,
resume: 'latest',
} as unknown as CliArgs);
vi.mocked(loadCliConfig).mockResolvedValue(
createMockConfig({
isInteractive: () => true,
getQuestion: () => '',
getSandbox: () => undefined,
}),
);
await main();
// Should NOT have crashed
expect(processExitSpy).not.toHaveBeenCalled();
// Should NOT have emitted a feedback error
expect(emitFeedbackSpy).not.toHaveBeenCalledWith(
'error',
expect.stringContaining('Error resuming session'),
);
processExitSpy.mockRestore();
emitFeedbackSpy.mockRestore();
});
it.skip('should log error when cleanupExpiredSessions fails', async () => {
const { cleanupExpiredSessions } = await import(
'./utils/sessionCleanup.js'
@@ -1013,18 +959,13 @@ describe('gemini.tsx main function exit codes', () => {
resume: 'invalid-session',
} as unknown as CliArgs);
vi.mock('./utils/sessionUtils.js', async (importOriginal) => {
const original =
await importOriginal<typeof import('./utils/sessionUtils.js')>();
return {
...original,
SessionSelector: vi.fn().mockImplementation(() => ({
resolveSession: vi
.fn()
.mockRejectedValue(new Error('Session not found')),
})),
};
});
vi.mock('./utils/sessionUtils.js', () => ({
SessionSelector: vi.fn().mockImplementation(() => ({
resolveSession: vi
.fn()
.mockRejectedValue(new Error('Session not found')),
})),
}));
process.env['GEMINI_API_KEY'] = 'test-key';
try {
+7 -19
View File
@@ -84,7 +84,7 @@ import { validateNonInteractiveAuth } from './validateNonInterActiveAuth.js';
import { checkForUpdates } from './ui/utils/updateCheck.js';
import { handleAutoUpdate } from './utils/handleAutoUpdate.js';
import { appEvents, AppEvent } from './utils/events.js';
import { SessionError, SessionSelector } from './utils/sessionUtils.js';
import { SessionSelector } from './utils/sessionUtils.js';
import { SettingsContext } from './ui/contexts/SettingsContext.js';
import { MouseProvider } from './ui/contexts/MouseContext.js';
import { StreamingState } from './ui/types.js';
@@ -706,24 +706,12 @@ export async function main() {
// Use the existing session ID to continue recording to the same session
config.setSessionId(resumedSessionData.conversation.sessionId);
} catch (error) {
if (
error instanceof SessionError &&
error.code === 'NO_SESSIONS_FOUND'
) {
// No sessions to resume — start a fresh session with a warning
startupWarnings.push({
id: 'resume-no-sessions',
message: error.message,
priority: WarningPriority.High,
});
} else {
coreEvents.emitFeedback(
'error',
`Error resuming session: ${error instanceof Error ? error.message : 'Unknown error'}`,
);
await runExitCleanup();
process.exit(ExitCodes.FATAL_INPUT_ERROR);
}
coreEvents.emitFeedback(
'error',
`Error resuming session: ${error instanceof Error ? error.message : 'Unknown error'}`,
);
await runExitCleanup();
process.exit(ExitCodes.FATAL_INPUT_ERROR);
}
}
@@ -0,0 +1,107 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Continuous Session Integration > should handle checkpoint_state and manual compress tools correctly > 1-before-checkpoint 1`] = `
[
{
"parts": [
{
"text": "<SESSION_CONTEXT>",
},
{
"text": "Start the mission PADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPAD",
},
],
"role": "user",
},
]
`;
exports[`Continuous Session Integration > should handle checkpoint_state and manual compress tools correctly > 2-with-checkpoint 1`] = `
[
{
"parts": [
{
"text": "<SESSION_CONTEXT>",
},
{
"text": "<state_checkpoint>
GOAL: Implementation of session continuity.
PROGRESS: Tools implemented.
CONSTRAINT: Use high-fidelity summary.
</state_checkpoint>",
},
{
"text": "Start the mission PADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPADPAD",
},
],
"role": "user",
},
{
"parts": [
{
"text": "I will now checkpoint our progress.",
},
{
"functionCall": {
"args": {
"summary": "GOAL: Implementation of session continuity.
PROGRESS: Tools implemented.
CONSTRAINT: Use high-fidelity summary.",
},
"id": "<CALL_ID>",
"name": "checkpoint_state",
},
"thoughtSignature": "skip_thought_signature_validator",
},
],
"role": "model",
},
{
"parts": [
{
"functionResponse": {
"id": "<CALL_ID>",
"name": "checkpoint_state",
"response": {
"output": "First checkpoint created. No previous summary found.",
},
},
},
],
"role": "user",
},
]
`;
exports[`Continuous Session Integration > should handle checkpoint_state and manual compress tools correctly > final-curated-history 1`] = `
[
{
"parts": [
{
"text": "<SESSION_CONTEXT>",
},
{
"text": "<state_checkpoint>
<state_snapshot>
<overall_goal>Implement session continuity</overall_goal>
<active_constraints>Use high-fidelity summary</active_constraints>
<key_knowledge>Tools implemented: checkpoint_state, compress</key_knowledge>
<task_state>1. [DONE] Implement tools
2. [IN PROGRESS] Verify continuity
</task_state>
</state_snapshot>
</state_checkpoint>",
},
],
"role": "user",
},
{
"parts": [
{
"text": "Compression successful. I have clear context and I remember our mission.",
},
],
"role": "model",
},
]
`;
@@ -0,0 +1,124 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Distill Result Integration > should surgically replace a noisy tool result with a distilled version > 1-initial-prompt 1`] = `
[
{
"parts": [
{
"text": "<SESSION_CONTEXT>",
},
{
"text": "Audit src/ for secrets",
},
],
"role": "user",
},
]
`;
exports[`Distill Result Integration > should surgically replace a noisy tool result with a distilled version > 2-request-with-noise 1`] = `
[
{
"parts": [
{
"text": "<SESSION_CONTEXT>",
},
{
"text": "Audit src/ for secrets",
},
],
"role": "user",
},
{
"parts": [
{
"text": "**Thought**
I need to search for SECRET in the src/ directory.",
},
{
"functionCall": {
"args": {
"file_path": "src/foo.txt",
},
"id": "<CALL_ID>",
"name": "read_file",
},
"thoughtSignature": "skip_thought_signature_validator",
},
],
"role": "model",
},
{
"parts": [
{
"functionResponse": {
"id": "<CALL_ID>",
"name": "read_file",
"response": {
"error": "File not found: <TEST_DIR>/src/foo.txt",
},
},
},
],
"role": "user",
},
]
`;
exports[`Distill Result Integration > should surgically replace a noisy tool result with a distilled version > final-curated-history 1`] = `
[
{
"parts": [
{
"text": "<SESSION_CONTEXT>",
},
{
"text": "Audit src/ for secrets",
},
],
"role": "user",
},
{
"parts": [
{
"text": "**Thought**
I need to search for SECRET in the src/ directory.",
},
{
"functionCall": {
"args": {
"file_path": "src/foo.txt",
},
"id": "<CALL_ID>",
"name": "read_file",
},
},
],
"role": "model",
},
{
"parts": [
{
"functionResponse": {
"id": "<CALL_ID>",
"name": "read_file",
"response": {
"distilled": true,
"distilled_output": "Found SECRET_KEY="12345" in src/env.ts",
"original_output_file": "<TMP_FILE>",
},
},
},
],
"role": "user",
},
{
"parts": [
{
"text": "I found the SECRET_KEY="12345" in src/env.ts after distilling the search results.",
},
],
"role": "model",
},
]
`;
@@ -0,0 +1,66 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, afterEach } from 'vitest';
import { AppRig } from '../test-utils/AppRig.js';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { PolicyDecision } from '@google/gemini-cli-core';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
describe('Continuous Session Integration', () => {
let rig: AppRig | undefined;
afterEach(async () => {
await rig?.unmount();
});
it('should handle checkpoint_state and manual compress tools correctly', async () => {
const fakeResponsesPath = path.join(
__dirname,
'../test-utils/fixtures/continuous_session.responses',
);
rig = new AppRig({
fakeResponsesPath,
configOverrides: {
continuousSession: true,
},
});
await rig.initialize();
rig.render();
await rig.waitForIdle();
// Use ASK_USER to pause and inspect the curated history at key moments
rig.setToolPolicy('checkpoint_state', PolicyDecision.ASK_USER);
rig.setToolPolicy('compress', PolicyDecision.ASK_USER);
// Start the quest
await rig.type('Start the mission ' + 'PAD'.repeat(100));
await rig.pressEnter();
// 1. Wait for CheckpointState tool call
await rig.waitForOutput('CheckpointState');
// Verify curated history BEFORE checkpoint is applied
expect(rig.getLastSentRequestContents()).toMatchSnapshot('1-before-checkpoint');
await rig.resolveTool('CheckpointState');
// 2. Wait for Compress tool call
await rig.waitForOutput('Compress');
// Verify curated history contains the checkpoint
expect(rig.getLastSentRequestContents()).toMatchSnapshot('2-with-checkpoint');
await rig.resolveTool('Compress');
// 3. Wait for final model response after compression
await rig.waitForOutput('Compression successful.');
await rig.waitForIdle();
// Verify the final curated history:
// - Should contain the high-fidelity snapshot
// - Should NOT contain pre-compression turns
expect(rig.getCuratedHistory()).toMatchSnapshot('final-curated-history');
});
});
@@ -0,0 +1,86 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, afterEach } from 'vitest';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { AppRig } from '../test-utils/AppRig.js';
import { PolicyDecision } from '@google/gemini-cli-core';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
describe('Distill Result Integration', () => {
let rig: AppRig | undefined;
afterEach(async () => {
await rig?.unmount();
});
it('should surgically replace a noisy tool result with a distilled version', async () => {
const fakeResponsesPath = path.resolve(
__dirname,
'../test-utils/fixtures/distill_result.responses',
);
rig = new AppRig({
fakeResponsesPath,
configOverrides: {
continuousSession: true,
modelSteering: true,
},
});
await rig.initialize();
rig.render();
await rig.waitForIdle();
rig.setMockCommands([
{
command: /read_file/,
result: {
output: 'NOISE\n'.repeat(50) + 'SECRET_KEY="12345"\n' + 'NOISE\n'.repeat(50),
exitCode: 0,
},
},
]);
// Use ASK_USER to pause and inspect the request before each model turn
rig.setToolPolicy('read_file', PolicyDecision.ASK_USER);
rig.setToolPolicy('distill_result', PolicyDecision.ASK_USER);
// 1. Initial Prompt: Audit for secrets
await rig.sendMessage('Audit src/ for secrets');
// 2. Model calls run_shell_command (the "Noise Bomb")
await rig.waitForOutput('ReadFile');
// Verify the curated history sent to model contains the initial user prompt
expect(rig.getLastSentRequestContents()).toMatchSnapshot('1-initial-prompt');
await rig.resolveTool('ReadFile');
// 3. Model realizes it's noisy and calls distill_result
await rig.waitForOutput('DistillResult');
// Verify history now includes the massive noise
expect(rig.getLastSentRequestContents()).toMatchSnapshot('2-request-with-noise');
await rig.resolveTool('DistillResult');
// 4. Model continues from the distilled state and finishes
await rig.waitForOutput(/found the SECRET_KEY/i);
await rig.waitForIdle();
// Verify the final curated history:
// - NO noise from the original read_file
// - original read_file response is replaced with our universal distillation schema
// - intermediate thoughts and the distill_result turn itself are elided
expect(rig.getCuratedHistory()).toMatchSnapshot('final-curated-history');
// Verify final output contains the signal
const output = rig.getStaticOutput();
expect(output).toContain('SECRET_KEY');
expect(output).toContain('12345');
});
});
+421 -59
View File
@@ -17,9 +17,21 @@ const createMockCommand = (name: string, kind: CommandKind): SlashCommand => ({
action: vi.fn(),
});
const mockCommandA = createMockCommand('command-a', CommandKind.BUILT_IN);
const mockCommandB = createMockCommand('command-b', CommandKind.BUILT_IN);
const mockCommandC = createMockCommand('command-c', CommandKind.FILE);
const mockCommandB_Override = createMockCommand('command-b', CommandKind.FILE);
class MockCommandLoader implements ICommandLoader {
constructor(private readonly commands: SlashCommand[]) {}
loadCommands = vi.fn(async () => Promise.resolve(this.commands));
private commandsToLoad: SlashCommand[];
constructor(commandsToLoad: SlashCommand[]) {
this.commandsToLoad = commandsToLoad;
}
loadCommands = vi.fn(
async (): Promise<SlashCommand[]> => Promise.resolve(this.commandsToLoad),
);
}
describe('CommandService', () => {
@@ -31,74 +43,424 @@ describe('CommandService', () => {
vi.restoreAllMocks();
});
describe('basic loading', () => {
it('should aggregate commands from multiple successful loaders', async () => {
const cmdA = createMockCommand('a', CommandKind.BUILT_IN);
const cmdB = createMockCommand('b', CommandKind.USER_FILE);
const service = await CommandService.create(
[new MockCommandLoader([cmdA]), new MockCommandLoader([cmdB])],
new AbortController().signal,
);
it('should load commands from a single loader', async () => {
const mockLoader = new MockCommandLoader([mockCommandA, mockCommandB]);
const service = await CommandService.create(
[mockLoader],
new AbortController().signal,
);
expect(service.getCommands()).toHaveLength(2);
expect(service.getCommands()).toEqual(
expect.arrayContaining([cmdA, cmdB]),
);
});
const commands = service.getCommands();
it('should handle empty loaders and failed loaders gracefully', async () => {
const cmdA = createMockCommand('a', CommandKind.BUILT_IN);
const failingLoader = new MockCommandLoader([]);
vi.spyOn(failingLoader, 'loadCommands').mockRejectedValue(
new Error('fail'),
);
expect(mockLoader.loadCommands).toHaveBeenCalledTimes(1);
expect(commands).toHaveLength(2);
expect(commands).toEqual(
expect.arrayContaining([mockCommandA, mockCommandB]),
);
});
const service = await CommandService.create(
[
new MockCommandLoader([cmdA]),
new MockCommandLoader([]),
failingLoader,
],
new AbortController().signal,
);
it('should aggregate commands from multiple loaders', async () => {
const loader1 = new MockCommandLoader([mockCommandA]);
const loader2 = new MockCommandLoader([mockCommandC]);
const service = await CommandService.create(
[loader1, loader2],
new AbortController().signal,
);
expect(service.getCommands()).toHaveLength(1);
expect(service.getCommands()[0].name).toBe('a');
expect(debugLogger.debug).toHaveBeenCalledWith(
'A command loader failed:',
expect.any(Error),
);
});
const commands = service.getCommands();
it('should return a readonly array of commands', async () => {
const service = await CommandService.create(
[new MockCommandLoader([createMockCommand('a', CommandKind.BUILT_IN)])],
new AbortController().signal,
);
expect(() => (service.getCommands() as unknown[]).push({})).toThrow();
});
expect(loader1.loadCommands).toHaveBeenCalledTimes(1);
expect(loader2.loadCommands).toHaveBeenCalledTimes(1);
expect(commands).toHaveLength(2);
expect(commands).toEqual(
expect.arrayContaining([mockCommandA, mockCommandC]),
);
});
it('should pass the abort signal to all loaders', async () => {
const controller = new AbortController();
const loader = new MockCommandLoader([]);
await CommandService.create([loader], controller.signal);
expect(loader.loadCommands).toHaveBeenCalledWith(controller.signal);
it('should override commands from earlier loaders with those from later loaders', async () => {
const loader1 = new MockCommandLoader([mockCommandA, mockCommandB]);
const loader2 = new MockCommandLoader([
mockCommandB_Override,
mockCommandC,
]);
const service = await CommandService.create(
[loader1, loader2],
new AbortController().signal,
);
const commands = service.getCommands();
expect(commands).toHaveLength(3); // Should be A, C, and the overridden B.
// The final list should contain the override from the *last* loader.
const commandB = commands.find((cmd) => cmd.name === 'command-b');
expect(commandB).toBeDefined();
expect(commandB?.kind).toBe(CommandKind.FILE); // Verify it's the overridden version.
expect(commandB).toEqual(mockCommandB_Override);
// Ensure the other commands are still present.
expect(commands).toEqual(
expect.arrayContaining([
mockCommandA,
mockCommandC,
mockCommandB_Override,
]),
);
});
it('should handle loaders that return an empty array of commands gracefully', async () => {
const loader1 = new MockCommandLoader([mockCommandA]);
const emptyLoader = new MockCommandLoader([]);
const loader3 = new MockCommandLoader([mockCommandB]);
const service = await CommandService.create(
[loader1, emptyLoader, loader3],
new AbortController().signal,
);
const commands = service.getCommands();
expect(emptyLoader.loadCommands).toHaveBeenCalledTimes(1);
expect(commands).toHaveLength(2);
expect(commands).toEqual(
expect.arrayContaining([mockCommandA, mockCommandB]),
);
});
it('should load commands from successful loaders even if one fails', async () => {
const successfulLoader = new MockCommandLoader([mockCommandA]);
const failingLoader = new MockCommandLoader([]);
const error = new Error('Loader failed');
vi.spyOn(failingLoader, 'loadCommands').mockRejectedValue(error);
const service = await CommandService.create(
[successfulLoader, failingLoader],
new AbortController().signal,
);
const commands = service.getCommands();
expect(commands).toHaveLength(1);
expect(commands).toEqual([mockCommandA]);
expect(debugLogger.debug).toHaveBeenCalledWith(
'A command loader failed:',
error,
);
});
it('getCommands should return a readonly array that cannot be mutated', async () => {
const service = await CommandService.create(
[new MockCommandLoader([mockCommandA])],
new AbortController().signal,
);
const commands = service.getCommands();
// Expect it to throw a TypeError at runtime because the array is frozen.
expect(() => {
// @ts-expect-error - Testing immutability is intentional here.
commands.push(mockCommandB);
}).toThrow();
// Verify the original array was not mutated.
expect(service.getCommands()).toHaveLength(1);
});
it('should pass the abort signal to all loaders', async () => {
const controller = new AbortController();
const signal = controller.signal;
const loader1 = new MockCommandLoader([mockCommandA]);
const loader2 = new MockCommandLoader([mockCommandB]);
await CommandService.create([loader1, loader2], signal);
expect(loader1.loadCommands).toHaveBeenCalledTimes(1);
expect(loader1.loadCommands).toHaveBeenCalledWith(signal);
expect(loader2.loadCommands).toHaveBeenCalledTimes(1);
expect(loader2.loadCommands).toHaveBeenCalledWith(signal);
});
it('should rename extension commands when they conflict', async () => {
const builtinCommand = createMockCommand('deploy', CommandKind.BUILT_IN);
const userCommand = createMockCommand('sync', CommandKind.FILE);
const extensionCommand1 = {
...createMockCommand('deploy', CommandKind.FILE),
extensionName: 'firebase',
description: '[firebase] Deploy to Firebase',
};
const extensionCommand2 = {
...createMockCommand('sync', CommandKind.FILE),
extensionName: 'git-helper',
description: '[git-helper] Sync with remote',
};
const mockLoader1 = new MockCommandLoader([builtinCommand]);
const mockLoader2 = new MockCommandLoader([
userCommand,
extensionCommand1,
extensionCommand2,
]);
const service = await CommandService.create(
[mockLoader1, mockLoader2],
new AbortController().signal,
);
const commands = service.getCommands();
expect(commands).toHaveLength(4);
// Built-in command keeps original name
const deployBuiltin = commands.find(
(cmd) => cmd.name === 'deploy' && !cmd.extensionName,
);
expect(deployBuiltin).toBeDefined();
expect(deployBuiltin?.kind).toBe(CommandKind.BUILT_IN);
// Extension command conflicting with built-in gets renamed
const deployExtension = commands.find(
(cmd) => cmd.name === 'firebase.deploy',
);
expect(deployExtension).toBeDefined();
expect(deployExtension?.extensionName).toBe('firebase');
// User command keeps original name
const syncUser = commands.find(
(cmd) => cmd.name === 'sync' && !cmd.extensionName,
);
expect(syncUser).toBeDefined();
expect(syncUser?.kind).toBe(CommandKind.FILE);
// Extension command conflicting with user command gets renamed
const syncExtension = commands.find(
(cmd) => cmd.name === 'git-helper.sync',
);
expect(syncExtension).toBeDefined();
expect(syncExtension?.extensionName).toBe('git-helper');
});
it('should handle user/project command override correctly', async () => {
const builtinCommand = createMockCommand('help', CommandKind.BUILT_IN);
const userCommand = createMockCommand('help', CommandKind.FILE);
const projectCommand = createMockCommand('deploy', CommandKind.FILE);
const userDeployCommand = createMockCommand('deploy', CommandKind.FILE);
const mockLoader1 = new MockCommandLoader([builtinCommand]);
const mockLoader2 = new MockCommandLoader([
userCommand,
userDeployCommand,
projectCommand,
]);
const service = await CommandService.create(
[mockLoader1, mockLoader2],
new AbortController().signal,
);
const commands = service.getCommands();
expect(commands).toHaveLength(2);
// User command overrides built-in
const helpCommand = commands.find((cmd) => cmd.name === 'help');
expect(helpCommand).toBeDefined();
expect(helpCommand?.kind).toBe(CommandKind.FILE);
// Project command overrides user command (last wins)
const deployCommand = commands.find((cmd) => cmd.name === 'deploy');
expect(deployCommand).toBeDefined();
expect(deployCommand?.kind).toBe(CommandKind.FILE);
});
it('should handle secondary conflicts when renaming extension commands', async () => {
// User has both /deploy and /gcp.deploy commands
const userCommand1 = createMockCommand('deploy', CommandKind.FILE);
const userCommand2 = createMockCommand('gcp.deploy', CommandKind.FILE);
// Extension also has a deploy command that will conflict with user's /deploy
const extensionCommand = {
...createMockCommand('deploy', CommandKind.FILE),
extensionName: 'gcp',
description: '[gcp] Deploy to Google Cloud',
};
const mockLoader = new MockCommandLoader([
userCommand1,
userCommand2,
extensionCommand,
]);
const service = await CommandService.create(
[mockLoader],
new AbortController().signal,
);
const commands = service.getCommands();
expect(commands).toHaveLength(3);
// Original user command keeps its name
const deployUser = commands.find(
(cmd) => cmd.name === 'deploy' && !cmd.extensionName,
);
expect(deployUser).toBeDefined();
// User's dot notation command keeps its name
const gcpDeployUser = commands.find(
(cmd) => cmd.name === 'gcp.deploy' && !cmd.extensionName,
);
expect(gcpDeployUser).toBeDefined();
// Extension command gets renamed with suffix due to secondary conflict
const deployExtension = commands.find(
(cmd) => cmd.name === 'gcp.deploy1' && cmd.extensionName === 'gcp',
);
expect(deployExtension).toBeDefined();
expect(deployExtension?.description).toBe('[gcp] Deploy to Google Cloud');
});
it('should handle multiple secondary conflicts with incrementing suffixes', async () => {
// User has /deploy, /gcp.deploy, and /gcp.deploy1
const userCommand1 = createMockCommand('deploy', CommandKind.FILE);
const userCommand2 = createMockCommand('gcp.deploy', CommandKind.FILE);
const userCommand3 = createMockCommand('gcp.deploy1', CommandKind.FILE);
// Extension has a deploy command
const extensionCommand = {
...createMockCommand('deploy', CommandKind.FILE),
extensionName: 'gcp',
description: '[gcp] Deploy to Google Cloud',
};
const mockLoader = new MockCommandLoader([
userCommand1,
userCommand2,
userCommand3,
extensionCommand,
]);
const service = await CommandService.create(
[mockLoader],
new AbortController().signal,
);
const commands = service.getCommands();
expect(commands).toHaveLength(4);
// Extension command gets renamed with suffix 2 due to multiple conflicts
const deployExtension = commands.find(
(cmd) => cmd.name === 'gcp.deploy2' && cmd.extensionName === 'gcp',
);
expect(deployExtension).toBeDefined();
expect(deployExtension?.description).toBe('[gcp] Deploy to Google Cloud');
});
it('should report conflicts via getConflicts', async () => {
const builtinCommand = createMockCommand('deploy', CommandKind.BUILT_IN);
const extensionCommand = {
...createMockCommand('deploy', CommandKind.FILE),
extensionName: 'firebase',
};
const mockLoader = new MockCommandLoader([
builtinCommand,
extensionCommand,
]);
const service = await CommandService.create(
[mockLoader],
new AbortController().signal,
);
const conflicts = service.getConflicts();
expect(conflicts).toHaveLength(1);
expect(conflicts[0]).toMatchObject({
name: 'deploy',
winner: builtinCommand,
losers: [
{
renamedTo: 'firebase.deploy',
command: expect.objectContaining({
name: 'deploy',
extensionName: 'firebase',
}),
},
],
});
});
describe('conflict delegation', () => {
it('should delegate conflict resolution to SlashCommandResolver', async () => {
const builtin = createMockCommand('help', CommandKind.BUILT_IN);
const user = createMockCommand('help', CommandKind.USER_FILE);
it('should report extension vs extension conflicts correctly', async () => {
// Both extensions try to register 'deploy'
const extension1Command = {
...createMockCommand('deploy', CommandKind.FILE),
extensionName: 'firebase',
};
const extension2Command = {
...createMockCommand('deploy', CommandKind.FILE),
extensionName: 'aws',
};
const service = await CommandService.create(
[new MockCommandLoader([builtin, user])],
new AbortController().signal,
);
const mockLoader = new MockCommandLoader([
extension1Command,
extension2Command,
]);
expect(service.getCommands().map((c) => c.name)).toContain('help');
expect(service.getCommands().map((c) => c.name)).toContain('user.help');
expect(service.getConflicts()).toHaveLength(1);
const service = await CommandService.create(
[mockLoader],
new AbortController().signal,
);
const conflicts = service.getConflicts();
expect(conflicts).toHaveLength(1);
expect(conflicts[0]).toMatchObject({
name: 'deploy',
winner: expect.objectContaining({
name: 'deploy',
extensionName: 'firebase',
}),
losers: [
{
renamedTo: 'aws.deploy', // ext2 is 'aws' and it lost because it was second in the list
command: expect.objectContaining({
name: 'deploy',
extensionName: 'aws',
}),
},
],
});
});
it('should report multiple conflicts for the same command name', async () => {
const builtinCommand = createMockCommand('deploy', CommandKind.BUILT_IN);
const ext1 = {
...createMockCommand('deploy', CommandKind.FILE),
extensionName: 'ext1',
};
const ext2 = {
...createMockCommand('deploy', CommandKind.FILE),
extensionName: 'ext2',
};
const mockLoader = new MockCommandLoader([builtinCommand, ext1, ext2]);
const service = await CommandService.create(
[mockLoader],
new AbortController().signal,
);
const conflicts = service.getConflicts();
expect(conflicts).toHaveLength(1);
expect(conflicts[0].name).toBe('deploy');
expect(conflicts[0].losers).toHaveLength(2);
expect(conflicts[0].losers).toEqual(
expect.arrayContaining([
expect.objectContaining({
renamedTo: 'ext1.deploy',
command: expect.objectContaining({ extensionName: 'ext1' }),
}),
expect.objectContaining({
renamedTo: 'ext2.deploy',
command: expect.objectContaining({ extensionName: 'ext2' }),
}),
]),
);
});
});
+86 -53
View File
@@ -6,8 +6,16 @@
import { debugLogger, coreEvents } from '@google/gemini-cli-core';
import type { SlashCommand } from '../ui/commands/types.js';
import type { ICommandLoader, CommandConflict } from './types.js';
import { SlashCommandResolver } from './SlashCommandResolver.js';
import type { ICommandLoader } from './types.js';
export interface CommandConflict {
name: string;
winner: SlashCommand;
losers: Array<{
command: SlashCommand;
renamedTo: string;
}>;
}
/**
* Orchestrates the discovery and loading of all slash commands for the CLI.
@@ -16,9 +24,9 @@ import { SlashCommandResolver } from './SlashCommandResolver.js';
* with an array of `ICommandLoader` instances, each responsible for fetching
* commands from a specific source (e.g., built-in code, local files).
*
* It uses a delegating resolver to reconcile name conflicts, ensuring that
* all commands are uniquely addressable via source-specific prefixes while
* allowing built-in commands to retain their primary names.
* The CommandService is responsible for invoking these loaders, aggregating their
* results, and resolving any name conflicts. This architecture allows the command
* system to be extended with new sources without modifying the service itself.
*/
export class CommandService {
/**
@@ -34,71 +42,96 @@ export class CommandService {
/**
* Asynchronously creates and initializes a new CommandService instance.
*
* This factory method orchestrates the loading process and delegates
* conflict resolution to the SlashCommandResolver.
* This factory method orchestrates the entire command loading process. It
* runs all provided loaders in parallel, aggregates their results, handles
* name conflicts for extension commands by renaming them, and then returns a
* fully constructed `CommandService` instance.
*
* @param loaders An array of loaders to fetch commands from.
* @param signal An AbortSignal to allow cancellation.
* @returns A promise that resolves to a fully initialized CommandService.
* Conflict resolution:
* - Extension commands that conflict with existing commands are renamed to
* `extensionName.commandName`
* - Non-extension commands (built-in, user, project) override earlier commands
* with the same name based on loader order
*
* @param loaders An array of objects that conform to the `ICommandLoader`
* interface. Built-in commands should come first, followed by FileCommandLoader.
* @param signal An AbortSignal to cancel the loading process.
* @returns A promise that resolves to a new, fully initialized `CommandService` instance.
*/
static async create(
loaders: ICommandLoader[],
signal: AbortSignal,
): Promise<CommandService> {
const allCommands = await this.loadAllCommands(loaders, signal);
const { finalCommands, conflicts } =
SlashCommandResolver.resolve(allCommands);
if (conflicts.length > 0) {
this.emitConflictEvents(conflicts);
}
return new CommandService(
Object.freeze(finalCommands),
Object.freeze(conflicts),
);
}
/**
* Invokes all loaders in parallel and flattens the results.
*/
private static async loadAllCommands(
loaders: ICommandLoader[],
signal: AbortSignal,
): Promise<SlashCommand[]> {
const results = await Promise.allSettled(
loaders.map((loader) => loader.loadCommands(signal)),
);
const commands: SlashCommand[] = [];
const allCommands: SlashCommand[] = [];
for (const result of results) {
if (result.status === 'fulfilled') {
commands.push(...result.value);
allCommands.push(...result.value);
} else {
debugLogger.debug('A command loader failed:', result.reason);
}
}
return commands;
}
/**
* Formats and emits telemetry for command conflicts.
*/
private static emitConflictEvents(conflicts: CommandConflict[]): void {
coreEvents.emitSlashCommandConflicts(
conflicts.flatMap((c) =>
c.losers.map((l) => ({
name: c.name,
renamedTo: l.renamedTo,
loserExtensionName: l.command.extensionName,
winnerExtensionName: l.reason.extensionName,
loserMcpServerName: l.command.mcpServerName,
winnerMcpServerName: l.reason.mcpServerName,
loserKind: l.command.kind,
winnerKind: l.reason.kind,
})),
),
);
const commandMap = new Map<string, SlashCommand>();
const conflictsMap = new Map<string, CommandConflict>();
for (const cmd of allCommands) {
let finalName = cmd.name;
// Extension commands get renamed if they conflict with existing commands
if (cmd.extensionName && commandMap.has(cmd.name)) {
const winner = commandMap.get(cmd.name)!;
let renamedName = `${cmd.extensionName}.${cmd.name}`;
let suffix = 1;
// Keep trying until we find a name that doesn't conflict
while (commandMap.has(renamedName)) {
renamedName = `${cmd.extensionName}.${cmd.name}${suffix}`;
suffix++;
}
finalName = renamedName;
if (!conflictsMap.has(cmd.name)) {
conflictsMap.set(cmd.name, {
name: cmd.name,
winner,
losers: [],
});
}
conflictsMap.get(cmd.name)!.losers.push({
command: cmd,
renamedTo: finalName,
});
}
commandMap.set(finalName, {
...cmd,
name: finalName,
});
}
const conflicts = Array.from(conflictsMap.values());
if (conflicts.length > 0) {
coreEvents.emitSlashCommandConflicts(
conflicts.flatMap((c) =>
c.losers.map((l) => ({
name: c.name,
renamedTo: l.renamedTo,
loserExtensionName: l.command.extensionName,
winnerExtensionName: c.winner.extensionName,
})),
),
);
}
const finalCommands = Object.freeze(Array.from(commandMap.values()));
const finalConflicts = Object.freeze(conflicts);
return new CommandService(finalCommands, finalConflicts);
}
/**
+4 -15
View File
@@ -37,7 +37,6 @@ import { sanitizeForDisplay } from '../ui/utils/textUtils.js';
interface CommandDirectory {
path: string;
kind: CommandKind;
extensionName?: string;
extensionId?: string;
}
@@ -112,7 +111,6 @@ export class FileCommandLoader implements ICommandLoader {
this.parseAndAdaptFile(
path.join(dirInfo.path, file),
dirInfo.path,
dirInfo.kind,
dirInfo.extensionName,
dirInfo.extensionId,
),
@@ -153,16 +151,10 @@ export class FileCommandLoader implements ICommandLoader {
const storage = this.config?.storage ?? new Storage(this.projectRoot);
// 1. User commands
dirs.push({
path: Storage.getUserCommandsDir(),
kind: CommandKind.USER_FILE,
});
dirs.push({ path: Storage.getUserCommandsDir() });
// 2. Project commands
dirs.push({
path: storage.getProjectCommandsDir(),
kind: CommandKind.WORKSPACE_FILE,
});
// 2. Project commands (override user commands)
dirs.push({ path: storage.getProjectCommandsDir() });
// 3. Extension commands (processed last to detect all conflicts)
if (this.config) {
@@ -173,7 +165,6 @@ export class FileCommandLoader implements ICommandLoader {
const extensionCommandDirs = activeExtensions.map((ext) => ({
path: path.join(ext.path, 'commands'),
kind: CommandKind.EXTENSION_FILE,
extensionName: ext.name,
extensionId: ext.id,
}));
@@ -188,14 +179,12 @@ export class FileCommandLoader implements ICommandLoader {
* Parses a single .toml file and transforms it into a SlashCommand object.
* @param filePath The absolute path to the .toml file.
* @param baseDir The root command directory for name calculation.
* @param kind The CommandKind.
* @param extensionName Optional extension name to prefix commands with.
* @returns A promise resolving to a SlashCommand, or null if the file is invalid.
*/
private async parseAndAdaptFile(
filePath: string,
baseDir: string,
kind: CommandKind,
extensionName?: string,
extensionId?: string,
): Promise<SlashCommand | null> {
@@ -297,7 +286,7 @@ export class FileCommandLoader implements ICommandLoader {
return {
name: baseCommandName,
description,
kind,
kind: CommandKind.FILE,
extensionName,
extensionId,
action: async (
@@ -44,7 +44,6 @@ export class McpPromptLoader implements ICommandLoader {
name: commandName,
description: prompt.description || `Invoke prompt ${prompt.name}`,
kind: CommandKind.MCP_PROMPT,
mcpServerName: serverName,
autoExecute: !prompt.arguments || prompt.arguments.length === 0,
subCommands: [
{
@@ -1,175 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { SlashCommandConflictHandler } from './SlashCommandConflictHandler.js';
import {
coreEvents,
CoreEvent,
type SlashCommandConflictsPayload,
type SlashCommandConflict,
} from '@google/gemini-cli-core';
import { CommandKind } from '../ui/commands/types.js';
vi.mock('@google/gemini-cli-core', async (importOriginal) => {
const actual =
await importOriginal<typeof import('@google/gemini-cli-core')>();
return {
...actual,
coreEvents: {
on: vi.fn(),
off: vi.fn(),
emitFeedback: vi.fn(),
},
};
});
describe('SlashCommandConflictHandler', () => {
let handler: SlashCommandConflictHandler;
/**
* Helper to find and invoke the registered conflict event listener.
*/
const simulateEvent = (conflicts: SlashCommandConflict[]) => {
const callback = vi
.mocked(coreEvents.on)
.mock.calls.find(
(call) => call[0] === CoreEvent.SlashCommandConflicts,
)![1] as (payload: SlashCommandConflictsPayload) => void;
callback({ conflicts });
};
beforeEach(() => {
vi.useFakeTimers();
handler = new SlashCommandConflictHandler();
handler.start();
});
afterEach(() => {
handler.stop();
vi.clearAllMocks();
vi.useRealTimers();
});
it('should listen for conflict events on start', () => {
expect(coreEvents.on).toHaveBeenCalledWith(
CoreEvent.SlashCommandConflicts,
expect.any(Function),
);
});
it('should display a descriptive message for a single extension conflict', () => {
simulateEvent([
{
name: 'deploy',
renamedTo: 'firebase.deploy',
loserExtensionName: 'firebase',
loserKind: CommandKind.EXTENSION_FILE,
winnerKind: CommandKind.BUILT_IN,
},
]);
vi.advanceTimersByTime(600);
expect(coreEvents.emitFeedback).toHaveBeenCalledWith(
'info',
"Extension 'firebase' command '/deploy' was renamed to '/firebase.deploy' because it conflicts with built-in command.",
);
});
it('should display a descriptive message for a single MCP conflict', () => {
simulateEvent([
{
name: 'pickle',
renamedTo: 'test-server.pickle',
loserMcpServerName: 'test-server',
loserKind: CommandKind.MCP_PROMPT,
winnerExtensionName: 'pickle-rick',
winnerKind: CommandKind.EXTENSION_FILE,
},
]);
vi.advanceTimersByTime(600);
expect(coreEvents.emitFeedback).toHaveBeenCalledWith(
'info',
"MCP server 'test-server' command '/pickle' was renamed to '/test-server.pickle' because it conflicts with extension 'pickle-rick' command.",
);
});
it('should group multiple conflicts for the same command name', () => {
simulateEvent([
{
name: 'launch',
renamedTo: 'user.launch',
loserKind: CommandKind.USER_FILE,
winnerKind: CommandKind.WORKSPACE_FILE,
},
{
name: 'launch',
renamedTo: 'workspace.launch',
loserKind: CommandKind.WORKSPACE_FILE,
winnerKind: CommandKind.USER_FILE,
},
]);
vi.advanceTimersByTime(600);
expect(coreEvents.emitFeedback).toHaveBeenCalledWith(
'info',
`Conflicts detected for command '/launch':
- User command '/launch' was renamed to '/user.launch'
- Workspace command '/launch' was renamed to '/workspace.launch'`,
);
});
it('should debounce multiple events within the flush window', () => {
simulateEvent([
{
name: 'a',
renamedTo: 'user.a',
loserKind: CommandKind.USER_FILE,
winnerKind: CommandKind.BUILT_IN,
},
]);
vi.advanceTimersByTime(200);
simulateEvent([
{
name: 'b',
renamedTo: 'user.b',
loserKind: CommandKind.USER_FILE,
winnerKind: CommandKind.BUILT_IN,
},
]);
vi.advanceTimersByTime(600);
// Should emit two feedbacks (one for each unique command name)
expect(coreEvents.emitFeedback).toHaveBeenCalledTimes(2);
});
it('should deduplicate already notified conflicts', () => {
const conflict = {
name: 'deploy',
renamedTo: 'firebase.deploy',
loserExtensionName: 'firebase',
loserKind: CommandKind.EXTENSION_FILE,
winnerKind: CommandKind.BUILT_IN,
};
simulateEvent([conflict]);
vi.advanceTimersByTime(600);
expect(coreEvents.emitFeedback).toHaveBeenCalledTimes(1);
vi.mocked(coreEvents.emitFeedback).mockClear();
simulateEvent([conflict]);
vi.advanceTimersByTime(600);
expect(coreEvents.emitFeedback).not.toHaveBeenCalled();
});
});
@@ -8,20 +8,10 @@ import {
coreEvents,
CoreEvent,
type SlashCommandConflictsPayload,
type SlashCommandConflict,
} from '@google/gemini-cli-core';
import { CommandKind } from '../ui/commands/types.js';
/**
* Handles slash command conflict events and provides user feedback.
*
* This handler batches multiple conflict events into a single notification
* block per command name to avoid UI clutter during startup or incremental loading.
*/
export class SlashCommandConflictHandler {
private notifiedConflicts = new Set<string>();
private pendingConflicts: SlashCommandConflict[] = [];
private flushTimeout: ReturnType<typeof setTimeout> | null = null;
constructor() {
this.handleConflicts = this.handleConflicts.bind(this);
@@ -33,18 +23,11 @@ export class SlashCommandConflictHandler {
stop() {
coreEvents.off(CoreEvent.SlashCommandConflicts, this.handleConflicts);
if (this.flushTimeout) {
clearTimeout(this.flushTimeout);
this.flushTimeout = null;
}
}
private handleConflicts(payload: SlashCommandConflictsPayload) {
const newConflicts = payload.conflicts.filter((c) => {
// Use a unique key to prevent duplicate notifications for the same conflict
const sourceId =
c.loserExtensionName || c.loserMcpServerName || c.loserKind;
const key = `${c.name}:${sourceId}:${c.renamedTo}`;
const key = `${c.name}:${c.loserExtensionName}`;
if (this.notifiedConflicts.has(key)) {
return false;
}
@@ -53,119 +36,19 @@ export class SlashCommandConflictHandler {
});
if (newConflicts.length > 0) {
this.pendingConflicts.push(...newConflicts);
this.scheduleFlush();
}
}
const conflictMessages = newConflicts
.map((c) => {
const winnerSource = c.winnerExtensionName
? `extension '${c.winnerExtensionName}'`
: 'an existing command';
return `- Command '/${c.name}' from extension '${c.loserExtensionName}' was renamed to '/${c.renamedTo}' because it conflicts with ${winnerSource}.`;
})
.join('\n');
private scheduleFlush() {
if (this.flushTimeout) {
clearTimeout(this.flushTimeout);
}
// Use a trailing debounce to capture staggered reloads during startup
this.flushTimeout = setTimeout(() => this.flush(), 500);
}
private flush() {
this.flushTimeout = null;
const conflicts = [...this.pendingConflicts];
this.pendingConflicts = [];
if (conflicts.length === 0) {
return;
}
// Group conflicts by their original command name
const grouped = new Map<string, SlashCommandConflict[]>();
for (const c of conflicts) {
const list = grouped.get(c.name) ?? [];
list.push(c);
grouped.set(c.name, list);
}
for (const [name, commandConflicts] of grouped) {
if (commandConflicts.length > 1) {
this.emitGroupedFeedback(name, commandConflicts);
} else {
this.emitSingleFeedback(commandConflicts[0]);
}
}
}
/**
* Emits a grouped notification for multiple conflicts sharing the same name.
*/
private emitGroupedFeedback(
name: string,
conflicts: SlashCommandConflict[],
): void {
const messages = conflicts
.map((c) => {
const source = this.getSourceDescription(
c.loserExtensionName,
c.loserKind,
c.loserMcpServerName,
);
return `- ${this.capitalize(source)} '/${c.name}' was renamed to '/${c.renamedTo}'`;
})
.join('\n');
coreEvents.emitFeedback(
'info',
`Conflicts detected for command '/${name}':\n${messages}`,
);
}
/**
* Emits a descriptive notification for a single command conflict.
*/
private emitSingleFeedback(c: SlashCommandConflict): void {
const loserSource = this.getSourceDescription(
c.loserExtensionName,
c.loserKind,
c.loserMcpServerName,
);
const winnerSource = this.getSourceDescription(
c.winnerExtensionName,
c.winnerKind,
c.winnerMcpServerName,
);
coreEvents.emitFeedback(
'info',
`${this.capitalize(loserSource)} '/${c.name}' was renamed to '/${c.renamedTo}' because it conflicts with ${winnerSource}.`,
);
}
private capitalize(s: string): string {
return s.charAt(0).toUpperCase() + s.slice(1);
}
/**
* Returns a human-readable description of a command's source.
*/
private getSourceDescription(
extensionName?: string,
kind?: string,
mcpServerName?: string,
): string {
switch (kind) {
case CommandKind.EXTENSION_FILE:
return extensionName
? `extension '${extensionName}' command`
: 'extension command';
case CommandKind.MCP_PROMPT:
return mcpServerName
? `MCP server '${mcpServerName}' command`
: 'MCP server command';
case CommandKind.USER_FILE:
return 'user command';
case CommandKind.WORKSPACE_FILE:
return 'workspace command';
case CommandKind.BUILT_IN:
return 'built-in command';
default:
return 'existing command';
coreEvents.emitFeedback(
'info',
`Command conflicts detected:\n${conflictMessages}`,
);
}
}
}
@@ -1,177 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi } from 'vitest';
import { SlashCommandResolver } from './SlashCommandResolver.js';
import { CommandKind, type SlashCommand } from '../ui/commands/types.js';
const createMockCommand = (name: string, kind: CommandKind): SlashCommand => ({
name,
description: `Description for ${name}`,
kind,
action: vi.fn(),
});
describe('SlashCommandResolver', () => {
describe('resolve', () => {
it('should return all commands when there are no conflicts', () => {
const cmdA = createMockCommand('a', CommandKind.BUILT_IN);
const cmdB = createMockCommand('b', CommandKind.USER_FILE);
const { finalCommands, conflicts } = SlashCommandResolver.resolve([
cmdA,
cmdB,
]);
expect(finalCommands).toHaveLength(2);
expect(conflicts).toHaveLength(0);
});
it('should rename extension commands when they conflict with built-in', () => {
const builtin = createMockCommand('deploy', CommandKind.BUILT_IN);
const extension = {
...createMockCommand('deploy', CommandKind.EXTENSION_FILE),
extensionName: 'firebase',
};
const { finalCommands, conflicts } = SlashCommandResolver.resolve([
builtin,
extension,
]);
expect(finalCommands.map((c) => c.name)).toContain('deploy');
expect(finalCommands.map((c) => c.name)).toContain('firebase.deploy');
expect(conflicts).toHaveLength(1);
});
it('should prefix both user and workspace commands when they conflict', () => {
const userCmd = createMockCommand('sync', CommandKind.USER_FILE);
const workspaceCmd = createMockCommand(
'sync',
CommandKind.WORKSPACE_FILE,
);
const { finalCommands, conflicts } = SlashCommandResolver.resolve([
userCmd,
workspaceCmd,
]);
const names = finalCommands.map((c) => c.name);
expect(names).not.toContain('sync');
expect(names).toContain('user.sync');
expect(names).toContain('workspace.sync');
expect(conflicts).toHaveLength(1);
expect(conflicts[0].losers).toHaveLength(2); // Both are considered losers
});
it('should prefix file commands but keep built-in names during conflicts', () => {
const builtin = createMockCommand('help', CommandKind.BUILT_IN);
const user = createMockCommand('help', CommandKind.USER_FILE);
const { finalCommands } = SlashCommandResolver.resolve([builtin, user]);
const names = finalCommands.map((c) => c.name);
expect(names).toContain('help');
expect(names).toContain('user.help');
});
it('should prefix both commands when MCP and user file conflict', () => {
const mcp = {
...createMockCommand('test', CommandKind.MCP_PROMPT),
mcpServerName: 'test-server',
};
const user = createMockCommand('test', CommandKind.USER_FILE);
const { finalCommands } = SlashCommandResolver.resolve([mcp, user]);
const names = finalCommands.map((c) => c.name);
expect(names).not.toContain('test');
expect(names).toContain('test-server.test');
expect(names).toContain('user.test');
});
it('should prefix MCP commands with server name when they conflict with built-in', () => {
const builtin = createMockCommand('help', CommandKind.BUILT_IN);
const mcp = {
...createMockCommand('help', CommandKind.MCP_PROMPT),
mcpServerName: 'test-server',
};
const { finalCommands } = SlashCommandResolver.resolve([builtin, mcp]);
const names = finalCommands.map((c) => c.name);
expect(names).toContain('help');
expect(names).toContain('test-server.help');
});
it('should prefix both MCP commands when they conflict with each other', () => {
const mcp1 = {
...createMockCommand('test', CommandKind.MCP_PROMPT),
mcpServerName: 'server1',
};
const mcp2 = {
...createMockCommand('test', CommandKind.MCP_PROMPT),
mcpServerName: 'server2',
};
const { finalCommands } = SlashCommandResolver.resolve([mcp1, mcp2]);
const names = finalCommands.map((c) => c.name);
expect(names).not.toContain('test');
expect(names).toContain('server1.test');
expect(names).toContain('server2.test');
});
it('should favor the last built-in command silently during conflicts', () => {
const builtin1 = {
...createMockCommand('help', CommandKind.BUILT_IN),
description: 'first',
};
const builtin2 = {
...createMockCommand('help', CommandKind.BUILT_IN),
description: 'second',
};
const { finalCommands } = SlashCommandResolver.resolve([
builtin1,
builtin2,
]);
expect(finalCommands).toHaveLength(1);
expect(finalCommands[0].description).toBe('second');
});
it('should fallback to numeric suffixes when both prefix and kind-based prefix are missing', () => {
const cmd1 = createMockCommand('test', CommandKind.BUILT_IN);
const cmd2 = {
...createMockCommand('test', 'unknown' as CommandKind),
};
const { finalCommands } = SlashCommandResolver.resolve([cmd1, cmd2]);
const names = finalCommands.map((c) => c.name);
expect(names).toContain('test');
expect(names).toContain('test1');
});
it('should apply numeric suffixes when renames also conflict', () => {
const user1 = createMockCommand('deploy', CommandKind.USER_FILE);
const user2 = createMockCommand('gcp.deploy', CommandKind.USER_FILE);
const extension = {
...createMockCommand('deploy', CommandKind.EXTENSION_FILE),
extensionName: 'gcp',
};
const { finalCommands } = SlashCommandResolver.resolve([
user1,
user2,
extension,
]);
expect(finalCommands.find((c) => c.name === 'gcp.deploy1')).toBeDefined();
});
});
});
@@ -1,213 +0,0 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type { SlashCommand } from '../ui/commands/types.js';
import { CommandKind } from '../ui/commands/types.js';
import type { CommandConflict } from './types.js';
/**
* Internal registry to track commands and conflicts during resolution.
*/
class CommandRegistry {
readonly commandMap = new Map<string, SlashCommand>();
readonly conflictsMap = new Map<string, CommandConflict>();
readonly firstEncounters = new Map<string, SlashCommand>();
get finalCommands(): SlashCommand[] {
return Array.from(this.commandMap.values());
}
get conflicts(): CommandConflict[] {
return Array.from(this.conflictsMap.values());
}
}
/**
* Resolves name conflicts among slash commands.
*
* Rules:
* 1. Built-in commands always keep the original name.
* 2. All other types are prefixed with their source name (e.g. user.name).
* 3. If multiple non-built-in commands conflict, all of them are renamed.
*/
export class SlashCommandResolver {
/**
* Orchestrates conflict resolution by applying renaming rules to ensures
* every command has a unique name.
*/
static resolve(allCommands: SlashCommand[]): {
finalCommands: SlashCommand[];
conflicts: CommandConflict[];
} {
const registry = new CommandRegistry();
for (const cmd of allCommands) {
const originalName = cmd.name;
let finalName = originalName;
if (registry.firstEncounters.has(originalName)) {
// We've already seen a command with this name, so resolve the conflict.
finalName = this.handleConflict(cmd, registry);
} else {
// Track the first claimant to report them as the conflict reason later.
registry.firstEncounters.set(originalName, cmd);
}
// Store under final name, ensuring the command object reflects it.
registry.commandMap.set(finalName, {
...cmd,
name: finalName,
});
}
return {
finalCommands: registry.finalCommands,
conflicts: registry.conflicts,
};
}
/**
* Resolves a name collision by deciding which command keeps the name and which is renamed.
*
* @param incoming The command currently being processed that has a name collision.
* @param registry The internal state of the resolution process.
* @returns The final name to be assigned to the `incoming` command.
*/
private static handleConflict(
incoming: SlashCommand,
registry: CommandRegistry,
): string {
const collidingName = incoming.name;
const originalClaimant = registry.firstEncounters.get(collidingName)!;
// Incoming built-in takes priority. Prefix any existing owner.
if (incoming.kind === CommandKind.BUILT_IN) {
this.prefixExistingCommand(collidingName, incoming, registry);
return collidingName;
}
// Incoming non-built-in is renamed to its source-prefixed version.
const renamedName = this.getRenamedName(
incoming.name,
this.getPrefix(incoming),
registry.commandMap,
);
this.trackConflict(
registry.conflictsMap,
collidingName,
originalClaimant,
incoming,
renamedName,
);
// Prefix current owner as well if it isn't a built-in.
this.prefixExistingCommand(collidingName, incoming, registry);
return renamedName;
}
/**
* Safely renames the command currently occupying a name in the registry.
*
* @param name The name of the command to prefix.
* @param reason The incoming command that is causing the prefixing.
* @param registry The internal state of the resolution process.
*/
private static prefixExistingCommand(
name: string,
reason: SlashCommand,
registry: CommandRegistry,
): void {
const currentOwner = registry.commandMap.get(name);
// Only non-built-in commands can be prefixed.
if (!currentOwner || currentOwner.kind === CommandKind.BUILT_IN) {
return;
}
// Determine the new name for the owner using its source prefix.
const renamedName = this.getRenamedName(
currentOwner.name,
this.getPrefix(currentOwner),
registry.commandMap,
);
// Update the registry: remove the old name and add the owner under the new name.
registry.commandMap.delete(name);
const renamedOwner = { ...currentOwner, name: renamedName };
registry.commandMap.set(renamedName, renamedOwner);
// Record the conflict so the user can be notified of the prefixing.
this.trackConflict(
registry.conflictsMap,
name,
reason,
currentOwner,
renamedName,
);
}
/**
* Generates a unique name using numeric suffixes if needed.
*/
private static getRenamedName(
name: string,
prefix: string | undefined,
commandMap: Map<string, SlashCommand>,
): string {
const base = prefix ? `${prefix}.${name}` : name;
let renamedName = base;
let suffix = 1;
while (commandMap.has(renamedName)) {
renamedName = `${base}${suffix}`;
suffix++;
}
return renamedName;
}
/**
* Returns a suitable prefix for a conflicting command.
*/
private static getPrefix(cmd: SlashCommand): string | undefined {
switch (cmd.kind) {
case CommandKind.EXTENSION_FILE:
return cmd.extensionName;
case CommandKind.MCP_PROMPT:
return cmd.mcpServerName;
case CommandKind.USER_FILE:
return 'user';
case CommandKind.WORKSPACE_FILE:
return 'workspace';
default:
return undefined;
}
}
/**
* Logs a conflict event.
*/
private static trackConflict(
conflictsMap: Map<string, CommandConflict>,
originalName: string,
reason: SlashCommand,
displacedCommand: SlashCommand,
renamedTo: string,
) {
if (!conflictsMap.has(originalName)) {
conflictsMap.set(originalName, {
name: originalName,
losers: [],
});
}
conflictsMap.get(originalName)!.losers.push({
command: displacedCommand,
renamedTo,
reason,
});
}
}
-9
View File
@@ -22,12 +22,3 @@ export interface ICommandLoader {
*/
loadCommands(signal: AbortSignal): Promise<SlashCommand[]>;
}
export interface CommandConflict {
name: string;
losers: Array<{
command: SlashCommand;
renamedTo: string;
reason: SlashCommand;
}>;
}
+65 -1
View File
@@ -150,6 +150,7 @@ export class AppRig {
private settings: LoadedSettings | undefined;
private testDir: string;
private sessionId: string;
private appRigId: string;
private pendingConfirmations = new Map<string, PendingConfirmation>();
private breakpointTools = new Set<string | undefined>();
@@ -165,6 +166,7 @@ export class AppRig {
this.testDir = fs.mkdtempSync(
path.join(os.tmpdir(), `gemini-app-rig-${uniqueId.slice(0, 8)}-`),
);
this.appRigId = path.basename(this.testDir).toLowerCase();
this.sessionId = `test-session-${uniqueId}`;
activeRigs.set(this.sessionId, this);
}
@@ -680,9 +682,10 @@ export class AppRig {
await this.waitUntil(
() => {
const frame = this.lastFrame;
return typeof pattern === 'string'
const matched = typeof pattern === 'string'
? frame.includes(pattern)
: pattern.test(frame);
return matched;
},
{
timeout,
@@ -701,6 +704,67 @@ export class AppRig {
await this.pressEnter();
}
getSentRequests() {
if (!this.config) throw new Error('AppRig not initialized');
return this.config.getContentGenerator().getSentRequests?.() || [];
}
/**
* Helper to get the curated history (contents) sent in the most recent model request.
* This method scrubs unstable data like temp paths and IDs for deterministic goldens.
*/
getLastSentRequestContents() {
const requests = this.getSentRequests();
if (requests.length === 0) return [];
const contents = requests[requests.length - 1].contents || [];
return this.scrubUnstableData(contents);
}
/**
* Gets the final curated history of the active chat session.
*/
getCuratedHistory() {
if (!this.config) throw new Error('AppRig not initialized');
const history = this.config.getGeminiClient().getChat().getHistory(true);
return this.scrubUnstableData(history);
}
private scrubUnstableData(contents: any) {
// Deeply scrub unstable data
const scrubbed = JSON.parse(
JSON.stringify(contents)
.replace(new RegExp(this.testDir, 'g'), '<TEST_DIR>')
.replace(new RegExp(this.appRigId, 'g'), '<APP_RIG_ID>')
.replace(new RegExp(this.sessionId, 'g'), '<SESSION_ID>'),
);
if (scrubbed.length > 0) {
if (scrubbed[0].parts[0].text?.includes('<session_context>')) {
scrubbed[0].parts[0].text = '<SESSION_CONTEXT>';
}
}
const removeIds = (obj: any) => {
if (Array.isArray(obj)) {
obj.forEach(removeIds);
} else if (obj && typeof obj === 'object') {
if (obj.functionCall) {
obj.functionCall.id = '<CALL_ID>';
}
if (obj.functionResponse) {
obj.functionResponse.id = '<CALL_ID>';
if (obj.functionResponse?.response?.original_output_file) {
obj.functionResponse.response.original_output_file = '<TMP_FILE>';
}
}
Object.values(obj).forEach(removeIds);
}
};
removeIds(scrubbed);
return scrubbed;
}
async unmount() {
// Clean up global state for this session
sessionStateMap.delete(this.sessionId);
@@ -0,0 +1,4 @@
{"method":"generateContentStream","response":[{"candidates":[{"content":{"role":"model","parts":[{"text":"I will now checkpoint our progress."},{"functionCall":{"name":"checkpoint_state","args":{"summary":"GOAL: Implementation of session continuity.\nPROGRESS: Tools implemented.\nCONSTRAINT: Use high-fidelity summary."}}}]},"finishReason":"STOP"}]}]}
{"method":"generateContentStream","response":[{"candidates":[{"content":{"role":"model","parts":[{"text":"Checkpoint created. Now I will trigger compression to clear the context."},{"functionCall":{"name":"compress","args":{}}}]},"finishReason":"STOP"}]}]}
{"method":"generateContent","response":{"candidates":[{"content":{"role":"model","parts":[{"text":"<state_snapshot>\n<overall_goal>Implement session continuity</overall_goal>\n<active_constraints>Use high-fidelity summary</active_constraints>\n<key_knowledge>Tools implemented: checkpoint_state, compress</key_knowledge>\n<task_state>1. [DONE] Implement tools\n2. [IN PROGRESS] Verify continuity\n</task_state>\n</state_snapshot>"}]}}],"finishReason":"STOP"}}
{"method":"generateContentStream","response":[{"candidates":[{"content":{"role":"model","parts":[{"text":"Compression successful. I have clear context and I remember our mission."}]},"finishReason":"STOP"}]}]}
@@ -0,0 +1,3 @@
{"method":"generateContentStream","response":[{"candidates":[{"content":{"role":"model","parts":[{"text":"**Thought**\nI need to search for SECRET in the src/ directory."},{"functionCall":{"name":"read_file","args":{"file_path":"src/foo.txt"}}}]},"finishReason":"STOP"}]}]}
{"method":"generateContentStream","response":[{"candidates":[{"content":{"role":"model","parts":[{"text":"**Thought**\nThe output is very noisy. I will distill it to keep the context clean."},{"functionCall":{"name":"distill_result","args":{"revised_text":"Found SECRET_KEY=\"12345\" in src/env.ts"}}}]},"finishReason":"STOP"}]}]}
{"method":"generateContentStream","response":[{"candidates":[{"content":{"role":"model","parts":[{"text":"I found the SECRET_KEY=\"12345\" in src/env.ts after distilling the search results."}]},"finishReason":"STOP"}]}]}
@@ -65,7 +65,6 @@ export function mockCoreDebugLogger<T extends Record<string, unknown>>(
return {
...actual,
coreEvents: {
// eslint-disable-next-line no-restricted-syntax
...(typeof actual['coreEvents'] === 'object' &&
actual['coreEvents'] !== null
? actual['coreEvents']
-1
View File
@@ -96,7 +96,6 @@ function isInkRenderMetrics(
typeof m === 'object' &&
m !== null &&
'output' in m &&
// eslint-disable-next-line no-restricted-syntax
typeof m['output'] === 'string'
);
}
+59 -78
View File
@@ -160,7 +160,6 @@ vi.mock('./hooks/useIdeTrustListener.js');
vi.mock('./hooks/useMessageQueue.js');
vi.mock('./hooks/useApprovalModeIndicator.js');
vi.mock('./hooks/useGitBranchName.js');
vi.mock('./hooks/useExtensionUpdates.js');
vi.mock('./contexts/VimModeContext.js');
vi.mock('./contexts/SessionContext.js');
vi.mock('./components/shared/text-buffer.js');
@@ -219,10 +218,6 @@ import { useIdeTrustListener } from './hooks/useIdeTrustListener.js';
import { useMessageQueue } from './hooks/useMessageQueue.js';
import { useApprovalModeIndicator } from './hooks/useApprovalModeIndicator.js';
import { useGitBranchName } from './hooks/useGitBranchName.js';
import {
useConfirmUpdateRequests,
useExtensionUpdates,
} from './hooks/useExtensionUpdates.js';
import { useVimMode } from './contexts/VimModeContext.js';
import { useSessionStats } from './contexts/SessionContext.js';
import { useTextBuffer } from './components/shared/text-buffer.js';
@@ -232,7 +227,10 @@ import { useInputHistoryStore } from './hooks/useInputHistoryStore.js';
import { useKeypress, type Key } from './hooks/useKeypress.js';
import * as useKeypressModule from './hooks/useKeypress.js';
import { useSuspend } from './hooks/useSuspend.js';
import { measureElement } from 'ink';
import { useTerminalSize } from './hooks/useTerminalSize.js';
import {
ShellExecutionService,
writeToStdout,
enableMouseEvents,
disableMouseEvents,
@@ -301,8 +299,6 @@ describe('AppContainer State Management', () => {
const mockedUseMessageQueue = useMessageQueue as Mock;
const mockedUseApprovalModeIndicator = useApprovalModeIndicator as Mock;
const mockedUseGitBranchName = useGitBranchName as Mock;
const mockedUseConfirmUpdateRequests = useConfirmUpdateRequests as Mock;
const mockedUseExtensionUpdates = useExtensionUpdates as Mock;
const mockedUseVimMode = useVimMode as Mock;
const mockedUseSessionStats = useSessionStats as Mock;
const mockedUseTextBuffer = useTextBuffer as Mock;
@@ -455,15 +451,6 @@ describe('AppContainer State Management', () => {
isFocused: true,
hasReceivedFocusEvent: true,
});
mockedUseConfirmUpdateRequests.mockReturnValue({
addConfirmUpdateExtensionRequest: vi.fn(),
confirmUpdateExtensionRequests: [],
});
mockedUseExtensionUpdates.mockReturnValue({
extensionsUpdateState: new Map(),
extensionsUpdateStateInternal: new Map(),
dispatchExtensionStateUpdate: vi.fn(),
});
// Mock Config
mockConfig = makeFakeConfig();
@@ -2194,6 +2181,35 @@ describe('AppContainer State Management', () => {
});
});
describe('Terminal Height Calculation', () => {
const mockedMeasureElement = measureElement as Mock;
const mockedUseTerminalSize = useTerminalSize as Mock;
it('should prevent terminal height from being less than 1', async () => {
const resizePtySpy = vi.spyOn(ShellExecutionService, 'resizePty');
// Arrange: Simulate a small terminal and a large footer
mockedUseTerminalSize.mockReturnValue({ columns: 80, rows: 5 });
mockedMeasureElement.mockReturnValue({ width: 80, height: 10 }); // Footer is taller than the screen
mockedUseGeminiStream.mockReturnValue({
...DEFAULT_GEMINI_STREAM_MOCK,
activePtyId: 'some-id',
});
let unmount: () => void;
await act(async () => {
const result = renderAppContainer();
unmount = result.unmount;
});
await waitFor(() => expect(resizePtySpy).toHaveBeenCalled());
const lastCall =
resizePtySpy.mock.calls[resizePtySpy.mock.calls.length - 1];
// Check the height argument specifically
expect(lastCall[2]).toBe(1);
unmount!();
});
});
describe('Keyboard Input Handling (CTRL+C / CTRL+D)', () => {
let mockHandleSlashCommand: Mock;
let mockCancelOngoingRequest: Mock;
@@ -3109,6 +3125,30 @@ describe('AppContainer State Management', () => {
});
});
describe('Shell Interaction', () => {
it('should not crash if resizing the pty fails', async () => {
const resizePtySpy = vi
.spyOn(ShellExecutionService, 'resizePty')
.mockImplementation(() => {
throw new Error('Cannot resize a pty that has already exited');
});
mockedUseGeminiStream.mockReturnValue({
...DEFAULT_GEMINI_STREAM_MOCK,
activePtyId: 'some-pty-id', // Make sure activePtyId is set
});
// The main assertion is that the render does not throw.
let unmount: () => void;
await act(async () => {
const result = renderAppContainer();
unmount = result.unmount;
});
await waitFor(() => expect(resizePtySpy).toHaveBeenCalled());
unmount!();
});
});
describe('Banner Text', () => {
it('should render placeholder banner text for USE_GEMINI auth type', async () => {
const config = makeFakeConfig();
@@ -3409,63 +3449,6 @@ describe('AppContainer State Management', () => {
unmount!();
});
it('resets the hint timer when a new component overflows (overflowingIdsSize increases)', async () => {
let unmount: () => void;
await act(async () => {
const result = renderAppContainer();
unmount = result.unmount;
});
await waitFor(() => expect(capturedUIState).toBeTruthy());
// 1. Trigger first overflow
act(() => {
capturedOverflowActions.addOverflowingId('test-id-1');
});
await waitFor(() => {
expect(capturedUIState.showIsExpandableHint).toBe(true);
});
// 2. Advance half the duration
act(() => {
vi.advanceTimersByTime(EXPAND_HINT_DURATION_MS / 2);
});
expect(capturedUIState.showIsExpandableHint).toBe(true);
// 3. Trigger second overflow (this should reset the timer)
act(() => {
capturedOverflowActions.addOverflowingId('test-id-2');
});
// Advance by 1ms to allow the OverflowProvider's 0ms batching timeout to fire
// and flush the state update to AppContainer, triggering the reset.
act(() => {
vi.advanceTimersByTime(1);
});
await waitFor(() => {
expect(capturedUIState.showIsExpandableHint).toBe(true);
});
// 4. Advance enough that the ORIGINAL timer would have expired
// Subtracting 1ms since we advanced it above to flush the state.
act(() => {
vi.advanceTimersByTime(EXPAND_HINT_DURATION_MS / 2 + 100 - 1);
});
// The hint should STILL be visible because the timer reset at step 3
expect(capturedUIState.showIsExpandableHint).toBe(true);
// 5. Advance to the end of the NEW timer
act(() => {
vi.advanceTimersByTime(EXPAND_HINT_DURATION_MS / 2 - 100);
});
await waitFor(() => {
expect(capturedUIState.showIsExpandableHint).toBe(false);
});
unmount!();
});
it('toggles expansion state and resets the hint timer when Ctrl+O is pressed in Standard Mode', async () => {
let unmount: () => void;
let stdin: ReturnType<typeof renderAppContainer>['stdin'];
@@ -3607,7 +3590,7 @@ describe('AppContainer State Management', () => {
unmount!();
});
it('DOES set showIsExpandableHint when overflow occurs in Alternate Buffer Mode', async () => {
it('does NOT set showIsExpandableHint when overflow occurs in Alternate Buffer Mode', async () => {
const alternateSettings = mergeSettings({}, {}, {}, {}, true);
const settingsWithAlternateBuffer = {
merged: {
@@ -3635,10 +3618,8 @@ describe('AppContainer State Management', () => {
capturedOverflowActions.addOverflowingId('test-id');
});
// Should NOW show hint because we are in Alternate Buffer Mode
await waitFor(() => {
expect(capturedUIState.showIsExpandableHint).toBe(true);
});
// Should NOT show hint because we are in Alternate Buffer Mode
expect(capturedUIState.showIsExpandableHint).toBe(false);
unmount!();
});
+35 -8
View File
@@ -283,18 +283,19 @@ export const AppContainer = (props: AppContainerProps) => {
* Manages the visibility and x-second timer for the expansion hint.
*
* This effect triggers the timer countdown whenever an overflow is detected
* or the user manually toggles the expansion state with Ctrl+O.
* By depending on overflowingIdsSize, the timer resets when *new* views
* overflow, but avoids infinitely resetting during single-view streaming.
* or the user manually toggles the expansion state with Ctrl+O. We use a stable
* boolean dependency (hasOverflowState) to ensure the timer only resets on
* genuine state transitions, preventing it from infinitely resetting during
* active text streaming.
*
* In alternate buffer mode, we don't trigger the hint automatically on overflow
* to avoid noise, but the user can still trigger it manually with Ctrl+O.
*/
useEffect(() => {
if (hasOverflowState) {
if (hasOverflowState && !isAlternateBuffer) {
triggerExpandHint(true);
}
}, [hasOverflowState, overflowingIdsSize, triggerExpandHint]);
}, [hasOverflowState, isAlternateBuffer, triggerExpandHint]);
const [defaultBannerText, setDefaultBannerText] = useState('');
const [warningBannerText, setWarningBannerText] = useState('');
@@ -1009,10 +1010,10 @@ Logging in with Google... Restarting Gemini CLI to continue.
historyManager.addItem(
{
type: MessageType.INFO,
text: `Memory reloaded successfully. ${
text: `Memory refreshed successfully. ${
flattenedMemory.length > 0
? `Loaded ${flattenedMemory.length} characters from ${fileCount} file(s)`
: 'No memory content found'
? `Loaded ${flattenedMemory.length} characters from ${fileCount} file(s).`
: 'No memory content found.'
}`,
},
Date.now(),
@@ -1420,6 +1421,32 @@ Logging in with Google... Restarting Gemini CLI to continue.
const initialPromptSubmitted = useRef(false);
const geminiClient = config.getGeminiClient();
useEffect(() => {
if (activePtyId) {
try {
ShellExecutionService.resizePty(
activePtyId,
Math.floor(terminalWidth * SHELL_WIDTH_FRACTION),
Math.max(
Math.floor(availableTerminalHeight - SHELL_HEIGHT_PADDING),
1,
),
);
} catch (e) {
// This can happen in a race condition where the pty exits
// right before we try to resize it.
if (
!(
e instanceof Error &&
e.message.includes('Cannot resize a pty that has already exited')
)
) {
throw e;
}
}
}
}, [terminalWidth, availableTerminalHeight, activePtyId]);
useEffect(() => {
if (
initialPrompt &&
@@ -29,16 +29,9 @@ vi.mock('../hooks/useKeypress.js', () => ({
useKeypress: vi.fn(),
}));
vi.mock('../components/shared/text-buffer.js', async (importOriginal) => {
const actual =
await importOriginal<
typeof import('../components/shared/text-buffer.js')
>();
return {
...actual,
useTextBuffer: vi.fn(),
};
});
vi.mock('../components/shared/text-buffer.js', () => ({
useTextBuffer: vi.fn(),
}));
vi.mock('../contexts/UIStateContext.js', () => ({
useUIState: vi.fn(() => ({
@@ -105,40 +105,34 @@ describe('agentsCommand', () => {
);
});
it('should reload the agent registry when reload subcommand is called', async () => {
it('should reload the agent registry when refresh subcommand is called', async () => {
const reloadSpy = vi.fn().mockResolvedValue(undefined);
mockConfig.getAgentRegistry = vi.fn().mockReturnValue({
reload: reloadSpy,
});
const reloadCommand = agentsCommand.subCommands?.find(
(cmd) => cmd.name === 'reload',
const refreshCommand = agentsCommand.subCommands?.find(
(cmd) => cmd.name === 'refresh',
);
expect(reloadCommand).toBeDefined();
expect(refreshCommand).toBeDefined();
const result = await reloadCommand!.action!(mockContext, '');
const result = await refreshCommand!.action!(mockContext, '');
expect(reloadSpy).toHaveBeenCalled();
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.INFO,
text: 'Reloading agent registry...',
}),
);
expect(result).toEqual({
type: 'message',
messageType: 'info',
content: 'Agents reloaded successfully',
content: 'Agents refreshed successfully.',
});
});
it('should show an error if agent registry is not available during reload', async () => {
it('should show an error if agent registry is not available during refresh', async () => {
mockConfig.getAgentRegistry = vi.fn().mockReturnValue(undefined);
const reloadCommand = agentsCommand.subCommands?.find(
(cmd) => cmd.name === 'reload',
const refreshCommand = agentsCommand.subCommands?.find(
(cmd) => cmd.name === 'refresh',
);
const result = await reloadCommand!.action!(mockContext, '');
const result = await refreshCommand!.action!(mockContext, '');
expect(result).toEqual({
type: 'message',
@@ -322,9 +322,9 @@ const configCommand: SlashCommand = {
completion: completeAllAgents,
};
const agentsReloadCommand: SlashCommand = {
name: 'reload',
altNames: ['refresh'],
const agentsRefreshCommand: SlashCommand = {
name: 'refresh',
altNames: ['reload'],
description: 'Reload the agent registry',
kind: CommandKind.BUILT_IN,
action: async (context: CommandContext) => {
@@ -340,7 +340,7 @@ const agentsReloadCommand: SlashCommand = {
context.ui.addItem({
type: MessageType.INFO,
text: 'Reloading agent registry...',
text: 'Refreshing agent registry...',
});
await agentRegistry.reload();
@@ -348,7 +348,7 @@ const agentsReloadCommand: SlashCommand = {
return {
type: 'message',
messageType: 'info',
content: 'Agents reloaded successfully',
content: 'Agents refreshed successfully.',
};
},
};
@@ -359,7 +359,7 @@ export const agentsCommand: SlashCommand = {
kind: CommandKind.BUILT_IN,
subCommands: [
agentsListCommand,
agentsReloadCommand,
agentsRefreshCommand,
enableCommand,
disableCommand,
configCommand,
@@ -755,7 +755,7 @@ describe('extensionsCommand', () => {
await uninstallAction!(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.ERROR,
text: 'Usage: /extensions uninstall <extension-names...>|--all',
text: 'Usage: /extensions uninstall <extension-name>',
});
expect(mockUninstallExtension).not.toHaveBeenCalled();
});
@@ -892,7 +892,7 @@ describe('extensionsCommand', () => {
});
});
describe('reload', () => {
describe('restart', () => {
let restartAction: SlashCommand['action'];
let mockRestartExtension: MockedFunction<
typeof ExtensionLoader.prototype.restartExtension
@@ -900,7 +900,7 @@ describe('extensionsCommand', () => {
beforeEach(() => {
restartAction = extensionsCommand().subCommands?.find(
(c) => c.name === 'reload',
(c) => c.name === 'restart',
)?.action;
expect(restartAction).not.toBeNull();
@@ -911,7 +911,7 @@ describe('extensionsCommand', () => {
getExtensions: mockGetExtensions,
restartExtension: mockRestartExtension,
}));
mockContext.invocation!.name = 'reload';
mockContext.invocation!.name = 'restart';
});
it('should show a message if no extensions are installed', async () => {
@@ -930,7 +930,7 @@ describe('extensionsCommand', () => {
});
});
it('reloads all active extensions when --all is provided', async () => {
it('restarts all active extensions when --all is provided', async () => {
const mockExtensions = [
{ name: 'ext1', isActive: true },
{ name: 'ext2', isActive: true },
@@ -946,13 +946,13 @@ describe('extensionsCommand', () => {
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.INFO,
text: 'Reloading 2 extensions...',
text: 'Restarting 2 extensions...',
}),
);
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.INFO,
text: '2 extensions reloaded successfully',
text: '2 extensions restarted successfully.',
}),
);
expect(mockContext.ui.dispatchExtensionStateUpdate).toHaveBeenCalledWith({
@@ -986,7 +986,7 @@ describe('extensionsCommand', () => {
);
});
it('reloads only specified active extensions', async () => {
it('restarts only specified active extensions', async () => {
const mockExtensions = [
{ name: 'ext1', isActive: false },
{ name: 'ext2', isActive: true },
@@ -1024,13 +1024,13 @@ describe('extensionsCommand', () => {
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.ERROR,
text: 'Usage: /extensions reload <extension-names>|--all',
text: 'Usage: /extensions restart <extension-names>|--all',
}),
);
expect(mockRestartExtension).not.toHaveBeenCalled();
});
it('handles errors during extension reload', async () => {
it('handles errors during extension restart', async () => {
const mockExtensions = [
{ name: 'ext1', isActive: true },
] as GeminiCLIExtension[];
@@ -1043,7 +1043,7 @@ describe('extensionsCommand', () => {
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.ERROR,
text: 'Failed to reload some extensions:\n ext1: Failed to restart',
text: 'Failed to restart some extensions:\n ext1: Failed to restart',
}),
);
});
@@ -1066,7 +1066,7 @@ describe('extensionsCommand', () => {
);
});
it('does not reload any extensions if none are found', async () => {
it('does not restart any extensions if none are found', async () => {
const mockExtensions = [
{ name: 'ext1', isActive: true },
] as GeminiCLIExtension[];
@@ -1083,8 +1083,8 @@ describe('extensionsCommand', () => {
);
});
it('should suggest only enabled extension names for the reload command', async () => {
mockContext.invocation!.name = 'reload';
it('should suggest only enabled extension names for the restart command', async () => {
mockContext.invocation!.name = 'restart';
const mockExtensions = [
{ name: 'ext1', isActive: true },
{ name: 'ext2', isActive: false },
@@ -176,7 +176,7 @@ async function restartAction(
if (!all && names?.length === 0) {
context.ui.addItem({
type: MessageType.ERROR,
text: 'Usage: /extensions reload <extension-names>|--all',
text: 'Usage: /extensions restart <extension-names>|--all',
});
return Promise.resolve();
}
@@ -208,12 +208,12 @@ async function restartAction(
const s = extensionsToRestart.length > 1 ? 's' : '';
const reloadingMessage = {
const restartingMessage = {
type: MessageType.INFO,
text: `Reloading ${extensionsToRestart.length} extension${s}...`,
text: `Restarting ${extensionsToRestart.length} extension${s}...`,
color: theme.text.primary,
};
context.ui.addItem(reloadingMessage);
context.ui.addItem(restartingMessage);
const results = await Promise.allSettled(
extensionsToRestart.map(async (extension) => {
@@ -254,12 +254,12 @@ async function restartAction(
.join('\n ');
context.ui.addItem({
type: MessageType.ERROR,
text: `Failed to reload some extensions:\n ${errorMessages}`,
text: `Failed to restart some extensions:\n ${errorMessages}`,
});
} else {
const infoItem: HistoryItemInfo = {
type: MessageType.INFO,
text: `${extensionsToRestart.length} extension${s} reloaded successfully`,
text: `${extensionsToRestart.length} extension${s} restarted successfully.`,
icon: emptyIcon,
color: theme.text.primary,
};
@@ -594,53 +594,33 @@ async function uninstallAction(context: CommandContext, args: string) {
return;
}
const uninstallArgs = args.split(' ').filter((value) => value.length > 0);
const all = uninstallArgs.includes('--all');
const names = uninstallArgs.filter((a) => !a.startsWith('--'));
if (!all && names.length === 0) {
const name = args.trim();
if (!name) {
context.ui.addItem({
type: MessageType.ERROR,
text: `Usage: /extensions uninstall <extension-names...>|--all`,
text: `Usage: /extensions uninstall <extension-name>`,
});
return;
}
let namesToUninstall: string[] = [];
if (all) {
namesToUninstall = extensionLoader.getExtensions().map((ext) => ext.name);
} else {
namesToUninstall = names;
}
context.ui.addItem({
type: MessageType.INFO,
text: `Uninstalling extension "${name}"...`,
});
if (namesToUninstall.length === 0) {
try {
await extensionLoader.uninstallExtension(name, false);
context.ui.addItem({
type: MessageType.INFO,
text: all ? 'No extensions installed.' : 'No extension name provided.',
text: `Extension "${name}" uninstalled successfully.`,
});
return;
}
for (const extensionName of namesToUninstall) {
} catch (error) {
context.ui.addItem({
type: MessageType.INFO,
text: `Uninstalling extension "${extensionName}"...`,
type: MessageType.ERROR,
text: `Failed to uninstall extension "${name}": ${getErrorMessage(
error,
)}`,
});
try {
await extensionLoader.uninstallExtension(extensionName, false);
context.ui.addItem({
type: MessageType.INFO,
text: `Extension "${extensionName}" uninstalled successfully.`,
});
} catch (error) {
context.ui.addItem({
type: MessageType.ERROR,
text: `Failed to uninstall extension "${extensionName}": ${getErrorMessage(
error,
)}`,
});
}
}
}
@@ -729,8 +709,7 @@ export function completeExtensions(
}
if (
context.invocation?.name === 'disable' ||
context.invocation?.name === 'restart' ||
context.invocation?.name === 'reload'
context.invocation?.name === 'restart'
) {
extensions = extensions.filter((ext) => ext.isActive);
}
@@ -825,10 +804,9 @@ const exploreExtensionsCommand: SlashCommand = {
action: exploreAction,
};
const reloadCommand: SlashCommand = {
name: 'reload',
altNames: ['restart'],
description: 'Reload all extensions',
const restartCommand: SlashCommand = {
name: 'restart',
description: 'Restart all extensions',
kind: CommandKind.BUILT_IN,
autoExecute: false,
action: restartAction,
@@ -865,7 +843,7 @@ export function extensionsCommand(
listExtensionsCommand,
updateExtensionsCommand,
exploreExtensionsCommand,
reloadCommand,
restartCommand,
...conditionalCommands,
],
action: (context, args) =>
+8 -8
View File
@@ -149,7 +149,7 @@ const authCommand: SlashCommand = {
return {
type: 'message',
messageType: 'info',
content: `Successfully authenticated and reloaded tools for '${serverName}'`,
content: `Successfully authenticated and refreshed tools for '${serverName}'.`,
};
} catch (error) {
return {
@@ -325,10 +325,10 @@ const schemaCommand: SlashCommand = {
action: (context) => listAction(context, true, true),
};
const reloadCommand: SlashCommand = {
name: 'reload',
altNames: ['refresh'],
description: 'Reloads MCP servers',
const refreshCommand: SlashCommand = {
name: 'refresh',
altNames: ['reload'],
description: 'Restarts MCP servers',
kind: CommandKind.BUILT_IN,
autoExecute: true,
action: async (
@@ -354,7 +354,7 @@ const reloadCommand: SlashCommand = {
context.ui.addItem({
type: 'info',
text: 'Reloading MCP servers...',
text: 'Restarting MCP servers...',
});
await mcpClientManager.restart();
@@ -460,7 +460,7 @@ async function handleEnableDisable(
const mcpClientManager = config.getMcpClientManager();
if (mcpClientManager) {
context.ui.addItem(
{ type: 'info', text: 'Reloading MCP servers...' },
{ type: 'info', text: 'Restarting MCP servers...' },
Date.now(),
);
await mcpClientManager.restart();
@@ -521,7 +521,7 @@ export const mcpCommand: SlashCommand = {
descCommand,
schemaCommand,
authCommand,
reloadCommand,
refreshCommand,
enableCommand,
disableCommand,
],
@@ -39,13 +39,13 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
return {
type: 'message',
messageType: 'info',
content: `Memory reloaded successfully. Loaded ${memoryContent.length} characters from ${fileCount} file(s).`,
content: `Memory refreshed successfully. Loaded ${memoryContent.length} characters from ${fileCount} file(s).`,
};
}
return {
type: 'message',
messageType: 'info',
content: 'Memory reloaded successfully.',
content: 'Memory refreshed successfully.',
};
}),
showMemory: vi.fn(),
@@ -63,7 +63,7 @@ describe('memoryCommand', () => {
let mockContext: CommandContext;
const getSubCommand = (
name: 'show' | 'add' | 'reload' | 'list',
name: 'show' | 'add' | 'refresh' | 'list',
): SlashCommand => {
const subCommand = memoryCommand.subCommands?.find(
(cmd) => cmd.name === name,
@@ -206,15 +206,15 @@ describe('memoryCommand', () => {
});
});
describe('/memory reload', () => {
let reloadCommand: SlashCommand;
describe('/memory refresh', () => {
let refreshCommand: SlashCommand;
let mockSetUserMemory: Mock;
let mockSetGeminiMdFileCount: Mock;
let mockSetGeminiMdFilePaths: Mock;
let mockContextManagerRefresh: Mock;
beforeEach(() => {
reloadCommand = getSubCommand('reload');
refreshCommand = getSubCommand('refresh');
mockSetUserMemory = vi.fn();
mockSetGeminiMdFileCount = vi.fn();
mockSetGeminiMdFilePaths = vi.fn();
@@ -266,7 +266,7 @@ describe('memoryCommand', () => {
});
it('should use ContextManager.refresh when JIT is enabled', async () => {
if (!reloadCommand.action) throw new Error('Command has no action');
if (!refreshCommand.action) throw new Error('Command has no action');
// Enable JIT in mock config
const config = mockContext.services.config;
@@ -276,7 +276,7 @@ describe('memoryCommand', () => {
vi.mocked(config.getUserMemory).mockReturnValue('JIT Memory Content');
vi.mocked(config.getGeminiMdFileCount).mockReturnValue(3);
await reloadCommand.action(mockContext, '');
await refreshCommand.action(mockContext, '');
expect(mockContextManagerRefresh).toHaveBeenCalledOnce();
expect(mockRefreshServerHierarchicalMemory).not.toHaveBeenCalled();
@@ -284,29 +284,29 @@ describe('memoryCommand', () => {
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
{
type: MessageType.INFO,
text: 'Memory reloaded successfully. Loaded 18 characters from 3 file(s).',
text: 'Memory refreshed successfully. Loaded 18 characters from 3 file(s).',
},
expect.any(Number),
);
});
it('should display success message when memory is reloaded with content (Legacy)', async () => {
if (!reloadCommand.action) throw new Error('Command has no action');
it('should display success message when memory is refreshed with content (Legacy)', async () => {
if (!refreshCommand.action) throw new Error('Command has no action');
const successMessage = {
type: 'message',
messageType: MessageType.INFO,
content:
'Memory reloaded successfully. Loaded 18 characters from 2 file(s).',
'Memory refreshed successfully. Loaded 18 characters from 2 file(s).',
};
mockRefreshMemory.mockResolvedValue(successMessage);
await reloadCommand.action(mockContext, '');
await refreshCommand.action(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
{
type: MessageType.INFO,
text: 'Reloading memory from source files...',
text: 'Refreshing memory from source files...',
},
expect.any(Number),
);
@@ -316,42 +316,42 @@ describe('memoryCommand', () => {
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
{
type: MessageType.INFO,
text: 'Memory reloaded successfully. Loaded 18 characters from 2 file(s).',
text: 'Memory refreshed successfully. Loaded 18 characters from 2 file(s).',
},
expect.any(Number),
);
});
it('should display success message when memory is reloaded with no content', async () => {
if (!reloadCommand.action) throw new Error('Command has no action');
it('should display success message when memory is refreshed with no content', async () => {
if (!refreshCommand.action) throw new Error('Command has no action');
const successMessage = {
type: 'message',
messageType: MessageType.INFO,
content: 'Memory reloaded successfully. No memory content found.',
content: 'Memory refreshed successfully. No memory content found.',
};
mockRefreshMemory.mockResolvedValue(successMessage);
await reloadCommand.action(mockContext, '');
await refreshCommand.action(mockContext, '');
expect(mockRefreshMemory).toHaveBeenCalledOnce();
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
{
type: MessageType.INFO,
text: 'Memory reloaded successfully. No memory content found.',
text: 'Memory refreshed successfully. No memory content found.',
},
expect.any(Number),
);
});
it('should display an error message if reloading fails', async () => {
if (!reloadCommand.action) throw new Error('Command has no action');
it('should display an error message if refreshing fails', async () => {
if (!refreshCommand.action) throw new Error('Command has no action');
const error = new Error('Failed to read memory files.');
mockRefreshMemory.mockRejectedValue(error);
await reloadCommand.action(mockContext, '');
await refreshCommand.action(mockContext, '');
expect(mockRefreshMemory).toHaveBeenCalledOnce();
expect(mockSetUserMemory).not.toHaveBeenCalled();
@@ -361,27 +361,27 @@ describe('memoryCommand', () => {
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
{
type: MessageType.ERROR,
text: `Error reloading memory: ${error.message}`,
text: `Error refreshing memory: ${error.message}`,
},
expect.any(Number),
);
});
it('should not throw if config service is unavailable', async () => {
if (!reloadCommand.action) throw new Error('Command has no action');
if (!refreshCommand.action) throw new Error('Command has no action');
const nullConfigContext = createMockCommandContext({
services: { config: null },
});
await expect(
reloadCommand.action(nullConfigContext, ''),
refreshCommand.action(nullConfigContext, ''),
).resolves.toBeUndefined();
expect(nullConfigContext.ui.addItem).toHaveBeenCalledWith(
{
type: MessageType.INFO,
text: 'Reloading memory from source files...',
text: 'Refreshing memory from source files...',
},
expect.any(Number),
);
@@ -63,16 +63,16 @@ export const memoryCommand: SlashCommand = {
},
},
{
name: 'reload',
altNames: ['refresh'],
description: 'Reload the memory from the source',
name: 'refresh',
altNames: ['reload'],
description: 'Refresh the memory from the source',
kind: CommandKind.BUILT_IN,
autoExecute: true,
action: async (context) => {
context.ui.addItem(
{
type: MessageType.INFO,
text: 'Reloading memory from source files...',
text: 'Refreshing memory from source files...',
},
Date.now(),
);
@@ -95,7 +95,7 @@ export const memoryCommand: SlashCommand = {
{
type: MessageType.ERROR,
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
text: `Error reloading memory: ${(error as Error).message}`,
text: `Error refreshing memory: ${(error as Error).message}`,
},
Date.now(),
);
@@ -20,7 +20,6 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => {
UserAccountManager: vi.fn().mockImplementation(() => ({
getCachedGoogleAccount: vi.fn().mockReturnValue('mock@example.com'),
})),
getG1CreditBalance: vi.fn().mockReturnValue(undefined),
};
});
+1 -6
View File
@@ -177,9 +177,7 @@ export type SlashCommandActionReturn =
export enum CommandKind {
BUILT_IN = 'built-in',
USER_FILE = 'user-file',
WORKSPACE_FILE = 'workspace-file',
EXTENSION_FILE = 'extension-file',
FILE = 'file',
MCP_PROMPT = 'mcp-prompt',
AGENT = 'agent',
}
@@ -205,9 +203,6 @@ export interface SlashCommand {
extensionName?: string;
extensionId?: string;
// Optional metadata for MCP commands
mcpServerName?: string;
// The action to run. Optional for parent commands that only group sub-commands.
action?: (
context: CommandContext,
@@ -8,14 +8,22 @@ import type React from 'react';
import { Box, Text } from 'ink';
import { theme } from '../semantic-colors.js';
import { ApprovalMode } from '@google/gemini-cli-core';
import { formatCommand } from '../utils/keybindingUtils.js';
import { Command } from '../../config/keyBindings.js';
interface ApprovalModeIndicatorProps {
approvalMode: ApprovalMode;
allowPlanMode?: boolean;
}
export const APPROVAL_MODE_TEXT = {
AUTO_EDIT: 'auto-accept edits',
PLAN: 'plan',
YOLO: 'YOLO',
HINT_SWITCH_TO_PLAN_MODE: 'shift+tab to plan',
HINT_SWITCH_TO_MANUAL_MODE: 'shift+tab to manual',
HINT_SWITCH_TO_AUTO_EDIT_MODE: 'shift+tab to accept edits',
HINT_SWITCH_TO_YOLO_MODE: 'ctrl+y',
};
export const ApprovalModeIndicator: React.FC<ApprovalModeIndicatorProps> = ({
approvalMode,
allowPlanMode,
@@ -24,32 +32,29 @@ export const ApprovalModeIndicator: React.FC<ApprovalModeIndicatorProps> = ({
let textContent = '';
let subText = '';
const cycleHint = formatCommand(Command.CYCLE_APPROVAL_MODE);
const yoloHint = formatCommand(Command.TOGGLE_YOLO);
switch (approvalMode) {
case ApprovalMode.AUTO_EDIT:
textColor = theme.status.warning;
textContent = 'auto-accept edits';
textContent = APPROVAL_MODE_TEXT.AUTO_EDIT;
subText = allowPlanMode
? `${cycleHint} to plan`
: `${cycleHint} to manual`;
? APPROVAL_MODE_TEXT.HINT_SWITCH_TO_PLAN_MODE
: APPROVAL_MODE_TEXT.HINT_SWITCH_TO_MANUAL_MODE;
break;
case ApprovalMode.PLAN:
textColor = theme.status.success;
textContent = 'plan';
subText = `${cycleHint} to manual`;
textContent = APPROVAL_MODE_TEXT.PLAN;
subText = APPROVAL_MODE_TEXT.HINT_SWITCH_TO_MANUAL_MODE;
break;
case ApprovalMode.YOLO:
textColor = theme.status.error;
textContent = 'YOLO';
subText = yoloHint;
textContent = APPROVAL_MODE_TEXT.YOLO;
subText = APPROVAL_MODE_TEXT.HINT_SWITCH_TO_YOLO_MODE;
break;
case ApprovalMode.DEFAULT:
default:
textColor = theme.text.accent;
textContent = '';
subText = `${cycleHint} to accept edits`;
subText = APPROVAL_MODE_TEXT.HINT_SWITCH_TO_AUTO_EDIT_MODE;
break;
}
@@ -1347,47 +1347,4 @@ describe('AskUserDialog', () => {
});
});
});
it('expands paste placeholders in multi-select custom option via Done', async () => {
const questions: Question[] = [
{
question: 'Which features?',
header: 'Features',
type: QuestionType.CHOICE,
options: [{ label: 'TypeScript', description: '' }],
multiSelect: true,
},
];
const onSubmit = vi.fn();
const { stdin } = renderWithProviders(
<AskUserDialog
questions={questions}
onSubmit={onSubmit}
onCancel={vi.fn()}
width={120}
/>,
{ width: 120 },
);
// Select TypeScript
writeKey(stdin, '\r');
// Down to Other
writeKey(stdin, '\x1b[B');
// Simulate bracketed paste of multi-line text into the custom option
const pastedText = 'Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6';
const ESC = '\x1b';
writeKey(stdin, `${ESC}[200~${pastedText}${ESC}[201~`);
// Down to Done and submit
writeKey(stdin, '\x1b[B');
writeKey(stdin, '\r');
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith({
'0': `TypeScript, ${pastedText}`,
});
});
});
});
@@ -23,11 +23,7 @@ import { useKeypress, type Key } from '../hooks/useKeypress.js';
import { keyMatchers, Command } from '../keyMatchers.js';
import { checkExhaustive } from '@google/gemini-cli-core';
import { TextInput } from './shared/TextInput.js';
import { formatCommand } from '../utils/keybindingUtils.js';
import {
useTextBuffer,
expandPastePlaceholders,
} from './shared/text-buffer.js';
import { useTextBuffer } from './shared/text-buffer.js';
import { getCachedStringWidth } from '../utils/textUtils.js';
import { useTabbedNavigation } from '../hooks/useTabbedNavigation.js';
import { DialogFooter } from './shared/DialogFooter.js';
@@ -256,7 +252,7 @@ const ReviewView: React.FC<ReviewViewProps> = ({
</Box>
<DialogFooter
primaryAction="Enter to submit"
navigationActions={`${formatCommand(Command.DIALOG_NEXT)}/${formatCommand(Command.DIALOG_PREV)} to edit answers`}
navigationActions="Tab/Shift+Tab to edit answers"
extraParts={extraParts}
/>
</Box>
@@ -306,12 +302,10 @@ const TextQuestionView: React.FC<TextQuestionViewProps> = ({
const lastTextValueRef = useRef(textValue);
useEffect(() => {
if (textValue !== lastTextValueRef.current) {
onSelectionChange?.(
expandPastePlaceholders(textValue, buffer.pastedContent),
);
onSelectionChange?.(textValue);
lastTextValueRef.current = textValue;
}
}, [textValue, onSelectionChange, buffer.pastedContent]);
}, [textValue, onSelectionChange]);
// Handle Ctrl+C to clear all text
const handleExtraKeys = useCallback(
@@ -594,15 +588,11 @@ const ChoiceQuestionView: React.FC<ChoiceQuestionViewProps> = ({
}
});
if (includeCustomOption && customOption.trim()) {
const expanded = expandPastePlaceholders(
customOption,
customBuffer.pastedContent,
);
answers.push(expanded.trim());
answers.push(customOption.trim());
}
return answers.join(', ');
},
[questionOptions, customBuffer.pastedContent],
[questionOptions],
);
// Synchronize selection changes with parent - only when it actually changes
@@ -767,12 +757,7 @@ const ChoiceQuestionView: React.FC<ChoiceQuestionViewProps> = ({
} else if (itemValue.type === 'other') {
// In single select, selecting other submits it if it has text
if (customOptionText.trim()) {
onAnswer(
expandPastePlaceholders(
customOptionText,
customBuffer.pastedContent,
).trim(),
);
onAnswer(customOptionText.trim());
}
}
}
@@ -782,7 +767,6 @@ const ChoiceQuestionView: React.FC<ChoiceQuestionViewProps> = ({
selectedIndices,
isCustomOptionSelected,
customOptionText,
customBuffer.pastedContent,
onAnswer,
buildAnswerString,
],
@@ -1162,7 +1146,7 @@ export const AskUserDialog: React.FC<AskUserDialogProps> = ({
navigationActions={
questions.length > 1
? currentQuestion.type === 'text' || isEditingCustomOption
? `${formatCommand(Command.DIALOG_NEXT)}/${formatCommand(Command.DIALOG_PREV)} to switch questions`
? 'Tab/Shift+Tab to switch questions'
: '←/→ to switch questions'
: currentQuestion.type === 'text' || isEditingCustomOption
? undefined
@@ -374,7 +374,7 @@ describe('Composer', () => {
const uiState = createMockUIState({
streamingState: StreamingState.Responding,
thought: {
subject: 'Thinking about code',
subject: 'Detailed in-history thought',
description: 'Full text is already in history',
},
});
@@ -385,7 +385,7 @@ describe('Composer', () => {
const { lastFrame } = await renderComposer(uiState, settings);
const output = lastFrame();
expect(output).toContain('LoadingIndicator: Thinking...');
expect(output).toContain('LoadingIndicator: Thinking ...');
});
it('hides shortcuts hint while loading', async () => {
+3 -3
View File
@@ -239,7 +239,7 @@ export const Composer = ({ isFocused = true }: { isFocused?: boolean }) => {
: uiState.currentLoadingPhrase
}
thoughtLabel={
inlineThinkingMode === 'full' ? 'Thinking...' : undefined
inlineThinkingMode === 'full' ? 'Thinking ...' : undefined
}
elapsedTime={uiState.elapsedTime}
/>
@@ -282,7 +282,7 @@ export const Composer = ({ isFocused = true }: { isFocused?: boolean }) => {
: uiState.currentLoadingPhrase
}
thoughtLabel={
inlineThinkingMode === 'full' ? 'Thinking...' : undefined
inlineThinkingMode === 'full' ? 'Thinking ...' : undefined
}
elapsedTime={uiState.elapsedTime}
/>
@@ -390,7 +390,7 @@ export const Composer = ({ isFocused = true }: { isFocused?: boolean }) => {
marginTop={
(showApprovalIndicator ||
uiState.shellModeActive) &&
!isNarrow
isNarrow
? 1
: 0
}
@@ -311,5 +311,9 @@ export const FolderTrustDialog: React.FC<FolderTrustDialogProps> = ({
</Box>
);
return <OverflowProvider>{content}</OverflowProvider>;
return isAlternateBuffer ? (
<OverflowProvider>{content}</OverflowProvider>
) : (
content
);
};
+6 -33
View File
@@ -132,7 +132,9 @@ describe('<Footer />', () => {
const output = lastFrame();
expect(output).toBeDefined();
// Should contain some part of the path, likely shortened
expect(output).toContain(path.join('make', 'it'));
expect(output).toContain(
path.join('directories', 'to', 'make', 'it', 'long'),
);
unmount();
});
@@ -147,38 +149,9 @@ describe('<Footer />', () => {
await waitUntilReady();
const output = lastFrame();
expect(output).toBeDefined();
expect(output).toContain(path.join('make', 'it'));
unmount();
});
it('should not truncate high-priority items on narrow terminals (regression)', async () => {
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
<Footer />,
{
width: 60,
uiState: {
sessionStats: mockSessionStats,
},
settings: createMockSettings({
general: {
vimMode: true,
},
ui: {
footer: {
showLabels: true,
items: ['workspace', 'model-name'],
},
},
}),
},
expect(output).toContain(
path.join('directories', 'to', 'make', 'it', 'long'),
);
await waitUntilReady();
const output = lastFrame();
// [INSERT] is high priority and should be fully visible
// (Note: VimModeProvider defaults to 'INSERT' mode when enabled)
expect(output).toContain('[INSERT]');
// Other items should be present but might be shortened
expect(output).toContain('gemini-pro');
unmount();
});
});
@@ -262,7 +235,7 @@ describe('<Footer />', () => {
},
);
await waitUntilReady();
expect(lastFrame()).toContain('85%');
expect(lastFrame()).toContain('15%');
expect(normalizeFrame(lastFrame())).toMatchSnapshot();
unmount();
});
+19 -44
View File
@@ -103,9 +103,6 @@ export interface FooterRowItem {
key: string;
header: string;
element: React.ReactNode;
flexGrow?: number;
flexShrink?: number;
isFocused?: boolean;
}
const COLUMN_GAP = 3;
@@ -126,20 +123,10 @@ export const FooterRow: React.FC<{
}
elements.push(
<Box
key={item.key}
flexDirection="column"
flexGrow={item.flexGrow ?? 0}
flexShrink={item.flexShrink ?? 1}
backgroundColor={item.isFocused ? theme.background.focus : undefined}
>
<Box key={item.key} flexDirection="column">
{showLabels && (
<Box height={1}>
<Text
color={item.isFocused ? theme.text.primary : theme.ui.comment}
>
{item.header}
</Text>
<Text color={theme.ui.comment}>{item.header}</Text>
</Box>
)}
<Box height={1}>{item.element}</Box>
@@ -151,7 +138,6 @@ export const FooterRow: React.FC<{
<Box
flexDirection="row"
flexWrap="nowrap"
width="100%"
columnGap={showLabels ? COLUMN_GAP : 0}
>
{elements}
@@ -422,50 +408,41 @@ export const Footer: React.FC = () => {
}
// --- Width Fitting Logic ---
let currentWidth = 2; // Initial padding
const columnsToRender: FooterColumn[] = [];
let droppedAny = false;
let currentUsedWidth = 2; // Initial padding
for (const col of potentialColumns) {
const gap = columnsToRender.length > 0 ? (showLabels ? COLUMN_GAP : 3) : 0;
for (let i = 0; i < potentialColumns.length; i++) {
const col = potentialColumns[i];
const gap = columnsToRender.length > 0 ? (showLabels ? COLUMN_GAP : 3) : 0; // Use 3 for dot separator width
const budgetWidth = col.id === 'workspace' ? 20 : col.width;
if (
col.isHighPriority ||
currentUsedWidth + gap + budgetWidth <= terminalWidth - 2
currentWidth + gap + budgetWidth <= terminalWidth - 2
) {
columnsToRender.push(col);
currentUsedWidth += gap + budgetWidth;
currentWidth += gap + budgetWidth;
} else {
droppedAny = true;
}
}
const totalBudgeted = columnsToRender.reduce(
(sum, c, idx) =>
sum +
(c.id === 'workspace' ? 20 : c.width) +
(idx > 0 ? (showLabels ? COLUMN_GAP : 3) : 0),
2,
);
const excessSpace = Math.max(0, terminalWidth - totalBudgeted);
const rowItems: FooterRowItem[] = columnsToRender.map((col) => {
const isWorkspace = col.id === 'workspace';
// Calculate exact space available for growth to prevent over-estimation truncation
const otherItemsWidth = columnsToRender
.filter((c) => c.id !== 'workspace')
.reduce((sum, c) => sum + c.width, 0);
const numItems = columnsToRender.length + (droppedAny ? 1 : 0);
const numGaps = numItems > 1 ? numItems - 1 : 0;
const gapsWidth = numGaps * (showLabels ? COLUMN_GAP : 3);
const ellipsisWidth = droppedAny ? 1 : 0;
const availableForWorkspace = Math.max(
20,
terminalWidth - 2 - gapsWidth - otherItemsWidth - ellipsisWidth,
);
const estimatedWidth = isWorkspace ? availableForWorkspace : col.width;
const maxWidth = col.id === 'workspace' ? 20 + excessSpace : col.width;
return {
key: col.id,
header: col.header,
element: col.element(estimatedWidth),
flexGrow: isWorkspace ? 1 : 0,
flexShrink: isWorkspace ? 1 : 0,
element: col.element(maxWidth),
};
});
@@ -474,8 +451,6 @@ export const Footer: React.FC = () => {
key: 'ellipsis',
header: '',
element: <Text color={theme.ui.comment}></Text>,
flexGrow: 0,
flexShrink: 0,
});
}
@@ -24,14 +24,13 @@ describe('<FooterConfigDialog />', () => {
it('renders correctly with default settings', async () => {
const settings = createMockSettings();
const renderResult = renderWithProviders(
const { lastFrame, waitUntilReady } = renderWithProviders(
<FooterConfigDialog onClose={mockOnClose} />,
{ settings },
);
await renderResult.waitUntilReady();
expect(renderResult.lastFrame()).toMatchSnapshot();
await expect(renderResult).toMatchSvgSnapshot();
await waitUntilReady();
expect(lastFrame()).toMatchSnapshot();
});
it('toggles an item when enter is pressed', async () => {
@@ -67,7 +66,7 @@ describe('<FooterConfigDialog />', () => {
);
await waitUntilReady();
// Initial order: workspace, git-branch, ...
// Initial order: workspace, branch, ...
const output = lastFrame();
const cwdIdx = output.indexOf('] workspace');
const branchIdx = output.indexOf('] git-branch');
@@ -109,40 +108,22 @@ describe('<FooterConfigDialog />', () => {
it('highlights the active item in the preview', async () => {
const settings = createMockSettings();
const renderResult = renderWithProviders(
const { lastFrame, stdin, waitUntilReady } = renderWithProviders(
<FooterConfigDialog onClose={mockOnClose} />,
{ settings },
);
const { lastFrame, stdin, waitUntilReady } = renderResult;
await waitUntilReady();
expect(lastFrame()).toContain('~/project/path');
// Move focus down to 'code-changes' (which has colored elements)
for (let i = 0; i < 8; i++) {
act(() => {
stdin.write('\u001b[B'); // Down arrow
});
}
await waitFor(() => {
// The selected indicator should be next to 'code-changes'
expect(lastFrame()).toMatch(/> \[ \] code-changes/);
});
// Toggle it on
// Move focus down to 'git-branch'
act(() => {
stdin.write('\r');
stdin.write('\u001b[B'); // Down arrow
});
await waitFor(() => {
// It should now be checked and appear in the preview
expect(lastFrame()).toMatch(/> \[✓\] code-changes/);
expect(lastFrame()).toContain('+12 -4');
expect(lastFrame()).toContain('main');
});
await expect(renderResult).toMatchSvgSnapshot();
});
it('shows an empty preview when all items are deselected', async () => {
@@ -153,64 +134,20 @@ describe('<FooterConfigDialog />', () => {
);
await waitUntilReady();
// Default items are the first 5. We toggle them off.
for (let i = 0; i < 5; i++) {
act(() => {
stdin.write('\r'); // Toggle off
});
for (let i = 0; i < 10; i++) {
act(() => {
stdin.write('\r'); // Toggle (deselect)
stdin.write('\u001b[B'); // Down arrow
});
}
await waitFor(
() => {
const output = lastFrame();
expect(output).toContain('Preview:');
expect(output).not.toContain('~/project/path');
expect(output).not.toContain('docker');
},
{ timeout: 2000 },
);
});
it('moves item correctly after trying to move up at the top', async () => {
const settings = createMockSettings();
const { lastFrame, stdin, waitUntilReady } = renderWithProviders(
<FooterConfigDialog onClose={mockOnClose} />,
{ settings },
);
await waitUntilReady();
// Default initial items in mock settings are 'git-branch', 'workspace', ...
await waitFor(() => {
const output = lastFrame();
expect(output).toContain('] git-branch');
expect(output).toContain('] workspace');
});
const output = lastFrame();
const branchIdx = output.indexOf('] git-branch');
const workspaceIdx = output.indexOf('] workspace');
expect(workspaceIdx).toBeLessThan(branchIdx);
// Try to move workspace up (left arrow) while it's at the top
act(() => {
stdin.write('\u001b[D'); // Left arrow
});
// Move workspace down (right arrow)
act(() => {
stdin.write('\u001b[C'); // Right arrow
});
await waitFor(() => {
const outputAfter = lastFrame();
const bIdxAfter = outputAfter.indexOf('] git-branch');
const wIdxAfter = outputAfter.indexOf('] workspace');
// workspace should now be after git-branch
expect(bIdxAfter).toBeLessThan(wIdxAfter);
expect(output).toContain('Preview:');
expect(output).not.toContain('~/project/path');
expect(output).not.toContain('docker');
expect(output).not.toContain('gemini-2.5-pro');
expect(output).not.toContain('1.2k left');
});
});
});
@@ -5,75 +5,119 @@
*/
import type React from 'react';
import { useCallback, useMemo, useReducer, useState } from 'react';
import { useCallback, useMemo, useReducer } from 'react';
import { Box, Text } from 'ink';
import { theme } from '../semantic-colors.js';
import { useSettingsStore } from '../contexts/SettingsContext.js';
import { useUIState } from '../contexts/UIStateContext.js';
import { useKeypress, type Key } from '../hooks/useKeypress.js';
import { keyMatchers, Command } from '../keyMatchers.js';
import { FooterRow, type FooterRowItem } from './Footer.js';
import { ALL_ITEMS, resolveFooterState } from '../../config/footerItems.js';
import { SettingScope } from '../../config/settings.js';
import { BaseSelectionList } from './shared/BaseSelectionList.js';
import type { SelectionListItem } from '../hooks/useSelectionList.js';
import { DialogFooter } from './shared/DialogFooter.js';
interface FooterConfigDialogProps {
onClose?: () => void;
}
interface FooterConfigItem {
key: string;
id: string;
label: string;
description?: string;
type: 'config' | 'labels-toggle' | 'reset';
}
interface FooterConfigState {
orderedIds: string[];
selectedIds: Set<string>;
activeIndex: number;
scrollOffset: number;
}
type FooterConfigAction =
| { type: 'MOVE_ITEM'; id: string; direction: number }
| { type: 'TOGGLE_ITEM'; id: string }
| { type: 'SET_STATE'; payload: Partial<FooterConfigState> };
| { type: 'MOVE_UP'; itemCount: number; maxToShow: number }
| { type: 'MOVE_DOWN'; itemCount: number; maxToShow: number }
| {
type: 'MOVE_LEFT';
items: Array<{ key: string }>;
}
| {
type: 'MOVE_RIGHT';
items: Array<{ key: string }>;
}
| { type: 'TOGGLE_ITEM'; items: Array<{ key: string }> }
| { type: 'SET_STATE'; payload: Partial<FooterConfigState> }
| { type: 'RESET_INDEX' };
function footerConfigReducer(
state: FooterConfigState,
action: FooterConfigAction,
): FooterConfigState {
switch (action.type) {
case 'MOVE_ITEM': {
const currentIndex = state.orderedIds.indexOf(action.id);
const newIndex = currentIndex + action.direction;
if (
currentIndex === -1 ||
newIndex < 0 ||
newIndex >= state.orderedIds.length
) {
return state;
case 'MOVE_UP': {
const { itemCount, maxToShow } = action;
const totalSlots = itemCount + 2; // +1 for showLabels, +1 for reset
const newIndex =
state.activeIndex > 0 ? state.activeIndex - 1 : totalSlots - 1;
let newOffset = state.scrollOffset;
if (newIndex < itemCount) {
if (newIndex === itemCount - 1) {
newOffset = Math.max(0, itemCount - maxToShow);
} else if (newIndex < state.scrollOffset) {
newOffset = newIndex;
}
}
return { ...state, activeIndex: newIndex, scrollOffset: newOffset };
}
case 'MOVE_DOWN': {
const { itemCount, maxToShow } = action;
const totalSlots = itemCount + 2;
const newIndex =
state.activeIndex < totalSlots - 1 ? state.activeIndex + 1 : 0;
let newOffset = state.scrollOffset;
if (newIndex === 0) {
newOffset = 0;
} else if (
newIndex < itemCount &&
newIndex >= state.scrollOffset + maxToShow
) {
newOffset = newIndex - maxToShow + 1;
}
return { ...state, activeIndex: newIndex, scrollOffset: newOffset };
}
case 'MOVE_LEFT':
case 'MOVE_RIGHT': {
const direction = action.type === 'MOVE_LEFT' ? -1 : 1;
const currentItem = action.items[state.activeIndex];
if (!currentItem) return state;
const currentId = currentItem.key;
const currentIndex = state.orderedIds.indexOf(currentId);
const newIndex = currentIndex + direction;
if (newIndex < 0 || newIndex >= state.orderedIds.length) return state;
const newOrderedIds = [...state.orderedIds];
[newOrderedIds[currentIndex], newOrderedIds[newIndex]] = [
newOrderedIds[newIndex],
newOrderedIds[currentIndex],
];
return { ...state, orderedIds: newOrderedIds };
return { ...state, orderedIds: newOrderedIds, activeIndex: newIndex };
}
case 'TOGGLE_ITEM': {
const isSystemFocused = state.activeIndex >= action.items.length;
if (isSystemFocused) return state;
const item = action.items[state.activeIndex];
if (!item) return state;
const nextSelected = new Set(state.selectedIds);
if (nextSelected.has(action.id)) {
nextSelected.delete(action.id);
if (nextSelected.has(item.key)) {
nextSelected.delete(item.key);
} else {
nextSelected.add(action.id);
nextSelected.add(item.key);
}
return { ...state, selectedIds: nextSelected };
}
case 'SET_STATE':
return { ...state, ...action.payload };
case 'RESET_INDEX':
return { ...state, activeIndex: 0, scrollOffset: 0 };
default:
return state;
}
@@ -83,54 +127,40 @@ export const FooterConfigDialog: React.FC<FooterConfigDialogProps> = ({
onClose,
}) => {
const { settings, setSetting } = useSettingsStore();
const { constrainHeight, terminalHeight, staticExtraHeight } = useUIState();
const [state, dispatch] = useReducer(footerConfigReducer, undefined, () =>
resolveFooterState(settings.merged),
);
const maxItemsToShow = 10;
const { orderedIds, selectedIds } = state;
const [focusKey, setFocusKey] = useState<string | undefined>(orderedIds[0]);
const [state, dispatch] = useReducer(footerConfigReducer, undefined, () => ({
...resolveFooterState(settings.merged),
activeIndex: 0,
scrollOffset: 0,
}));
const listItems = useMemo((): Array<SelectionListItem<FooterConfigItem>> => {
const items: Array<SelectionListItem<FooterConfigItem>> = orderedIds
.map((id: string) => {
const item = ALL_ITEMS.find((i) => i.id === id);
if (!item) return null;
return {
key: id,
value: {
const { orderedIds, selectedIds, activeIndex, scrollOffset } = state;
// Prepare items
const listItems = useMemo(
() =>
orderedIds
.map((id: string) => {
const item = ALL_ITEMS.find((i) => i.id === id);
if (!item) return null;
return {
key: id,
id,
label: item.id,
description: item.description as string,
type: 'config' as const,
},
};
})
.filter((i): i is NonNullable<typeof i> => i !== null);
};
})
.filter((i): i is NonNullable<typeof i> => i !== null),
[orderedIds],
);
items.push({
key: 'show-labels',
value: {
key: 'show-labels',
id: 'show-labels',
label: 'Show footer labels',
type: 'labels-toggle',
},
});
const maxLabelWidth = useMemo(
() => listItems.reduce((max, item) => Math.max(max, item.label.length), 0),
[listItems],
);
items.push({
key: 'reset',
value: {
key: 'reset',
id: 'reset',
label: 'Reset to default footer',
type: 'reset',
},
});
return items;
}, [orderedIds]);
const isResetFocused = activeIndex === listItems.length + 1;
const isShowLabelsFocused = activeIndex === listItems.length;
const handleSaveAndClose = useCallback(() => {
const finalItems = orderedIds.filter((id: string) => selectedIds.has(id));
@@ -149,9 +179,14 @@ export const FooterConfigDialog: React.FC<FooterConfigDialogProps> = ({
const handleResetToDefaults = useCallback(() => {
setSetting(SettingScope.User, 'ui.footer.items', undefined);
const newState = resolveFooterState(settings.merged);
dispatch({ type: 'SET_STATE', payload: newState });
setFocusKey(newState.orderedIds[0]);
dispatch({
type: 'SET_STATE',
payload: {
...resolveFooterState(settings.merged),
activeIndex: 0,
scrollOffset: 0,
},
});
}, [setSetting, settings.merged]);
const handleToggleLabels = useCallback(() => {
@@ -159,23 +194,6 @@ export const FooterConfigDialog: React.FC<FooterConfigDialogProps> = ({
setSetting(SettingScope.User, 'ui.footer.showLabels', !current);
}, [setSetting, settings.merged.ui.footer.showLabels]);
const handleSelect = useCallback(
(item: FooterConfigItem) => {
if (item.type === 'config') {
dispatch({ type: 'TOGGLE_ITEM', id: item.id });
} else if (item.type === 'labels-toggle') {
handleToggleLabels();
} else if (item.type === 'reset') {
handleResetToDefaults();
}
},
[handleResetToDefaults, handleToggleLabels],
);
const handleHighlight = useCallback((item: FooterConfigItem) => {
setFocusKey(item.key);
}, []);
useKeypress(
(key: Key) => {
if (keyMatchers[Command.ESCAPE](key)) {
@@ -183,18 +201,43 @@ export const FooterConfigDialog: React.FC<FooterConfigDialogProps> = ({
return true;
}
if (keyMatchers[Command.DIALOG_NAVIGATION_UP](key)) {
dispatch({
type: 'MOVE_UP',
itemCount: listItems.length,
maxToShow: maxItemsToShow,
});
return true;
}
if (keyMatchers[Command.DIALOG_NAVIGATION_DOWN](key)) {
dispatch({
type: 'MOVE_DOWN',
itemCount: listItems.length,
maxToShow: maxItemsToShow,
});
return true;
}
if (keyMatchers[Command.MOVE_LEFT](key)) {
if (focusKey && orderedIds.includes(focusKey)) {
dispatch({ type: 'MOVE_ITEM', id: focusKey, direction: -1 });
return true;
}
dispatch({ type: 'MOVE_LEFT', items: listItems });
return true;
}
if (keyMatchers[Command.MOVE_RIGHT](key)) {
if (focusKey && orderedIds.includes(focusKey)) {
dispatch({ type: 'MOVE_ITEM', id: focusKey, direction: 1 });
return true;
dispatch({ type: 'MOVE_RIGHT', items: listItems });
return true;
}
if (keyMatchers[Command.RETURN](key) || key.name === 'space') {
if (isResetFocused) {
handleResetToDefaults();
} else if (isShowLabelsFocused) {
handleToggleLabels();
} else {
dispatch({ type: 'TOGGLE_ITEM', items: listItems });
}
return true;
}
return false;
@@ -202,11 +245,17 @@ export const FooterConfigDialog: React.FC<FooterConfigDialogProps> = ({
{ isActive: true, priority: true },
);
const visibleItems = listItems.slice(
scrollOffset,
scrollOffset + maxItemsToShow,
);
const activeId = listItems[activeIndex]?.key;
const showLabels = settings.merged.ui.footer.showLabels !== false;
// Preview logic
const previewContent = useMemo(() => {
if (focusKey === 'reset') {
if (isResetFocused) {
return (
<Text color={theme.ui.comment} italic>
Default footer (uses legacy settings)
@@ -220,9 +269,8 @@ export const FooterConfigDialog: React.FC<FooterConfigDialogProps> = ({
if (itemsToPreview.length === 0) return null;
const itemColor = showLabels ? theme.text.primary : theme.ui.comment;
const getColor = (id: string, defaultColor?: string) =>
defaultColor || itemColor;
id === activeId ? 'white' : defaultColor || itemColor;
// Mock data for preview (headers come from ALL_ITEMS)
const mockData: Record<string, React.ReactNode> = {
@@ -264,43 +312,16 @@ export const FooterConfigDialog: React.FC<FooterConfigDialogProps> = ({
key: id,
header: ALL_ITEMS.find((i) => i.id === id)?.header ?? id,
element: mockData[id],
flexGrow: 1,
isFocused: id === focusKey,
}));
return (
<Box overflow="hidden" flexWrap="nowrap" width="100%">
<FooterRow items={rowItems} showLabels={showLabels} />
<Box overflow="hidden" flexWrap="nowrap">
<Box flexShrink={0}>
<FooterRow items={rowItems} showLabels={showLabels} />
</Box>
</Box>
);
}, [orderedIds, selectedIds, focusKey, showLabels]);
const availableTerminalHeight = constrainHeight
? terminalHeight - staticExtraHeight
: Number.MAX_SAFE_INTEGER;
const BORDER_HEIGHT = 2; // Outer round border
const STATIC_ELEMENTS = 13; // Text, margins, preview box, dialog footer
// Default padding adds 2 lines (top and bottom)
let includePadding = true;
if (availableTerminalHeight < BORDER_HEIGHT + 2 + STATIC_ELEMENTS + 6) {
includePadding = false;
}
const effectivePaddingY = includePadding ? 2 : 0;
const availableListSpace = Math.max(
0,
availableTerminalHeight -
BORDER_HEIGHT -
effectivePaddingY -
STATIC_ELEMENTS,
);
const maxItemsToShow = Math.max(
1,
Math.min(listItems.length, Math.floor(availableListSpace / 2)),
);
}, [orderedIds, selectedIds, activeId, isResetFocused, showLabels]);
return (
<Box
@@ -308,7 +329,7 @@ export const FooterConfigDialog: React.FC<FooterConfigDialogProps> = ({
borderStyle="round"
borderColor={theme.border.default}
paddingX={2}
paddingY={includePadding ? 1 : 0}
paddingY={1}
width="100%"
>
<Text bold>Configure Footer{'\n'}</Text>
@@ -316,65 +337,59 @@ export const FooterConfigDialog: React.FC<FooterConfigDialogProps> = ({
Select which items to display in the footer.
</Text>
<Box flexDirection="column" marginTop={1} flexGrow={1}>
<BaseSelectionList<FooterConfigItem>
items={listItems}
onSelect={handleSelect}
onHighlight={handleHighlight}
focusKey={focusKey}
showNumbers={false}
maxItemsToShow={maxItemsToShow}
showScrollArrows={true}
selectedIndicator=">"
renderItem={(item, { isSelected, titleColor }) => {
const configItem = item.value;
const isChecked =
configItem.type === 'config'
? selectedIds.has(configItem.id)
: configItem.type === 'labels-toggle'
? showLabels
: false;
<Box flexDirection="column" marginTop={1} minHeight={maxItemsToShow}>
{visibleItems.length === 0 ? (
<Text color={theme.text.secondary}>No items found.</Text>
) : (
visibleItems.map((item, idx) => {
const index = scrollOffset + idx;
const isFocused = index === activeIndex;
const isChecked = selectedIds.has(item.key);
return (
<Box flexDirection="column" minHeight={2}>
<Box flexDirection="row">
{configItem.type !== 'reset' && (
<Text
color={
isChecked ? theme.status.success : theme.text.secondary
}
>
[{isChecked ? '✓' : ' '}]
</Text>
)}
<Text
color={
configItem.type === 'reset' && isSelected
? theme.status.warning
: titleColor
}
>
{configItem.type !== 'reset' ? ' ' : ''}
{configItem.label}
</Text>
</Box>
{configItem.description && (
<Text color={theme.text.secondary} wrap="wrap">
{' '}
{configItem.description}
</Text>
)}
<Box key={item.key} flexDirection="row">
<Text color={isFocused ? theme.status.success : undefined}>
{isFocused ? '> ' : ' '}
</Text>
<Text
color={isFocused ? theme.status.success : theme.text.primary}
>
[{isChecked ? '✓' : ' '}]{' '}
{item.label.padEnd(maxLabelWidth + 1)}
</Text>
<Text color={theme.text.secondary}> {item.description}</Text>
</Box>
);
}}
/>
})
)}
</Box>
<DialogFooter
primaryAction="Enter to select"
navigationActions="↑/↓ to navigate · ←/→ to reorder"
cancelAction="Esc to close"
/>
<Box marginTop={1} flexDirection="column">
<Box flexDirection="row">
<Text color={isShowLabelsFocused ? theme.status.success : undefined}>
{isShowLabelsFocused ? '> ' : ' '}
</Text>
<Text color={isShowLabelsFocused ? theme.status.success : undefined}>
[{showLabels ? '✓' : ' '}] Show footer labels
</Text>
</Box>
<Box flexDirection="row">
<Text color={isResetFocused ? theme.status.warning : undefined}>
{isResetFocused ? '> ' : ' '}
</Text>
<Text
color={isResetFocused ? theme.status.warning : theme.text.secondary}
>
Reset to default footer
</Text>
</Box>
</Box>
<Box marginTop={1} flexDirection="column">
<Text color={theme.text.secondary}>
/ navigate · / reorder · enter/space select · esc close
</Text>
</Box>
<Box
marginTop={1}
@@ -384,9 +399,7 @@ export const FooterConfigDialog: React.FC<FooterConfigDialogProps> = ({
flexDirection="column"
>
<Text bold>Preview:</Text>
<Box flexDirection="row" width="100%">
{previewContent}
</Box>
<Box flexDirection="row">{previewContent}</Box>
</Box>
</Box>
);
+1 -1
View File
@@ -77,7 +77,7 @@ describe('Help Component', () => {
expect(output).toContain('Keyboard Shortcuts:');
expect(output).toContain('Ctrl+C');
expect(output).toContain('Ctrl+S');
expect(output).toContain('Page Up/Page Down');
expect(output).toContain('Page Up/Down');
unmount();
});
});
+15 -17
View File
@@ -10,8 +10,6 @@ import { theme } from '../semantic-colors.js';
import { type SlashCommand, CommandKind } from '../commands/types.js';
import { KEYBOARD_SHORTCUTS_URL } from '../constants.js';
import { sanitizeForDisplay } from '../utils/textUtils.js';
import { formatCommand } from '../utils/keybindingUtils.js';
import { Command } from '../../config/keyBindings.js';
interface Help {
commands: readonly SlashCommand[];
@@ -118,75 +116,75 @@ export const Help: React.FC<Help> = ({ commands }) => (
</Text>
<Text color={theme.text.primary}>
<Text bold color={theme.text.accent}>
{formatCommand(Command.MOVE_WORD_LEFT)}/
{formatCommand(Command.MOVE_WORD_RIGHT)}
Alt+Left/Right
</Text>{' '}
- Jump through words in the input
</Text>
<Text color={theme.text.primary}>
<Text bold color={theme.text.accent}>
{formatCommand(Command.QUIT)}
Ctrl+C
</Text>{' '}
- Quit application
</Text>
<Text color={theme.text.primary}>
<Text bold color={theme.text.accent}>
{formatCommand(Command.NEWLINE)}
{process.platform === 'win32' ? 'Ctrl+Enter' : 'Ctrl+J'}
</Text>{' '}
- New line
{process.platform === 'linux'
? '- New line (Alt+Enter works for certain linux distros)'
: '- New line'}
</Text>
<Text color={theme.text.primary}>
<Text bold color={theme.text.accent}>
{formatCommand(Command.CLEAR_SCREEN)}
Ctrl+L
</Text>{' '}
- Clear the screen
</Text>
<Text color={theme.text.primary}>
<Text bold color={theme.text.accent}>
{formatCommand(Command.TOGGLE_COPY_MODE)}
Ctrl+S
</Text>{' '}
- Enter selection mode to copy text
</Text>
<Text color={theme.text.primary}>
<Text bold color={theme.text.accent}>
{formatCommand(Command.OPEN_EXTERNAL_EDITOR)}
Ctrl+X
</Text>{' '}
- Open input in external editor
</Text>
<Text color={theme.text.primary}>
<Text bold color={theme.text.accent}>
{formatCommand(Command.TOGGLE_YOLO)}
Ctrl+Y
</Text>{' '}
- Toggle YOLO mode
</Text>
<Text color={theme.text.primary}>
<Text bold color={theme.text.accent}>
{formatCommand(Command.SUBMIT)}
Enter
</Text>{' '}
- Send message
</Text>
<Text color={theme.text.primary}>
<Text bold color={theme.text.accent}>
{formatCommand(Command.ESCAPE)}
Esc
</Text>{' '}
- Cancel operation / Clear input (double press)
</Text>
<Text color={theme.text.primary}>
<Text bold color={theme.text.accent}>
{formatCommand(Command.PAGE_UP)}/{formatCommand(Command.PAGE_DOWN)}
Page Up/Down
</Text>{' '}
- Scroll page up/down
</Text>
<Text color={theme.text.primary}>
<Text bold color={theme.text.accent}>
{formatCommand(Command.CYCLE_APPROVAL_MODE)}
Shift+Tab
</Text>{' '}
- Toggle auto-accepting edits
</Text>
<Text color={theme.text.primary}>
<Text bold color={theme.text.accent}>
{formatCommand(Command.HISTORY_UP)}/
{formatCommand(Command.HISTORY_DOWN)}
Up/Down
</Text>{' '}
- Cycle through your prompt history
</Text>
@@ -290,26 +290,6 @@ describe('<HistoryItemDisplay />', () => {
unmount();
});
it('renders "Thinking..." header when isFirstThinking is true', async () => {
const item: HistoryItem = {
...baseItem,
type: 'thinking',
thought: { subject: 'Thinking', description: 'test' },
};
const { lastFrame, waitUntilReady, unmount } = renderWithProviders(
<HistoryItemDisplay {...baseItem} item={item} isFirstThinking={true} />,
{
settings: createMockSettings({
merged: { ui: { inlineThinkingMode: 'full' } },
}),
},
);
await waitUntilReady();
expect(lastFrame()).toContain(' Thinking...');
expect(lastFrame()).toMatchSnapshot();
unmount();
});
it('does not render thinking item when disabled', async () => {
const item: HistoryItem = {
...baseItem,
@@ -46,8 +46,6 @@ interface HistoryItemDisplayProps {
commands?: readonly SlashCommand[];
availableTerminalHeightGemini?: number;
isExpandable?: boolean;
isFirstThinking?: boolean;
isFirstAfterThinking?: boolean;
}
export const HistoryItemDisplay: React.FC<HistoryItemDisplayProps> = ({
@@ -58,30 +56,16 @@ export const HistoryItemDisplay: React.FC<HistoryItemDisplayProps> = ({
commands,
availableTerminalHeightGemini,
isExpandable,
isFirstThinking = false,
isFirstAfterThinking = false,
}) => {
const settings = useSettings();
const inlineThinkingMode = getInlineThinkingMode(settings);
const itemForDisplay = useMemo(() => escapeAnsiCtrlCodes(item), [item]);
const needsTopMarginAfterThinking =
isFirstAfterThinking && inlineThinkingMode !== 'off';
return (
<Box
flexDirection="column"
key={itemForDisplay.id}
width={terminalWidth}
marginTop={needsTopMarginAfterThinking ? 1 : 0}
>
<Box flexDirection="column" key={itemForDisplay.id} width={terminalWidth}>
{/* Render standard message types */}
{itemForDisplay.type === 'thinking' && inlineThinkingMode !== 'off' && (
<ThinkingMessage
thought={itemForDisplay.thought}
terminalWidth={terminalWidth}
isFirstThinking={isFirstThinking}
/>
<ThinkingMessage thought={itemForDisplay.thought} />
)}
{itemForDisplay.type === 'hint' && (
<HintMessage text={itemForDisplay.text} />
@@ -1349,7 +1349,7 @@ describe('InputPrompt', () => {
it('should autocomplete custom commands from .toml files on Enter', async () => {
const customCommand: SlashCommand = {
name: 'find-capital',
kind: CommandKind.USER_FILE,
kind: CommandKind.FILE,
description: 'Find capital of a country',
action: vi.fn(),
// No autoExecute flag - custom commands default to undefined
@@ -2206,8 +2206,7 @@ describe('InputPrompt', () => {
// Check that all lines, including the empty one, are rendered.
// This implicitly tests that the Box wrapper provides height for the empty line.
expect(frame).toContain('hello');
expect(frame).toContain('world');
expect(frame).toContain(chalk.inverse(' '));
expect(frame).toContain(`world${chalk.inverse(' ')}`);
const outputLines = frame.trim().split('\n');
// The number of lines should be 2 for the border plus 3 for the content.
@@ -15,7 +15,7 @@ import { HalfLinePaddedBox } from './shared/HalfLinePaddedBox.js';
import {
type TextBuffer,
logicalPosToOffset,
expandPastePlaceholders,
PASTED_TEXT_PLACEHOLDER_REGEX,
getTransformUnderCursor,
LARGE_PASTE_LINE_THRESHOLD,
LARGE_PASTE_CHAR_THRESHOLD,
@@ -346,9 +346,10 @@ export const InputPrompt: React.FC<InputPromptProps> = ({
(submittedValue: string) => {
let processedValue = submittedValue;
if (buffer.pastedContent) {
processedValue = expandPastePlaceholders(
processedValue,
buffer.pastedContent,
// Replace placeholders like [Pasted Text: 6 lines] with actual content
processedValue = processedValue.replace(
PASTED_TEXT_PLACEHOLDER_REGEX,
(match) => buffer.pastedContent[match] || match,
);
}
@@ -258,32 +258,13 @@ describe('<LoadingIndicator />', () => {
const output = lastFrame();
expect(output).toBeDefined();
if (output) {
// Should NOT contain "Thinking... " prefix because the subject already starts with "Thinking"
expect(output).not.toContain('Thinking... Thinking');
expect(output).toContain('💬');
expect(output).toContain('Thinking about something...');
expect(output).not.toContain('and other stuff.');
}
unmount();
});
it('should prepend "Thinking... " if the subject does not start with "Thinking"', async () => {
const props = {
thought: {
subject: 'Planning the response...',
description: 'details',
},
elapsedTime: 5,
};
const { lastFrame, unmount, waitUntilReady } = renderWithContext(
<LoadingIndicator {...props} />,
StreamingState.Responding,
);
await waitUntilReady();
const output = lastFrame();
expect(output).toContain('Thinking... Planning the response...');
unmount();
});
it('should prioritize thought.subject over currentLoadingPhrase', async () => {
const props = {
thought: {
@@ -299,13 +280,13 @@ describe('<LoadingIndicator />', () => {
);
await waitUntilReady();
const output = lastFrame();
expect(output).toContain('Thinking... ');
expect(output).toContain('💬');
expect(output).toContain('This should be displayed');
expect(output).not.toContain('This should not be displayed');
unmount();
});
it('should not display thought indicator for non-thought loading phrases', async () => {
it('should not display thought icon for non-thought loading phrases', async () => {
const { lastFrame, unmount, waitUntilReady } = renderWithContext(
<LoadingIndicator
currentLoadingPhrase="some random tip..."
@@ -314,7 +295,7 @@ describe('<LoadingIndicator />', () => {
StreamingState.Responding,
);
await waitUntilReady();
expect(lastFrame()).not.toContain('Thinking... ');
expect(lastFrame()).not.toContain('💬');
unmount();
});
@@ -58,11 +58,7 @@ export const LoadingIndicator: React.FC<LoadingIndicatorProps> = ({
const hasThoughtIndicator =
currentLoadingPhrase !== INTERACTIVE_SHELL_WAITING_PHRASE &&
Boolean(thought?.subject?.trim());
// Avoid "Thinking... Thinking..." duplication if primaryText already starts with "Thinking"
const thinkingIndicator =
hasThoughtIndicator && !primaryText?.startsWith('Thinking')
? 'Thinking... '
: '';
const thinkingIndicator = hasThoughtIndicator ? '💬 ' : '';
const cancelAndTimerContent =
showCancelAndTimer &&
@@ -22,19 +22,17 @@ import { CoreToolCallStatus } from '@google/gemini-cli-core';
import { type IndividualToolCallDisplay } from '../types.js';
// Mock dependencies
const mockUseSettings = vi.fn().mockReturnValue({
merged: {
ui: {
inlineThinkingMode: 'off',
},
},
});
vi.mock('../contexts/SettingsContext.js', async () => {
const actual = await vi.importActual('../contexts/SettingsContext.js');
return {
...actual,
useSettings: () => mockUseSettings(),
useSettings: () => ({
merged: {
ui: {
inlineThinkingMode: 'off',
},
},
}),
};
});
@@ -335,13 +333,6 @@ describe('MainContent', () => {
beforeEach(() => {
vi.mocked(useAlternateBuffer).mockReturnValue(false);
mockUseSettings.mockReturnValue({
merged: {
ui: {
inlineThinkingMode: 'off',
},
},
});
});
afterEach(() => {
@@ -579,64 +570,6 @@ describe('MainContent', () => {
unmount();
});
it('renders multiple thinking messages sequentially correctly', async () => {
mockUseSettings.mockReturnValue({
merged: {
ui: {
inlineThinkingMode: 'expanded',
},
},
});
vi.mocked(useAlternateBuffer).mockReturnValue(true);
const uiState = {
...defaultMockUiState,
history: [
{ id: 0, type: 'user' as const, text: 'Plan a solution' },
{
id: 1,
type: 'thinking' as const,
thought: {
subject: 'Initial analysis',
description:
'This is a multiple line paragraph for the first thinking message of how the model analyzes the problem.',
},
},
{
id: 2,
type: 'thinking' as const,
thought: {
subject: 'Planning execution',
description:
'This a second multiple line paragraph for the second thinking message explaining the plan in detail so that it wraps around the terminal display.',
},
},
{
id: 3,
type: 'thinking' as const,
thought: {
subject: 'Refining approach',
description:
'And finally a third multiple line paragraph for the third thinking message to refine the solution.',
},
},
],
};
const renderResult = renderWithProviders(<MainContent />, {
uiState: uiState as Partial<UIState>,
});
await renderResult.waitUntilReady();
const output = renderResult.lastFrame();
expect(output).toContain('Initial analysis');
expect(output).toContain('Planning execution');
expect(output).toContain('Refining approach');
expect(output).toMatchSnapshot();
await expect(renderResult).toMatchSvgSnapshot();
renderResult.unmount();
});
describe('MainContent Tool Output Height Logic', () => {
const testCases = [
{
+27 -68
View File
@@ -62,31 +62,11 @@ export const MainContent = () => {
return -1;
}, [uiState.history]);
const augmentedHistory = useMemo(
() =>
uiState.history.map((item, index) => {
const isExpandable = index > lastUserPromptIndex;
const prevType =
index > 0 ? uiState.history[index - 1]?.type : undefined;
const isFirstThinking =
item.type === 'thinking' && prevType !== 'thinking';
const isFirstAfterThinking =
item.type !== 'thinking' && prevType === 'thinking';
return {
item,
isExpandable,
isFirstThinking,
isFirstAfterThinking,
};
}),
[uiState.history, lastUserPromptIndex],
);
const historyItems = useMemo(
() =>
augmentedHistory.map(
({ item, isExpandable, isFirstThinking, isFirstAfterThinking }) => (
uiState.history.map((h, index) => {
const isExpandable = index > lastUserPromptIndex;
return (
<MemoizedHistoryItemDisplay
terminalWidth={mainAreaWidth}
availableTerminalHeight={
@@ -95,22 +75,21 @@ export const MainContent = () => {
: undefined
}
availableTerminalHeightGemini={MAX_GEMINI_MESSAGE_LINES}
key={item.id}
item={item}
key={h.id}
item={h}
isPending={false}
commands={uiState.slashCommands}
isExpandable={isExpandable}
isFirstThinking={isFirstThinking}
isFirstAfterThinking={isFirstAfterThinking}
/>
),
),
);
}),
[
augmentedHistory,
uiState.history,
mainAreaWidth,
staticAreaMaxItemHeight,
uiState.slashCommands,
uiState.constrainHeight,
lastUserPromptIndex,
],
);
@@ -127,31 +106,18 @@ export const MainContent = () => {
const pendingItems = useMemo(
() => (
<Box flexDirection="column">
{pendingHistoryItems.map((item, i) => {
const prevType =
i === 0
? uiState.history.at(-1)?.type
: pendingHistoryItems[i - 1]?.type;
const isFirstThinking =
item.type === 'thinking' && prevType !== 'thinking';
const isFirstAfterThinking =
item.type !== 'thinking' && prevType === 'thinking';
return (
<HistoryItemDisplay
key={i}
availableTerminalHeight={
uiState.constrainHeight ? staticAreaMaxItemHeight : undefined
}
terminalWidth={mainAreaWidth}
item={{ ...item, id: 0 }}
isPending={true}
isExpandable={true}
isFirstThinking={isFirstThinking}
isFirstAfterThinking={isFirstAfterThinking}
/>
);
})}
{pendingHistoryItems.map((item, i) => (
<HistoryItemDisplay
key={i}
availableTerminalHeight={
uiState.constrainHeight ? staticAreaMaxItemHeight : undefined
}
terminalWidth={mainAreaWidth}
item={{ ...item, id: 0 }}
isPending={true}
isExpandable={true}
/>
))}
{showConfirmationQueue && confirmingTool && (
<ToolConfirmationQueue confirmingTool={confirmingTool} />
)}
@@ -164,25 +130,20 @@ export const MainContent = () => {
mainAreaWidth,
showConfirmationQueue,
confirmingTool,
uiState.history,
],
);
const virtualizedData = useMemo(
() => [
{ type: 'header' as const },
...augmentedHistory.map(
({ item, isExpandable, isFirstThinking, isFirstAfterThinking }) => ({
type: 'history' as const,
item,
isExpandable,
isFirstThinking,
isFirstAfterThinking,
}),
),
...uiState.history.map((item, index) => ({
type: 'history' as const,
item,
isExpandable: index > lastUserPromptIndex,
})),
{ type: 'pending' as const },
],
[augmentedHistory],
[uiState.history, lastUserPromptIndex],
);
const renderItem = useCallback(
@@ -210,8 +171,6 @@ export const MainContent = () => {
isPending={false}
commands={uiState.slashCommands}
isExpandable={item.isExpandable}
isFirstThinking={item.isFirstThinking}
isFirstAfterThinking={item.isFirstAfterThinking}
/>
);
} else {
@@ -5,20 +5,10 @@
*/
import { render } from '../../test-utils/render.js';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { describe, it, expect } from 'vitest';
import { QuotaDisplay } from './QuotaDisplay.js';
describe('QuotaDisplay', () => {
beforeEach(() => {
vi.stubEnv('TZ', 'America/Los_Angeles');
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-03-02T20:29:00.000Z'));
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllEnvs();
});
it('should not render when remaining is undefined', async () => {
const { lastFrame, waitUntilReady, unmount } = render(
<QuotaDisplay remaining={undefined} limit={100} />,
@@ -46,7 +36,7 @@ describe('QuotaDisplay', () => {
unmount();
});
it('should not render when usage < 80%', async () => {
it('should not render when usage > 20%', async () => {
const { lastFrame, waitUntilReady, unmount } = render(
<QuotaDisplay remaining={85} limit={100} />,
);
@@ -55,7 +45,7 @@ describe('QuotaDisplay', () => {
unmount();
});
it('should render warning when used >= 80%', async () => {
it('should render yellow when usage < 20%', async () => {
const { lastFrame, waitUntilReady, unmount } = render(
<QuotaDisplay remaining={15} limit={100} />,
);
@@ -64,7 +54,7 @@ describe('QuotaDisplay', () => {
unmount();
});
it('should render critical when used >= 95%', async () => {
it('should render red when usage < 5%', async () => {
const { lastFrame, waitUntilReady, unmount } = render(
<QuotaDisplay remaining={4} limit={100} />,
);
+20 -24
View File
@@ -7,9 +7,9 @@
import type React from 'react';
import { Text } from 'ink';
import {
getUsedStatusColor,
QUOTA_USED_WARNING_THRESHOLD,
QUOTA_USED_CRITICAL_THRESHOLD,
getStatusColor,
QUOTA_THRESHOLD_HIGH,
QUOTA_THRESHOLD_MEDIUM,
} from '../utils/displayUtils.js';
import { formatResetTime } from '../utils/formatters.js';
@@ -34,36 +34,32 @@ export const QuotaDisplay: React.FC<QuotaDisplayProps> = ({
return null;
}
const usedPercentage = 100 - (remaining / limit) * 100;
const percentage = (remaining / limit) * 100;
if (!forceShow && usedPercentage < QUOTA_USED_WARNING_THRESHOLD) {
if (!forceShow && percentage > QUOTA_THRESHOLD_HIGH) {
return null;
}
const color = getUsedStatusColor(usedPercentage, {
warning: QUOTA_USED_WARNING_THRESHOLD,
critical: QUOTA_USED_CRITICAL_THRESHOLD,
const color = getStatusColor(percentage, {
green: QUOTA_THRESHOLD_HIGH,
yellow: QUOTA_THRESHOLD_MEDIUM,
});
let text: string;
const resetInfo =
!terse && resetTime ? `, ${formatResetTime(resetTime)}` : '';
if (remaining === 0) {
const resetMsg = resetTime
? `, resets in ${formatResetTime(resetTime, 'terse')}`
: '';
text = terse ? 'Limit reached' : `Limit reached${resetMsg}`;
} else {
text = terse
? `${usedPercentage.toFixed(0)}%`
: `${usedPercentage.toFixed(0)}% used${
resetTime
? ` (Limit resets in ${formatResetTime(resetTime, 'terse')})`
: ''
}`;
let text = terse
? 'Limit reached'
: `/stats Limit reached${resetInfo}${!terse && '. /auth to continue.'}`;
if (lowercase) text = text.toLowerCase();
return <Text color={color}>{text}</Text>;
}
if (lowercase) {
text = text.toLowerCase();
}
let text = terse
? `${percentage.toFixed(0)}%`
: `/stats ${percentage.toFixed(0)}% usage remaining${resetInfo}`;
if (lowercase) text = text.toLowerCase();
return <Text color={color}>{text}</Text>;
};
@@ -9,9 +9,9 @@ import { Box, Text } from 'ink';
import { theme } from '../semantic-colors.js';
import { formatResetTime } from '../utils/formatters.js';
import {
getUsedStatusColor,
QUOTA_USED_WARNING_THRESHOLD,
QUOTA_USED_CRITICAL_THRESHOLD,
getStatusColor,
QUOTA_THRESHOLD_HIGH,
QUOTA_THRESHOLD_MEDIUM,
} from '../utils/displayUtils.js';
interface QuotaStatsInfoProps {
@@ -31,26 +31,19 @@ export const QuotaStatsInfo: React.FC<QuotaStatsInfoProps> = ({
return null;
}
const usedPercentage = 100 - (remaining / limit) * 100;
const color = getUsedStatusColor(usedPercentage, {
warning: QUOTA_USED_WARNING_THRESHOLD,
critical: QUOTA_USED_CRITICAL_THRESHOLD,
const percentage = (remaining / limit) * 100;
const color = getStatusColor(percentage, {
green: QUOTA_THRESHOLD_HIGH,
yellow: QUOTA_THRESHOLD_MEDIUM,
});
return (
<Box flexDirection="column" marginTop={0} marginBottom={0}>
<Text color={color}>
{remaining === 0
? `Limit reached${
resetTime
? `, resets in ${formatResetTime(resetTime, 'terse')}`
: ''
}`
: `${usedPercentage.toFixed(0)}% used${
resetTime
? ` (Limit resets in ${formatResetTime(resetTime, 'terse')})`
: ''
}`}
? `Limit reached`
: `${percentage.toFixed(0)}% usage remaining`}
{resetTime && `, ${formatResetTime(resetTime)}`}
</Text>
{showDetails && (
<>
@@ -6,18 +6,15 @@
import { render } from '../../test-utils/render.js';
import { RawMarkdownIndicator } from './RawMarkdownIndicator.js';
import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest';
import { describe, it, expect, afterEach } from 'vitest';
describe('RawMarkdownIndicator', () => {
const originalPlatform = process.platform;
beforeEach(() => vi.stubEnv('FORCE_GENERIC_KEYBINDING_HINTS', ''));
afterEach(() => {
Object.defineProperty(process, 'platform', {
value: originalPlatform,
});
vi.unstubAllEnvs();
});
it('renders correct key binding for darwin', async () => {
@@ -29,7 +26,7 @@ describe('RawMarkdownIndicator', () => {
);
await waitUntilReady();
expect(lastFrame()).toContain('raw markdown mode');
expect(lastFrame()).toContain('Option+M to toggle');
expect(lastFrame()).toContain('option+m to toggle');
unmount();
});
@@ -42,7 +39,7 @@ describe('RawMarkdownIndicator', () => {
);
await waitUntilReady();
expect(lastFrame()).toContain('raw markdown mode');
expect(lastFrame()).toContain('Alt+M to toggle');
expect(lastFrame()).toContain('alt+m to toggle');
unmount();
});
});
@@ -7,11 +7,9 @@
import type React from 'react';
import { Box, Text } from 'ink';
import { theme } from '../semantic-colors.js';
import { formatCommand } from '../utils/keybindingUtils.js';
import { Command } from '../../config/keyBindings.js';
export const RawMarkdownIndicator: React.FC = () => {
const modKey = formatCommand(Command.TOGGLE_MARKDOWN);
const modKey = process.platform === 'darwin' ? 'option+m' : 'alt+m';
return (
<Box>
<Text>
@@ -4,7 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { Box, Text, useIsScreenReaderEnabled } from 'ink';
import { Box, Text } from 'ink';
import type React from 'react';
import { useMemo } from 'react';
import { theme } from '../semantic-colors.js';
@@ -58,7 +58,6 @@ export const RewindConfirmation: React.FC<RewindConfirmationProps> = ({
terminalWidth,
timestamp,
}) => {
const isScreenReaderEnabled = useIsScreenReaderEnabled();
useKeypress(
(key) => {
if (keyMatchers[Command.ESCAPE](key)) {
@@ -84,53 +83,6 @@ export const RewindConfirmation: React.FC<RewindConfirmationProps> = ({
option.value !== RewindOutcome.RevertOnly,
);
}, [stats]);
if (isScreenReaderEnabled) {
return (
<Box flexDirection="column" width={terminalWidth}>
<Text bold>Confirm Rewind</Text>
{stats && (
<Box flexDirection="column">
<Text>
{stats.fileCount === 1
? `File: ${stats.details?.at(0)?.fileName}`
: `${stats.fileCount} files affected`}
</Text>
<Text>Lines added: {stats.addedLines}</Text>
<Text>Lines removed: {stats.removedLines}</Text>
{timestamp && <Text>({formatTimeAgo(timestamp)})</Text>}
<Text>
Note: Rewinding does not affect files edited manually or by the
shell tool.
</Text>
</Box>
)}
{!stats && (
<Box>
<Text color={theme.text.secondary}>No code changes to revert.</Text>
{timestamp && (
<Text color={theme.text.secondary}>
{' '}
({formatTimeAgo(timestamp)})
</Text>
)}
</Box>
)}
<Text>Select an action:</Text>
<Text color={theme.text.secondary}>
Use arrow keys to navigate, Enter to confirm, Esc to cancel.
</Text>
<RadioButtonSelect
items={options}
onSelect={handleSelect}
isFocused={true}
/>
</Box>
);
}
return (
<Box

Some files were not shown because too many files have changed in this diff Show More