diff --git a/.gemini/skills/docs-writer/SKILL.md b/.gemini/skills/docs-writer/SKILL.md index 13fc91765e..d7cf7b81be 100644 --- a/.gemini/skills/docs-writer/SKILL.md +++ b/.gemini/skills/docs-writer/SKILL.md @@ -45,6 +45,10 @@ Write precisely to ensure your instructions are unambiguous. specific verbs. - **Examples:** Use meaningful names in examples; avoid placeholders like "foo" or "bar." +- **Quota and limit terminology:** For any content involving resource capacity + or using the word "quota" or "limit", strictly adhere to the guidelines in + the `quota-limit-style-guide.md` resource file. Generally, Use "quota" for the + administrative bucket and "limit" for the numerical ceiling. ### Formatting and syntax Apply consistent formatting to make documentation visually organized and @@ -114,6 +118,8 @@ documentation. reflects existing code. - **Structure:** Apply "Structure (New Docs)" rules (BLUF, headings, etc.) when adding new sections to existing pages. +- **Headers**: If you change a header, you must check for links that lead to + that header and update them. - **Tone:** Ensure the tone is active and engaging. Use "you" and contractions. - **Clarity:** Correct awkward wording, spelling, and grammar. Rephrase sentences to make them easier for users to understand. @@ -129,7 +135,8 @@ and that all links are functional. technical behavior. 2. **Self-review:** Re-read changes for formatting, correctness, and flow. 3. **Link check:** Verify all new and existing links leading to or from modified - pages. + pages. If you changed a header, ensure that any links that lead to it are + updated. 4. **Format:** Once all changes are complete, ask to execute `npm run format` to ensure consistent formatting across the project. If the user confirms, execute the command. diff --git a/.gemini/skills/docs-writer/quota-limit-style-guide.md b/.gemini/skills/docs-writer/quota-limit-style-guide.md new file mode 100644 index 0000000000..b26c160cb5 --- /dev/null +++ b/.gemini/skills/docs-writer/quota-limit-style-guide.md @@ -0,0 +1,61 @@ +# Style Guide: Quota vs. Limit + +This guide defines the usage of "quota," "limit," and related terms in +user-facing interfaces. + +## TL;DR + +- **`quota`**: The administrative "bucket." Use for settings, billing, and + requesting increases. (e.g., "Adjust your storage **quota**.") +- **`limit`**: The real-time numerical "ceiling." Use for error messages when a + user is blocked. (e.g., "You've reached your request **limit**.") +- **When blocked, combine them:** Explain the **limit** that was hit and the + **quota** that is the remedy. (e.g., "You've reached the request **limit** for + your developer **quota**.") +- **Related terms:** Use `usage` for consumption tracking, `restriction` for + fixed rules, and `reset` for when a limit refreshes. + +--- + +## Detailed Guidelines + +### Definitions + +- **Quota is the "what":** It identifies the category of resource being managed + (e.g., storage quota, GPU quota, request/prompt quota). +- **Limit is the "how much":** It defines the numerical boundary. + +Use **quota** when referring to the administrative concept or the request for +more. Use **limit** when discussing the specific point of exhaustion. + +### When to use "quota" + +Use this term for **account management, billing, and settings.** It describes +the entitlement the user has purchased or been assigned. + +**Examples:** + +- **Navigation label:** Quota and usage +- **Contextual help:** Your **usage quota** is managed by your organization. To + request an increase, contact your administrator. + +### When to use "limit" + +Use this term for **real-time feedback, notifications, and error messages.** It +identifies the specific wall the user just hit. + +**Examples:** + +- **Error message:** You’ve reached the 50-request-per-minute **limit**. +- **Inline warning:** Input exceeds the 32k token **limit**. + +### How to use both together + +When a user is blocked, combine both terms to explain the **event** (limit) and +the **remedy** (quota). + +**Example:** + +- **Heading:** Daily usage limit reached +- **Body:** You've reached the maximum daily capacity for your developer quota. + To continue working today, upgrade your quota. diff --git a/.gemini/skills/string-reviewer/SKILL.md b/.gemini/skills/string-reviewer/SKILL.md new file mode 100644 index 0000000000..f37d83b4ad --- /dev/null +++ b/.gemini/skills/string-reviewer/SKILL.md @@ -0,0 +1,99 @@ +--- +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 user’s 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}"` +``` \ No newline at end of file diff --git a/.gemini/skills/string-reviewer/references/settings.md b/.gemini/skills/string-reviewer/references/settings.md new file mode 100644 index 0000000000..df054127a8 --- /dev/null +++ b/.gemini/skills/string-reviewer/references/settings.md @@ -0,0 +1,28 @@ +# 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` diff --git a/.gemini/skills/string-reviewer/references/word-list.md b/.gemini/skills/string-reviewer/references/word-list.md new file mode 100644 index 0000000000..1bb04b9817 --- /dev/null +++ b/.gemini/skills/string-reviewer/references/word-list.md @@ -0,0 +1,61 @@ +## 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. diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 201d46a66d..0da8dd1a0b 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -14,4 +14,9 @@ # Docs have a dedicated approver group in addition to maintainers /docs/ @google-gemini/gemini-cli-maintainers @google-gemini/gemini-cli-docs -/README.md @google-gemini/gemini-cli-maintainers @google-gemini/gemini-cli-docs \ No newline at end of file +/README.md @google-gemini/gemini-cli-maintainers @google-gemini/gemini-cli-docs + +# Prompt contents, tool definitions, and evals require reviews from prompt approvers +/packages/core/src/prompts/ @google-gemini/gemini-cli-prompt-approvers +/packages/core/src/tools/ @google-gemini/gemini-cli-prompt-approvers +/evals/ @google-gemini/gemini-cli-prompt-approvers diff --git a/.github/actions/publish-release/action.yml b/.github/actions/publish-release/action.yml index 8f062205cb..70a413f13a 100644 --- a/.github/actions/publish-release/action.yml +++ b/.github/actions/publish-release/action.yml @@ -192,6 +192,13 @@ runs: INPUTS_CLI_PACKAGE_NAME: '${{ inputs.cli-package-name }}' INPUTS_A2A_PACKAGE_NAME: '${{ inputs.a2a-package-name }}' + - name: '📦 Prepare bundled CLI for npm release' + if: "inputs.npm-registry-url != 'https://npm.pkg.github.com/'" + working-directory: '${{ inputs.working-directory }}' + shell: 'bash' + run: | + node ${{ github.workspace }}/scripts/prepare-npm-release.js + - name: 'Get CLI Token' uses: './.github/actions/npm-auth-token' id: 'cli-token' diff --git a/.github/actions/push-sandbox/action.yml b/.github/actions/push-sandbox/action.yml index e2d1ac942c..bab85af453 100644 --- a/.github/actions/push-sandbox/action.yml +++ b/.github/actions/push-sandbox/action.yml @@ -44,6 +44,8 @@ runs: - name: 'npm build' shell: 'bash' run: 'npm run build' + - name: 'Set up QEMU' + uses: 'docker/setup-qemu-action@v3' - name: 'Set up Docker Buildx' uses: 'docker/setup-buildx-action@v3' - name: 'Log in to GitHub Container Registry' @@ -69,16 +71,19 @@ runs: env: INPUTS_GITHUB_REF_NAME: '${{ inputs.github-ref-name }}' INPUTS_GITHUB_SHA: '${{ inputs.github-sha }}' + # We build amd64 just so we can verify it. + # We build and push both amd64 and arm64 in the publish step. - name: 'build' id: 'docker_build' shell: 'bash' env: GEMINI_SANDBOX_IMAGE_TAG: '${{ steps.image_tag.outputs.FINAL_TAG }}' GEMINI_SANDBOX: 'docker' + BUILD_SANDBOX_FLAGS: '--platform linux/amd64 --load' STEPS_IMAGE_TAG_OUTPUTS_FINAL_TAG: '${{ steps.image_tag.outputs.FINAL_TAG }}' run: |- npm run build:sandbox -- \ - --image google/gemini-cli-sandbox:${STEPS_IMAGE_TAG_OUTPUTS_FINAL_TAG} \ + --image "google/gemini-cli-sandbox:${STEPS_IMAGE_TAG_OUTPUTS_FINAL_TAG}" \ --output-file final_image_uri.txt echo "uri=$(cat final_image_uri.txt)" >> $GITHUB_OUTPUT - name: 'verify' @@ -92,10 +97,14 @@ runs: - name: 'publish' shell: 'bash' if: "${{ inputs.dry-run != 'true' }}" - run: |- - docker push "${STEPS_DOCKER_BUILD_OUTPUTS_URI}" env: - STEPS_DOCKER_BUILD_OUTPUTS_URI: '${{ steps.docker_build.outputs.uri }}' + GEMINI_SANDBOX_IMAGE_TAG: '${{ steps.image_tag.outputs.FINAL_TAG }}' + GEMINI_SANDBOX: 'docker' + BUILD_SANDBOX_FLAGS: '--platform linux/amd64,linux/arm64 --push' + STEPS_IMAGE_TAG_OUTPUTS_FINAL_TAG: '${{ steps.image_tag.outputs.FINAL_TAG }}' + run: |- + npm run build:sandbox -- \ + --image "google/gemini-cli-sandbox:${STEPS_IMAGE_TAG_OUTPUTS_FINAL_TAG}" - name: 'Create issue on failure' if: |- ${{ failure() }} diff --git a/.github/workflows/chained_e2e.yml b/.github/workflows/chained_e2e.yml index 3633c5027b..8d714b34b0 100644 --- a/.github/workflows/chained_e2e.yml +++ b/.github/workflows/chained_e2e.yml @@ -264,6 +264,27 @@ jobs: run: 'npm run build' shell: 'pwsh' + - name: 'Ensure Chrome is available' + shell: 'pwsh' + run: | + $chromePaths = @( + "${env:ProgramFiles}\Google\Chrome\Application\chrome.exe", + "${env:ProgramFiles(x86)}\Google\Chrome\Application\chrome.exe" + ) + $chromeExists = $chromePaths | Where-Object { Test-Path $_ } | Select-Object -First 1 + if (-not $chromeExists) { + Write-Host 'Chrome not found, installing via Chocolatey...' + choco install googlechrome -y --no-progress --ignore-checksums + } + $installed = $chromePaths | Where-Object { Test-Path $_ } | Select-Object -First 1 + if ($installed) { + Write-Host "Chrome found at: $installed" + & $installed --version + } else { + Write-Error 'Chrome installation failed' + exit 1 + } + - name: 'Run E2E tests' env: GEMINI_API_KEY: '${{ secrets.GEMINI_API_KEY }}' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a358ad8b07..973d88f5f8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 + 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:scripts fi diff --git a/.github/workflows/gemini-automated-issue-triage.yml b/.github/workflows/gemini-automated-issue-triage.yml index fe4c52292a..1cab2abaa9 100644 --- a/.github/workflows/gemini-automated-issue-triage.yml +++ b/.github/workflows/gemini-automated-issue-triage.yml @@ -121,6 +121,7 @@ jobs: 'area/security', 'area/platform', 'area/extensions', + 'area/documentation', 'area/unknown' ]; const labelNames = labels.map(label => label.name).filter(name => allowedLabels.includes(name)); @@ -255,6 +256,14 @@ jobs: "Issues with a specific extension." "Feature request for the extension ecosystem." + area/documentation + - Description: Issues related to user-facing documentation and other content on the documentation website. + - Example Issues: + "A typo in a README file." + "DOCS: A command is not working as described in the documentation." + "A request for a new documentation page." + "Instructions missing for skills feature" + area/unknown - Description: Issues that do not clearly fit into any other defined area/ category, or where information is too limited to make a determination. Use this when no other area is appropriate. diff --git a/.github/workflows/gemini-scheduled-issue-triage.yml b/.github/workflows/gemini-scheduled-issue-triage.yml index 25b0cdf4ec..50dd56883e 100644 --- a/.github/workflows/gemini-scheduled-issue-triage.yml +++ b/.github/workflows/gemini-scheduled-issue-triage.yml @@ -63,7 +63,7 @@ jobs: echo '🔍 Finding issues missing area labels...' NO_AREA_ISSUES="$(gh issue list --repo "${GITHUB_REPOSITORY}" \ - --search 'is:open is:issue -label:area/core -label:area/agent -label:area/enterprise -label:area/non-interactive -label:area/security -label:area/platform -label:area/extensions -label:area/unknown' --limit 100 --json number,title,body)" + --search 'is:open is:issue -label:area/core -label:area/agent -label:area/enterprise -label:area/non-interactive -label:area/security -label:area/platform -label:area/extensions -label:area/documentation -label:area/unknown' --limit 100 --json number,title,body)" echo '🔍 Finding issues missing kind labels...' NO_KIND_ISSUES="$(gh issue list --repo "${GITHUB_REPOSITORY}" \ @@ -204,6 +204,7 @@ jobs: Categorization Guidelines (Area): area/agent: Core Agent, Tools, Memory, Sub-Agents, Hooks, Agent Quality area/core: User Interface, OS Support, Core Functionality + area/documentation: End-user and contributor-facing documentation, website-related area/enterprise: Telemetry, Policy, Quota / Licensing area/extensions: Gemini CLI extensions capability area/non-interactive: GitHub Actions, SDK, 3P Integrations, Shell Scripting, Command line automation diff --git a/.github/workflows/unassign-inactive-assignees.yml b/.github/workflows/unassign-inactive-assignees.yml new file mode 100644 index 0000000000..dd09f0feaf --- /dev/null +++ b/.github/workflows/unassign-inactive-assignees.yml @@ -0,0 +1,315 @@ +name: 'Unassign Inactive Issue Assignees' + +# This workflow runs daily and scans every open "help wanted" issue that has +# one or more assignees. For each assignee it checks whether they have a +# non-draft pull request (open and ready for review, or already merged) that +# is linked to the issue. Draft PRs are intentionally excluded so that +# contributors cannot reset the check by opening a no-op PR. If no +# qualifying PR is found within 7 days of assignment the assignee is +# automatically removed and a friendly comment is posted so that other +# contributors can pick up the work. +# Maintainers, org members, and collaborators (anyone with write access or +# above) are always exempted and will never be auto-unassigned. + +on: + schedule: + - cron: '0 9 * * *' # Every day at 09:00 UTC + workflow_dispatch: + inputs: + dry_run: + description: 'Run in dry-run mode (no changes will be applied)' + required: false + default: false + type: 'boolean' + +concurrency: + group: '${{ github.workflow }}' + cancel-in-progress: true + +defaults: + run: + shell: 'bash' + +jobs: + unassign-inactive-assignees: + if: "github.repository == 'google-gemini/gemini-cli'" + runs-on: 'ubuntu-latest' + permissions: + issues: 'write' + + steps: + - name: 'Generate GitHub App Token' + id: 'generate_token' + uses: 'actions/create-github-app-token@v2' + with: + app-id: '${{ secrets.APP_ID }}' + private-key: '${{ secrets.PRIVATE_KEY }}' + + - name: 'Unassign inactive assignees' + uses: 'actions/github-script@v7' + env: + DRY_RUN: '${{ inputs.dry_run }}' + with: + github-token: '${{ steps.generate_token.outputs.token }}' + script: | + const dryRun = process.env.DRY_RUN === 'true'; + if (dryRun) { + core.info('DRY RUN MODE ENABLED: No changes will be applied.'); + } + + const owner = context.repo.owner; + const repo = context.repo.repo; + const GRACE_PERIOD_DAYS = 7; + const now = new Date(); + + let maintainerLogins = new Set(); + const teams = ['gemini-cli-maintainers', 'gemini-cli-askmode-approvers', 'gemini-cli-docs']; + + for (const team_slug of teams) { + try { + const members = await github.paginate(github.rest.teams.listMembersInOrg, { + org: owner, + team_slug, + }); + for (const m of members) maintainerLogins.add(m.login.toLowerCase()); + core.info(`Fetched ${members.length} members from team ${team_slug}.`); + } catch (e) { + core.warning(`Could not fetch team ${team_slug}: ${e.message}`); + } + } + + const isGooglerCache = new Map(); + const isGoogler = async (login) => { + if (isGooglerCache.has(login)) return isGooglerCache.get(login); + try { + for (const org of ['googlers', 'google']) { + try { + await github.rest.orgs.checkMembershipForUser({ org, username: login }); + isGooglerCache.set(login, true); + return true; + } catch (e) { + if (e.status !== 404) throw e; + } + } + } catch (e) { + core.warning(`Could not check org membership for ${login}: ${e.message}`); + } + isGooglerCache.set(login, false); + return false; + }; + + const permissionCache = new Map(); + const isPrivilegedUser = async (login) => { + if (maintainerLogins.has(login.toLowerCase())) return true; + + if (permissionCache.has(login)) return permissionCache.get(login); + + try { + const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner, + repo, + username: login, + }); + const privileged = ['admin', 'maintain', 'write', 'triage'].includes(data.permission); + permissionCache.set(login, privileged); + if (privileged) { + core.info(` @${login} is a repo collaborator (${data.permission}) — exempt.`); + return true; + } + } catch (e) { + if (e.status !== 404) { + core.warning(`Could not check permission for ${login}: ${e.message}`); + } + } + + const googler = await isGoogler(login); + permissionCache.set(login, googler); + return googler; + }; + + core.info('Fetching open "help wanted" issues with assignees...'); + + const issues = await github.paginate(github.rest.issues.listForRepo, { + owner, + repo, + state: 'open', + labels: 'help wanted', + per_page: 100, + }); + + const assignedIssues = issues.filter( + (issue) => !issue.pull_request && issue.assignees && issue.assignees.length > 0 + ); + + core.info(`Found ${assignedIssues.length} assigned "help wanted" issues.`); + + let totalUnassigned = 0; + + let timelineEvents = []; + try { + timelineEvents = await github.paginate(github.rest.issues.listEventsForTimeline, { + owner, + repo, + issue_number: issue.number, + per_page: 100, + mediaType: { previews: ['mockingbird'] }, + }); + } catch (err) { + core.warning(`Could not fetch timeline for issue #${issue.number}: ${err.message}`); + continue; + } + + const assignedAtMap = new Map(); + + for (const event of timelineEvents) { + if (event.event === 'assigned' && event.assignee) { + const login = event.assignee.login.toLowerCase(); + const at = new Date(event.created_at); + assignedAtMap.set(login, at); + } else if (event.event === 'unassigned' && event.assignee) { + assignedAtMap.delete(event.assignee.login.toLowerCase()); + } + } + + const linkedPRAuthorSet = new Set(); + const seenPRKeys = new Set(); + + for (const event of timelineEvents) { + if ( + event.event !== 'cross-referenced' || + !event.source || + event.source.type !== 'pull_request' || + !event.source.issue || + !event.source.issue.user || + !event.source.issue.number || + !event.source.issue.repository + ) continue; + + const prOwner = event.source.issue.repository.owner.login; + const prRepo = event.source.issue.repository.name; + const prNumber = event.source.issue.number; + const prAuthor = event.source.issue.user.login.toLowerCase(); + const prKey = `${prOwner}/${prRepo}#${prNumber}`; + + if (seenPRKeys.has(prKey)) continue; + seenPRKeys.add(prKey); + + try { + const { data: pr } = await github.rest.pulls.get({ + owner: prOwner, + repo: prRepo, + pull_number: prNumber, + }); + + const isReady = (pr.state === 'open' && !pr.draft) || + (pr.state === 'closed' && pr.merged_at !== null); + + core.info( + ` PR ${prKey} by @${prAuthor}: ` + + `state=${pr.state}, draft=${pr.draft}, merged=${!!pr.merged_at} → ` + + (isReady ? 'qualifies' : 'does NOT qualify (draft or closed without merge)') + ); + + if (isReady) linkedPRAuthorSet.add(prAuthor); + } catch (err) { + core.warning(`Could not fetch PR ${prKey}: ${err.message}`); + } + } + + const assigneesToRemove = []; + + for (const assignee of issue.assignees) { + const login = assignee.login.toLowerCase(); + + if (await isPrivilegedUser(assignee.login)) { + core.info(` @${assignee.login}: privileged user — skipping.`); + continue; + } + + const assignedAt = assignedAtMap.get(login); + + if (!assignedAt) { + core.warning( + `No 'assigned' event found for @${login} on issue #${issue.number}; ` + + `falling back to issue creation date (${issue.created_at}).` + ); + assignedAtMap.set(login, new Date(issue.created_at)); + } + const resolvedAssignedAt = assignedAtMap.get(login); + + const daysSinceAssignment = (now - resolvedAssignedAt) / (1000 * 60 * 60 * 24); + + core.info( + ` @${login}: assigned ${daysSinceAssignment.toFixed(1)} day(s) ago, ` + + `ready-for-review PR: ${linkedPRAuthorSet.has(login) ? 'yes' : 'no'}` + ); + + if (daysSinceAssignment < GRACE_PERIOD_DAYS) { + core.info(` → within grace period, skipping.`); + continue; + } + + if (linkedPRAuthorSet.has(login)) { + core.info(` → ready-for-review PR found, keeping assignment.`); + continue; + } + + core.info(` → no ready-for-review PR after ${GRACE_PERIOD_DAYS} days, will unassign.`); + assigneesToRemove.push(assignee.login); + } + + if (assigneesToRemove.length === 0) { + continue; + } + + if (!dryRun) { + try { + await github.rest.issues.removeAssignees({ + owner, + repo, + issue_number: issue.number, + assignees: assigneesToRemove, + }); + } catch (err) { + core.warning( + `Failed to unassign ${assigneesToRemove.join(', ')} from issue #${issue.number}: ${err.message}` + ); + continue; + } + + const mentionList = assigneesToRemove.map((l) => `@${l}`).join(', '); + const commentBody = + `👋 ${mentionList} — it has been more than ${GRACE_PERIOD_DAYS} days since ` + + `you were assigned to this issue and we could not find a pull request ` + + `ready for review.\n\n` + + `To keep the backlog moving and ensure issues stay accessible to all ` + + `contributors, we require a PR that is open and ready for review (not a ` + + `draft) within ${GRACE_PERIOD_DAYS} days of assignment.\n\n` + + `We are automatically unassigning you so that other contributors can pick ` + + `this up. If you are still actively working on this, please:\n` + + `1. Re-assign yourself by commenting \`/assign\`.\n` + + `2. Open a PR (not a draft) linked to this issue (e.g. \`Fixes #${issue.number}\`) ` + + `within ${GRACE_PERIOD_DAYS} days so the automation knows real progress is being made.\n\n` + + `Thank you for your contribution — we hope to see a PR from you soon! 🙏`; + + try { + await github.rest.issues.createComment({ + owner, + repo, + issue_number: issue.number, + body: commentBody, + }); + } catch (err) { + core.warning( + `Failed to post comment on issue #${issue.number}: ${err.message}` + ); + } + } + + totalUnassigned += assigneesToRemove.length; + core.info( + ` ${dryRun ? '[DRY RUN] Would have unassigned' : 'Unassigned'}: ${assigneesToRemove.join(', ')}` + ); + } + + core.info(`\nDone. Total assignees ${dryRun ? 'that would be' : ''} unassigned: ${totalUnassigned}`); diff --git a/.vscode/settings.json b/.vscode/settings.json index 3661ecf9c2..3197edbbfc 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -7,6 +7,9 @@ "[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, + "[typescriptreact]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, "[json]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d442f408f7..d0902b2e97 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -320,11 +320,9 @@ npm run lint - Please adhere to the coding style, patterns, and conventions used throughout the existing codebase. -- 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. +- 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. - **Imports:** Pay special attention to import paths. The project uses ESLint to enforce restrictions on relative imports between packages. diff --git a/README.md b/README.md index 02dd4988f0..959b5a9534 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ See [Releases](./docs/releases.md) for more details. ### Preview -New preview releases will be published each week at UTC 2359 on Tuesdays. These +New preview releases will be published each week at UTC 23:59 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 2000 on Tuesdays, this +- New stable releases will be published each week at UTC 20:00 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 0000. This will be all changes +- New releases will be published each day at UTC 00:00. 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. @@ -301,7 +301,7 @@ gemini ### Tools & Extensions -- [**Built-in Tools Overview**](./docs/tools/index.md) +- [**Built-in Tools Overview**](./docs/reference/tools.md) - [File System Operations](./docs/tools/file-system.md) - [Shell Commands](./docs/tools/shell.md) - [Web Fetch & Search](./docs/tools/web-fetch.md) @@ -323,8 +323,7 @@ gemini - [**Enterprise Guide**](./docs/cli/enterprise.md) - Deploy and manage in a corporate environment. - [**Telemetry & Monitoring**](./docs/cli/telemetry.md) - Usage tracking. -- [**Tools API Development**](./docs/reference/tools-api.md) - Create custom - tools. +- [**Tools reference**](./docs/reference/tools.md) - Built-in tools overview. - [**Local development**](./docs/local-development.md) - Local development tooling. diff --git a/docs/changelogs/index.md b/docs/changelogs/index.md index 537e9d1aee..33c179072a 100644 --- a/docs/changelogs/index.md +++ b/docs/changelogs/index.md @@ -18,6 +18,30 @@ on GitHub. | [Preview](preview.md) | Experimental features ready for early feedback. | | [Stable](latest.md) | Stable, recommended for general use. | +## Announcements: v0.32.0 - 2026-03-03 + +- **Generalist Agent:** The generalist agent is now enabled to improve task + delegation and routing + ([#19665](https://github.com/google-gemini/gemini-cli/pull/19665) by + @joshualitt). +- **Model Steering in Workspace:** Added support for model steering directly in + the workspace + ([#20343](https://github.com/google-gemini/gemini-cli/pull/20343) by + @joshualitt). +- **Plan Mode Enhancements:** Users can now open and modify plans in an external + editor, and the planning workflow has been adapted to handle complex tasks + more effectively with multi-select options + ([#20348](https://github.com/google-gemini/gemini-cli/pull/20348) by @Adib234, + [#20465](https://github.com/google-gemini/gemini-cli/pull/20465) by @jerop). +- **Interactive Shell Autocompletion:** Introduced interactive shell + autocompletion for a more seamless experience + ([#20082](https://github.com/google-gemini/gemini-cli/pull/20082) by + @mrpmohiburrahman). +- **Parallel Extension Loading:** Extensions are now loaded in parallel to + improve startup times + ([#20229](https://github.com/google-gemini/gemini-cli/pull/20229) by + @scidomino). + ## Announcements: v0.31.0 - 2026-02-27 - **Gemini 3.1 Pro Preview:** Gemini CLI now supports the new Gemini 3.1 Pro diff --git a/docs/changelogs/latest.md b/docs/changelogs/latest.md index 760e070bd9..d5d13717c7 100644 --- a/docs/changelogs/latest.md +++ b/docs/changelogs/latest.md @@ -1,6 +1,6 @@ -# Latest stable release: v0.31.0 +# Latest stable release: v0.32.1 -Released: February 27, 2026 +Released: March 4, 2026 For most users, our latest stable release is the recommended release. Install the latest stable version with: @@ -11,405 +11,198 @@ npm install -g @google/gemini-cli ## Highlights -- **Gemini 3.1 Pro Preview:** Gemini CLI now supports the new Gemini 3.1 Pro - Preview model. -- **Experimental Browser Agent:** We've introduced a new experimental browser - agent to directly interact with web pages and retrieve context. -- **Policy Engine Updates:** The policy engine has been expanded to support - project-level policies, MCP server wildcards, and tool annotation matching, - providing greater control over tool executions. -- **Web Fetch Enhancements:** A new experimental direct web fetch tool has been - implemented, alongside rate-limiting features for enhanced security. -- **Improved Plan Mode:** Plan Mode now includes support for custom storage - directories, automatic model switching, and summarizing work after execution. +- **Plan Mode Enhancements**: Significant updates to Plan Mode, including the + ability to open and modify plans in an external editor, adaptations for + complex tasks with multi-select options, and integration tests for plan mode. +- **Agent and Steering Improvements**: The generalist agent has been enabled to + enhance task delegation, model steering is now supported directly within the + workspace, and contiguous parallel admission is enabled for `Kind.Agent` + tools. +- **Interactive Shell**: Interactive shell autocompletion has been introduced, + significantly enhancing the user experience. +- **Core Stability and Performance**: Extensions are now loaded in parallel, + fetch timeouts have been increased, robust A2A streaming reassembly was + implemented, and orphaned processes when terminal closes have been prevented. +- **Billing and Quota Handling**: Implemented G1 AI credits overage flow with + billing telemetry and added support for quota error fallbacks across all + authentication types. ## What's Changed -- Use ranged reads and limited searches and fuzzy editing improvements by - @gundermanc in - [#19240](https://github.com/google-gemini/gemini-cli/pull/19240) -- Fix bottom border color by @jacob314 in - [#19266](https://github.com/google-gemini/gemini-cli/pull/19266) -- Release note generator fix by @g-samroberts in - [#19363](https://github.com/google-gemini/gemini-cli/pull/19363) -- test(evals): add behavioral tests for tool output masking by @NTaylorMullen in - [#19172](https://github.com/google-gemini/gemini-cli/pull/19172) -- docs: clarify preflight instructions in GEMINI.md by @NTaylorMullen in - [#19377](https://github.com/google-gemini/gemini-cli/pull/19377) -- feat(cli): add gemini --resume hint on exit by @Mag1ck in - [#16285](https://github.com/google-gemini/gemini-cli/pull/16285) -- fix: optimize height calculations for ask_user dialog by @jackwotherspoon in - [#19017](https://github.com/google-gemini/gemini-cli/pull/19017) -- feat(cli): add Alt+D for forward word deletion by @scidomino in - [#19300](https://github.com/google-gemini/gemini-cli/pull/19300) -- Disable failing eval test by @chrstnb in - [#19455](https://github.com/google-gemini/gemini-cli/pull/19455) -- fix(cli): support legacy onConfirm callback in ToolActionsContext by +- fix(patch): cherry-pick 0659ad1 to release/v0.32.0-pr-21042 to patch version + v0.32.0 and create version 0.32.1 by @gemini-cli-robot in + [#21048](https://github.com/google-gemini/gemini-cli/pull/21048) +- feat(plan): add integration tests for plan mode by @Adib234 in + [#20214](https://github.com/google-gemini/gemini-cli/pull/20214) +- fix(acp): update auth handshake to spec by @skeshive in + [#19725](https://github.com/google-gemini/gemini-cli/pull/19725) +- feat(core): implement robust A2A streaming reassembly and fix task continuity + by @adamfweidman in + [#20091](https://github.com/google-gemini/gemini-cli/pull/20091) +- feat(cli): load extensions in parallel by @scidomino in + [#20229](https://github.com/google-gemini/gemini-cli/pull/20229) +- Plumb the maxAttempts setting through Config args by @kevinjwang1 in + [#20239](https://github.com/google-gemini/gemini-cli/pull/20239) +- fix(cli): skip 404 errors in setup-github file downloads by @h30s in + [#20287](https://github.com/google-gemini/gemini-cli/pull/20287) +- fix(cli): expose model.name setting in settings dialog for persistence by + @achaljhawar in + [#19605](https://github.com/google-gemini/gemini-cli/pull/19605) +- docs: remove legacy cmd examples in favor of powershell by @scidomino in + [#20323](https://github.com/google-gemini/gemini-cli/pull/20323) +- feat(core): Enable model steering in workspace. by @joshualitt in + [#20343](https://github.com/google-gemini/gemini-cli/pull/20343) +- fix: remove trailing comma in issue triage workflow settings json by @Nixxx19 + in [#20265](https://github.com/google-gemini/gemini-cli/pull/20265) +- feat(core): implement task tracker foundation and service by @anj-s in + [#19464](https://github.com/google-gemini/gemini-cli/pull/19464) +- test: support tests that include color information by @jacob314 in + [#20220](https://github.com/google-gemini/gemini-cli/pull/20220) +- feat(core): introduce Kind.Agent for sub-agent classification by @abhipatel12 + in [#20369](https://github.com/google-gemini/gemini-cli/pull/20369) +- Changelog for v0.30.0 by @gemini-cli-robot in + [#20252](https://github.com/google-gemini/gemini-cli/pull/20252) +- Update changelog workflow to reject nightly builds by @g-samroberts in + [#20248](https://github.com/google-gemini/gemini-cli/pull/20248) +- Changelog for v0.31.0-preview.0 by @gemini-cli-robot in + [#20249](https://github.com/google-gemini/gemini-cli/pull/20249) +- feat(cli): hide workspace policy update dialog and auto-accept by default by + @Abhijit-2592 in + [#20351](https://github.com/google-gemini/gemini-cli/pull/20351) +- feat(core): rename grep_search include parameter to include_pattern by @SandyTao520 in - [#19369](https://github.com/google-gemini/gemini-cli/pull/19369) -- chore(deps): bump tar from 7.5.7 to 7.5.8 by @.github/dependabot.yml[bot] in - [#19367](https://github.com/google-gemini/gemini-cli/pull/19367) -- fix(plan): allow safe fallback when experiment setting for plan is not enabled - but approval mode at startup is plan by @Adib234 in - [#19439](https://github.com/google-gemini/gemini-cli/pull/19439) -- Add explicit color-convert dependency by @chrstnb in - [#19460](https://github.com/google-gemini/gemini-cli/pull/19460) -- feat(devtools): migrate devtools package into monorepo by @SandyTao520 in - [#18936](https://github.com/google-gemini/gemini-cli/pull/18936) -- fix(core): clarify plan mode constraints and exit mechanism by @jerop in - [#19438](https://github.com/google-gemini/gemini-cli/pull/19438) -- feat(cli): add macOS run-event notifications (interactive only) by - @LyalinDotCom in - [#19056](https://github.com/google-gemini/gemini-cli/pull/19056) -- Changelog for v0.29.0 by @gemini-cli-robot in - [#19361](https://github.com/google-gemini/gemini-cli/pull/19361) -- fix(ui): preventing empty history items from being added by @devr0306 in - [#19014](https://github.com/google-gemini/gemini-cli/pull/19014) -- Changelog for v0.30.0-preview.0 by @gemini-cli-robot in - [#19364](https://github.com/google-gemini/gemini-cli/pull/19364) -- feat(core): add support for MCP progress updates by @NTaylorMullen in - [#19046](https://github.com/google-gemini/gemini-cli/pull/19046) -- fix(core): ensure directory exists before writing conversation file by - @godwiniheuwa in - [#18429](https://github.com/google-gemini/gemini-cli/pull/18429) -- fix(ui): move margin from top to bottom in ToolGroupMessage by @imadraude in - [#17198](https://github.com/google-gemini/gemini-cli/pull/17198) -- fix(cli): treat unknown slash commands as regular input instead of showing - error by @skyvanguard in - [#17393](https://github.com/google-gemini/gemini-cli/pull/17393) -- feat(core): experimental in-progress steering hints (2 of 2) by @joshualitt in - [#19307](https://github.com/google-gemini/gemini-cli/pull/19307) -- docs(plan): add documentation for plan mode command by @Adib234 in - [#19467](https://github.com/google-gemini/gemini-cli/pull/19467) -- fix(core): ripgrep fails when pattern looks like ripgrep flag by @syvb in - [#18858](https://github.com/google-gemini/gemini-cli/pull/18858) -- fix(cli): disable auto-completion on Shift+Tab to preserve mode cycling by - @NTaylorMullen in - [#19451](https://github.com/google-gemini/gemini-cli/pull/19451) -- use issuer instead of authorization_endpoint for oauth discovery by - @garrettsparks in - [#17332](https://github.com/google-gemini/gemini-cli/pull/17332) -- feat(cli): include `/dir add` directories in @ autocomplete suggestions by - @jasmeetsb in [#19246](https://github.com/google-gemini/gemini-cli/pull/19246) -- feat(admin): Admin settings should only apply if adminControlsApplicable = - true and fetch errors should be fatal by @skeshive in - [#19453](https://github.com/google-gemini/gemini-cli/pull/19453) -- Format strict-development-rules command by @g-samroberts in - [#19484](https://github.com/google-gemini/gemini-cli/pull/19484) -- feat(core): centralize compatibility checks and add TrueColor detection by + [#20328](https://github.com/google-gemini/gemini-cli/pull/20328) +- feat(plan): support opening and modifying plan in external editor by @Adib234 + in [#20348](https://github.com/google-gemini/gemini-cli/pull/20348) +- feat(cli): implement interactive shell autocompletion by @mrpmohiburrahman in + [#20082](https://github.com/google-gemini/gemini-cli/pull/20082) +- fix(core): allow /memory add to work in plan mode by @Jefftree in + [#20353](https://github.com/google-gemini/gemini-cli/pull/20353) +- feat(core): add HTTP 499 to retryable errors and map to RetryableQuotaError by + @bdmorgan in [#20432](https://github.com/google-gemini/gemini-cli/pull/20432) +- feat(core): Enable generalist agent by @joshualitt in + [#19665](https://github.com/google-gemini/gemini-cli/pull/19665) +- Updated tests in TableRenderer.test.tsx to use SVG snapshots by @devr0306 in + [#20450](https://github.com/google-gemini/gemini-cli/pull/20450) +- Refactor Github Action per b/485167538 by @google-admin in + [#19443](https://github.com/google-gemini/gemini-cli/pull/19443) +- fix(github): resolve actionlint and yamllint regressions from #19443 by @jerop + in [#20467](https://github.com/google-gemini/gemini-cli/pull/20467) +- fix: action var usage by @galz10 in + [#20492](https://github.com/google-gemini/gemini-cli/pull/20492) +- feat(core): improve A2A content extraction by @adamfweidman in + [#20487](https://github.com/google-gemini/gemini-cli/pull/20487) +- fix(cli): support quota error fallbacks for all authentication types by + @sehoon38 in [#20475](https://github.com/google-gemini/gemini-cli/pull/20475) +- fix(core): flush transcript for pure tool-call responses to ensure BeforeTool + hooks see complete state by @krishdef7 in + [#20419](https://github.com/google-gemini/gemini-cli/pull/20419) +- feat(plan): adapt planning workflow based on complexity of task by @jerop in + [#20465](https://github.com/google-gemini/gemini-cli/pull/20465) +- fix: prevent orphaned processes from consuming 100% CPU when terminal closes + by @yuvrajangadsingh in + [#16965](https://github.com/google-gemini/gemini-cli/pull/16965) +- feat(core): increase fetch timeout and fix [object Object] error + stringification by @bdmorgan in + [#20441](https://github.com/google-gemini/gemini-cli/pull/20441) +- [Gemma x Gemini CLI] Add an Experimental Gemma Router that uses a LiteRT-LM + shim into the Composite Model Classifier Strategy by @sidwan02 in + [#17231](https://github.com/google-gemini/gemini-cli/pull/17231) +- docs(plan): update documentation regarding supporting editing of plan files + during plan approval by @Adib234 in + [#20452](https://github.com/google-gemini/gemini-cli/pull/20452) +- test(cli): fix flaky ToolResultDisplay overflow test by @jwhelangoog in + [#20518](https://github.com/google-gemini/gemini-cli/pull/20518) +- ui(cli): reduce length of Ctrl+O hint by @jwhelangoog in + [#20490](https://github.com/google-gemini/gemini-cli/pull/20490) +- fix(ui): correct styled table width calculations by @devr0306 in + [#20042](https://github.com/google-gemini/gemini-cli/pull/20042) +- Avoid overaggressive unescaping by @scidomino in + [#20520](https://github.com/google-gemini/gemini-cli/pull/20520) +- feat(telemetry) Instrument traces with more attributes and make them available + to OTEL users by @heaventourist in + [#20237](https://github.com/google-gemini/gemini-cli/pull/20237) +- Add support for policy engine in extensions by @chrstnb in + [#20049](https://github.com/google-gemini/gemini-cli/pull/20049) +- Docs: Update to Terms of Service & FAQ by @jkcinouye in + [#20488](https://github.com/google-gemini/gemini-cli/pull/20488) +- Fix bottom border rendering for search and add a regression test. by @jacob314 + in [#20517](https://github.com/google-gemini/gemini-cli/pull/20517) +- fix(core): apply retry logic to CodeAssistServer for all users by @bdmorgan in + [#20507](https://github.com/google-gemini/gemini-cli/pull/20507) +- Fix extension MCP server env var loading by @chrstnb in + [#20374](https://github.com/google-gemini/gemini-cli/pull/20374) +- feat(ui): add 'ctrl+o' hint to truncated content message by @jerop in + [#20529](https://github.com/google-gemini/gemini-cli/pull/20529) +- Fix flicker showing message to press ctrl-O again to collapse. by @jacob314 in + [#20414](https://github.com/google-gemini/gemini-cli/pull/20414) +- fix(cli): hide shortcuts hint while model is thinking or the user has typed a + prompt + add debounce to avoid flicker by @jacob314 in + [#19389](https://github.com/google-gemini/gemini-cli/pull/19389) +- feat(plan): update planning workflow to encourage multi-select with + descriptions of options by @Adib234 in + [#20491](https://github.com/google-gemini/gemini-cli/pull/20491) +- refactor(core,cli): useAlternateBuffer read from config by @psinha40898 in + [#20346](https://github.com/google-gemini/gemini-cli/pull/20346) +- fix(cli): ensure dialogs stay scrolled to bottom in alternate buffer mode by + @jacob314 in [#20527](https://github.com/google-gemini/gemini-cli/pull/20527) +- fix(core): revert auto-save of policies to user space by @Abhijit-2592 in + [#20531](https://github.com/google-gemini/gemini-cli/pull/20531) +- Demote unreliable test. by @gundermanc in + [#20571](https://github.com/google-gemini/gemini-cli/pull/20571) +- fix(core): handle optional response fields from code assist API by @sehoon38 + in [#20345](https://github.com/google-gemini/gemini-cli/pull/20345) +- fix(cli): keep thought summary when loading phrases are off by @LyalinDotCom + in [#20497](https://github.com/google-gemini/gemini-cli/pull/20497) +- feat(cli): add temporary flag to disable workspace policies by @Abhijit-2592 + in [#20523](https://github.com/google-gemini/gemini-cli/pull/20523) +- Disable expensive and scheduled workflows on personal forks by @dewitt in + [#20449](https://github.com/google-gemini/gemini-cli/pull/20449) +- Moved markdown parsing logic to a separate util file by @devr0306 in + [#20526](https://github.com/google-gemini/gemini-cli/pull/20526) +- fix(plan): prevent agent from using ask_user for shell command confirmation by + @Adib234 in [#20504](https://github.com/google-gemini/gemini-cli/pull/20504) +- fix(core): disable retries for code assist streaming requests by @sehoon38 in + [#20561](https://github.com/google-gemini/gemini-cli/pull/20561) +- feat(billing): implement G1 AI credits overage flow with billing telemetry by + @gsquared94 in + [#18590](https://github.com/google-gemini/gemini-cli/pull/18590) +- feat: better error messages by @gsquared94 in + [#20577](https://github.com/google-gemini/gemini-cli/pull/20577) +- fix(ui): persist expansion in AskUser dialog when navigating options by @jerop + in [#20559](https://github.com/google-gemini/gemini-cli/pull/20559) +- fix(cli): prevent sub-agent tool calls from leaking into UI by @abhipatel12 in + [#20580](https://github.com/google-gemini/gemini-cli/pull/20580) +- fix(cli): Shell autocomplete polish by @jacob314 in + [#20411](https://github.com/google-gemini/gemini-cli/pull/20411) +- Changelog for v0.31.0-preview.1 by @gemini-cli-robot in + [#20590](https://github.com/google-gemini/gemini-cli/pull/20590) +- Add slash command for promoting behavioral evals to CI blocking by @gundermanc + in [#20575](https://github.com/google-gemini/gemini-cli/pull/20575) +- Changelog for v0.30.1 by @gemini-cli-robot in + [#20589](https://github.com/google-gemini/gemini-cli/pull/20589) +- Add low/full CLI error verbosity mode for cleaner UI by @LyalinDotCom in + [#20399](https://github.com/google-gemini/gemini-cli/pull/20399) +- Disable Gemini PR reviews on draft PRs. by @gundermanc in + [#20362](https://github.com/google-gemini/gemini-cli/pull/20362) +- Docs: FAQ update by @jkcinouye in + [#20585](https://github.com/google-gemini/gemini-cli/pull/20585) +- fix(core): reduce intrusive MCP errors and deduplicate diagnostics by @spencer426 in - [#19478](https://github.com/google-gemini/gemini-cli/pull/19478) -- Remove unused files and update index and sidebar. by @g-samroberts in - [#19479](https://github.com/google-gemini/gemini-cli/pull/19479) -- Migrate core render util to use xterm.js as part of the rendering loop. by - @jacob314 in [#19044](https://github.com/google-gemini/gemini-cli/pull/19044) -- Changelog for v0.30.0-preview.1 by @gemini-cli-robot in - [#19496](https://github.com/google-gemini/gemini-cli/pull/19496) -- build: replace deprecated built-in punycode with userland package by @jacob314 - in [#19502](https://github.com/google-gemini/gemini-cli/pull/19502) -- Speculative fixes to try to fix react error. by @jacob314 in - [#19508](https://github.com/google-gemini/gemini-cli/pull/19508) -- fix spacing by @jacob314 in - [#19494](https://github.com/google-gemini/gemini-cli/pull/19494) -- fix(core): ensure user rejections update tool outcome for telemetry by - @abhiasap in [#18982](https://github.com/google-gemini/gemini-cli/pull/18982) -- fix(acp): Initialize config (#18897) by @Mervap in - [#18898](https://github.com/google-gemini/gemini-cli/pull/18898) -- fix(core): add error logging for IDE fetch failures by @yuvrajangadsingh in - [#17981](https://github.com/google-gemini/gemini-cli/pull/17981) -- feat(acp): support set_mode interface (#18890) by @Mervap in - [#18891](https://github.com/google-gemini/gemini-cli/pull/18891) -- fix(core): robust workspace-based IDE connection discovery by @ehedlund in - [#18443](https://github.com/google-gemini/gemini-cli/pull/18443) -- Deflake windows tests. by @jacob314 in - [#19511](https://github.com/google-gemini/gemini-cli/pull/19511) -- Fix: Avoid tool confirmation timeout when no UI listeners are present by - @pdHaku0 in [#17955](https://github.com/google-gemini/gemini-cli/pull/17955) -- format md file by @scidomino in - [#19474](https://github.com/google-gemini/gemini-cli/pull/19474) -- feat(cli): add experimental.useOSC52Copy setting by @scidomino in - [#19488](https://github.com/google-gemini/gemini-cli/pull/19488) -- feat(cli): replace loading phrases boolean with enum setting by @LyalinDotCom - in [#19347](https://github.com/google-gemini/gemini-cli/pull/19347) -- Update skill to adjust for generated results. by @g-samroberts in - [#19500](https://github.com/google-gemini/gemini-cli/pull/19500) -- Fix message too large issue. by @gundermanc in - [#19499](https://github.com/google-gemini/gemini-cli/pull/19499) -- fix(core): prevent duplicate tool approval entries in auto-saved.toml by - @Abhijit-2592 in - [#19487](https://github.com/google-gemini/gemini-cli/pull/19487) -- fix(core): resolve crash in ClearcutLogger when os.cpus() is empty by @Adib234 - in [#19555](https://github.com/google-gemini/gemini-cli/pull/19555) -- chore(core): improve encapsulation and remove unused exports by @adamfweidman - in [#19556](https://github.com/google-gemini/gemini-cli/pull/19556) -- Revert "Add generic searchable list to back settings and extensions (… by - @chrstnb in [#19434](https://github.com/google-gemini/gemini-cli/pull/19434) -- fix(core): improve error type extraction for telemetry by @yunaseoul in - [#19565](https://github.com/google-gemini/gemini-cli/pull/19565) -- fix: remove extra padding in Composer by @jackwotherspoon in - [#19529](https://github.com/google-gemini/gemini-cli/pull/19529) -- feat(plan): support configuring custom plans storage directory by @jerop in - [#19577](https://github.com/google-gemini/gemini-cli/pull/19577) -- Migrate files to resource or references folder. by @g-samroberts in - [#19503](https://github.com/google-gemini/gemini-cli/pull/19503) -- feat(policy): implement project-level policy support by @Abhijit-2592 in - [#18682](https://github.com/google-gemini/gemini-cli/pull/18682) -- feat(core): Implement parallel FC for read only tools. by @joshualitt in - [#18791](https://github.com/google-gemini/gemini-cli/pull/18791) -- chore(skills): adds pr-address-comments skill to work on PR feedback by - @mbleigh in [#19576](https://github.com/google-gemini/gemini-cli/pull/19576) -- refactor(sdk): introduce session-based architecture by @mbleigh in - [#19180](https://github.com/google-gemini/gemini-cli/pull/19180) -- fix(ci): add fallback JSON extraction to issue triage workflow by @bdmorgan in - [#19593](https://github.com/google-gemini/gemini-cli/pull/19593) -- feat(core): refine Edit and WriteFile tool schemas for Gemini 3 by - @SandyTao520 in - [#19476](https://github.com/google-gemini/gemini-cli/pull/19476) -- Changelog for v0.30.0-preview.3 by @gemini-cli-robot in - [#19585](https://github.com/google-gemini/gemini-cli/pull/19585) -- fix(plan): exclude EnterPlanMode tool from YOLO mode by @Adib234 in - [#19570](https://github.com/google-gemini/gemini-cli/pull/19570) -- chore: resolve build warnings and update dependencies by @mattKorwel in - [#18880](https://github.com/google-gemini/gemini-cli/pull/18880) -- feat(ui): add source indicators to slash commands by @ehedlund in - [#18839](https://github.com/google-gemini/gemini-cli/pull/18839) -- docs: refine Plan Mode documentation structure and workflow by @jerop in - [#19644](https://github.com/google-gemini/gemini-cli/pull/19644) -- Docs: Update release information regarding Gemini 3.1 by @jkcinouye in - [#19568](https://github.com/google-gemini/gemini-cli/pull/19568) -- fix(security): rate limit web_fetch tool to mitigate DDoS via prompt injection - by @mattKorwel in - [#19567](https://github.com/google-gemini/gemini-cli/pull/19567) -- Add initial implementation of /extensions explore command by @chrstnb in - [#19029](https://github.com/google-gemini/gemini-cli/pull/19029) -- fix: use discoverOAuthFromWWWAuthenticate for reactive OAuth flow (#18760) by - @maximus12793 in - [#19038](https://github.com/google-gemini/gemini-cli/pull/19038) -- Search updates by @alisa-alisa in - [#19482](https://github.com/google-gemini/gemini-cli/pull/19482) -- feat(cli): add support for numpad SS3 sequences by @scidomino in - [#19659](https://github.com/google-gemini/gemini-cli/pull/19659) -- feat(cli): enhance folder trust with configuration discovery and security - warnings by @galz10 in - [#19492](https://github.com/google-gemini/gemini-cli/pull/19492) -- feat(ui): improve startup warnings UX with dismissal and show-count limits by - @spencer426 in - [#19584](https://github.com/google-gemini/gemini-cli/pull/19584) -- feat(a2a): Add API key authentication provider by @adamfweidman in - [#19548](https://github.com/google-gemini/gemini-cli/pull/19548) -- Send accepted/removed lines with ACCEPT_FILE telemetry. by @gundermanc in - [#19670](https://github.com/google-gemini/gemini-cli/pull/19670) -- feat(models): support Gemini 3.1 Pro Preview and fixes by @sehoon38 in - [#19676](https://github.com/google-gemini/gemini-cli/pull/19676) -- feat(plan): enforce read-only constraints in Plan Mode by @mattKorwel in - [#19433](https://github.com/google-gemini/gemini-cli/pull/19433) -- fix(cli): allow perfect match @scripts/test-windows-paths.js completions to - submit on Enter by @spencer426 in - [#19562](https://github.com/google-gemini/gemini-cli/pull/19562) -- fix(core): treat 503 Service Unavailable as retryable quota error by @sehoon38 - in [#19642](https://github.com/google-gemini/gemini-cli/pull/19642) -- Update sidebar.json for to allow top nav tabs. by @g-samroberts in - [#19595](https://github.com/google-gemini/gemini-cli/pull/19595) -- security: strip deceptive Unicode characters from terminal output by @ehedlund - in [#19026](https://github.com/google-gemini/gemini-cli/pull/19026) -- Fixes 'input.on' is not a function error in Gemini CLI by @gundermanc in - [#19691](https://github.com/google-gemini/gemini-cli/pull/19691) -- Revert "feat(ui): add source indicators to slash commands" by @ehedlund in - [#19695](https://github.com/google-gemini/gemini-cli/pull/19695) -- security: implement deceptive URL detection and disclosure in tool - confirmations by @ehedlund in - [#19288](https://github.com/google-gemini/gemini-cli/pull/19288) -- fix(core): restore auth consent in headless mode and add unit tests by - @ehedlund in [#19689](https://github.com/google-gemini/gemini-cli/pull/19689) -- Fix unsafe assertions in code_assist folder. by @gundermanc in - [#19706](https://github.com/google-gemini/gemini-cli/pull/19706) -- feat(cli): make JetBrains warning more specific by @jacob314 in - [#19687](https://github.com/google-gemini/gemini-cli/pull/19687) -- fix(cli): extensions dialog UX polish by @jacob314 in - [#19685](https://github.com/google-gemini/gemini-cli/pull/19685) -- fix(cli): use getDisplayString for manual model selection in dialog by - @sehoon38 in [#19726](https://github.com/google-gemini/gemini-cli/pull/19726) -- feat(policy): repurpose "Always Allow" persistence to workspace level by - @Abhijit-2592 in - [#19707](https://github.com/google-gemini/gemini-cli/pull/19707) -- fix(cli): re-enable CLI banner by @sehoon38 in - [#19741](https://github.com/google-gemini/gemini-cli/pull/19741) -- Disallow and suppress unsafe assignment by @gundermanc in - [#19736](https://github.com/google-gemini/gemini-cli/pull/19736) -- feat(core): migrate read_file to 1-based start_line/end_line parameters by - @adamfweidman in - [#19526](https://github.com/google-gemini/gemini-cli/pull/19526) -- feat(cli): improve CTRL+O experience for both standard and alternate screen - buffer (ASB) modes by @jwhelangoog in - [#19010](https://github.com/google-gemini/gemini-cli/pull/19010) -- Utilize pipelining of grep_search -> read_file to eliminate turns by - @gundermanc in - [#19574](https://github.com/google-gemini/gemini-cli/pull/19574) -- refactor(core): remove unsafe type assertions in error utils (Phase 1.1) by - @mattKorwel in - [#19750](https://github.com/google-gemini/gemini-cli/pull/19750) -- Disallow unsafe returns. by @gundermanc in - [#19767](https://github.com/google-gemini/gemini-cli/pull/19767) -- fix(cli): filter subagent sessions from resume history by @abhipatel12 in - [#19698](https://github.com/google-gemini/gemini-cli/pull/19698) -- chore(lint): fix lint errors seen when running npm run lint by @abhipatel12 in - [#19844](https://github.com/google-gemini/gemini-cli/pull/19844) -- feat(core): remove unnecessary login verbiage from Code Assist auth by - @NTaylorMullen in - [#19861](https://github.com/google-gemini/gemini-cli/pull/19861) -- fix(plan): time share by approval mode dashboard reporting negative time - shares by @Adib234 in - [#19847](https://github.com/google-gemini/gemini-cli/pull/19847) -- fix(core): allow any preview model in quota access check by @bdmorgan in - [#19867](https://github.com/google-gemini/gemini-cli/pull/19867) -- fix(core): prevent omission placeholder deletions in replace/write_file by - @nsalerni in [#19870](https://github.com/google-gemini/gemini-cli/pull/19870) -- fix(core): add uniqueness guard to edit tool by @Shivangisharma4 in - [#19890](https://github.com/google-gemini/gemini-cli/pull/19890) -- refactor(config): remove enablePromptCompletion from settings by @sehoon38 in - [#19974](https://github.com/google-gemini/gemini-cli/pull/19974) -- refactor(core): move session conversion logic to core by @abhipatel12 in - [#19972](https://github.com/google-gemini/gemini-cli/pull/19972) -- Fix: Persist manual model selection on restart #19864 by @Nixxx19 in - [#19891](https://github.com/google-gemini/gemini-cli/pull/19891) -- fix(core): increase default retry attempts and add quota error backoff by - @sehoon38 in [#19949](https://github.com/google-gemini/gemini-cli/pull/19949) -- feat(core): add policy chain support for Gemini 3.1 by @sehoon38 in - [#19991](https://github.com/google-gemini/gemini-cli/pull/19991) -- Updates command reference and /stats command. by @g-samroberts in - [#19794](https://github.com/google-gemini/gemini-cli/pull/19794) -- Fix for silent failures in non-interactive mode by @owenofbrien in - [#19905](https://github.com/google-gemini/gemini-cli/pull/19905) -- fix(plan): allow plan mode writes on Windows and fix prompt paths by @Adib234 - in [#19658](https://github.com/google-gemini/gemini-cli/pull/19658) -- fix(core): prevent OAuth server crash on unexpected requests by @reyyanxahmed - in [#19668](https://github.com/google-gemini/gemini-cli/pull/19668) -- feat: Map tool kinds to explicit ACP.ToolKind values and update test … by - @sripasg in [#19547](https://github.com/google-gemini/gemini-cli/pull/19547) -- chore: restrict gemini-automted-issue-triage to only allow echo by @galz10 in - [#20047](https://github.com/google-gemini/gemini-cli/pull/20047) -- Allow ask headers longer than 16 chars by @scidomino in - [#20041](https://github.com/google-gemini/gemini-cli/pull/20041) -- fix(core): prevent state corruption in McpClientManager during collis by @h30s - in [#19782](https://github.com/google-gemini/gemini-cli/pull/19782) -- fix(bundling): copy devtools package to bundle for runtime resolution by - @SandyTao520 in - [#19766](https://github.com/google-gemini/gemini-cli/pull/19766) -- feat(policy): Support MCP Server Wildcards in Policy Engine by @jerop in - [#20024](https://github.com/google-gemini/gemini-cli/pull/20024) -- docs(CONTRIBUTING): update React DevTools version to 6 by @mmgok in - [#20014](https://github.com/google-gemini/gemini-cli/pull/20014) -- feat(core): optimize tool descriptions and schemas for Gemini 3 by - @aishaneeshah in - [#19643](https://github.com/google-gemini/gemini-cli/pull/19643) -- feat(core): implement experimental direct web fetch by @mbleigh in - [#19557](https://github.com/google-gemini/gemini-cli/pull/19557) -- feat(core): replace expected_replacements with allow_multiple in replace tool - by @SandyTao520 in - [#20033](https://github.com/google-gemini/gemini-cli/pull/20033) -- fix(sandbox): harden image packaging integrity checks by @aviralgarg05 in - [#19552](https://github.com/google-gemini/gemini-cli/pull/19552) -- fix(core): allow environment variable expansion and explicit overrides for MCP - servers by @galz10 in - [#18837](https://github.com/google-gemini/gemini-cli/pull/18837) -- feat(policy): Implement Tool Annotation Matching in Policy Engine by @jerop in - [#20029](https://github.com/google-gemini/gemini-cli/pull/20029) -- fix(core): prevent utility calls from changing session active model by - @adamfweidman in - [#20035](https://github.com/google-gemini/gemini-cli/pull/20035) -- fix(cli): skip workspace policy loading when in home directory by - @Abhijit-2592 in - [#20054](https://github.com/google-gemini/gemini-cli/pull/20054) -- fix(scripts): Add Windows (win32/x64) support to lint.js by @ZafeerMahmood in - [#16193](https://github.com/google-gemini/gemini-cli/pull/16193) -- fix(a2a-server): Remove unsafe type assertions in agent by @Nixxx19 in - [#19723](https://github.com/google-gemini/gemini-cli/pull/19723) -- Fix: Handle corrupted token file gracefully when switching auth types (#19845) - by @Nixxx19 in - [#19850](https://github.com/google-gemini/gemini-cli/pull/19850) -- fix critical dep vulnerability by @scidomino in - [#20087](https://github.com/google-gemini/gemini-cli/pull/20087) -- Add new setting to configure maxRetries by @kevinjwang1 in - [#20064](https://github.com/google-gemini/gemini-cli/pull/20064) -- Stabilize tests. by @gundermanc in - [#20095](https://github.com/google-gemini/gemini-cli/pull/20095) -- make windows tests mandatory by @scidomino in - [#20096](https://github.com/google-gemini/gemini-cli/pull/20096) -- Add 3.1 pro preview to behavioral evals. by @gundermanc in - [#20088](https://github.com/google-gemini/gemini-cli/pull/20088) -- feat:PR-rate-limit by @JagjeevanAK in - [#19804](https://github.com/google-gemini/gemini-cli/pull/19804) -- feat(cli): allow expanding full details of MCP tool on approval by @y-okt in - [#19916](https://github.com/google-gemini/gemini-cli/pull/19916) -- feat(security): Introduce Conseca framework by @shrishabh in - [#13193](https://github.com/google-gemini/gemini-cli/pull/13193) -- fix(cli): Remove unsafe type assertions in activityLogger #19713 by @Nixxx19 - in [#19745](https://github.com/google-gemini/gemini-cli/pull/19745) -- feat: implement AfterTool tail tool calls by @googlestrobe in - [#18486](https://github.com/google-gemini/gemini-cli/pull/18486) -- ci(actions): fix PR rate limiter excluding maintainers by @scidomino in - [#20117](https://github.com/google-gemini/gemini-cli/pull/20117) -- Shortcuts: Move SectionHeader title below top line and refine styling by - @keithguerin in - [#18721](https://github.com/google-gemini/gemini-cli/pull/18721) -- refactor(ui): Update and simplify use of gray colors in themes by @keithguerin - in [#20141](https://github.com/google-gemini/gemini-cli/pull/20141) -- fix punycode2 by @jacob314 in - [#20154](https://github.com/google-gemini/gemini-cli/pull/20154) -- feat(ide): add GEMINI_CLI_IDE_PID env var to override IDE process detection by - @kiryltech in [#15842](https://github.com/google-gemini/gemini-cli/pull/15842) -- feat(policy): Propagate Tool Annotations for MCP Servers by @jerop in - [#20083](https://github.com/google-gemini/gemini-cli/pull/20083) -- fix(a2a-server): pass allowedTools settings to core Config by @reyyanxahmed in - [#19680](https://github.com/google-gemini/gemini-cli/pull/19680) -- feat(mcp): add progress bar, throttling, and input validation for MCP tool - progress by @jasmeetsb in - [#19772](https://github.com/google-gemini/gemini-cli/pull/19772) -- feat(policy): centralize plan mode tool visibility in policy engine by @jerop - in [#20178](https://github.com/google-gemini/gemini-cli/pull/20178) -- feat(browser): implement experimental browser agent by @gsquared94 in - [#19284](https://github.com/google-gemini/gemini-cli/pull/19284) -- feat(plan): summarize work after executing a plan by @jerop in - [#19432](https://github.com/google-gemini/gemini-cli/pull/19432) -- fix(core): create new McpClient on restart to apply updated config by @h30s in - [#20126](https://github.com/google-gemini/gemini-cli/pull/20126) -- Changelog for v0.30.0-preview.5 by @gemini-cli-robot in - [#20107](https://github.com/google-gemini/gemini-cli/pull/20107) -- Update packages. by @jacob314 in - [#20152](https://github.com/google-gemini/gemini-cli/pull/20152) -- Fix extension env dir loading issue by @chrstnb in - [#20198](https://github.com/google-gemini/gemini-cli/pull/20198) -- restrict /assign to help-wanted issues by @scidomino in - [#20207](https://github.com/google-gemini/gemini-cli/pull/20207) -- feat(plan): inject message when user manually exits Plan mode by @jerop in - [#20203](https://github.com/google-gemini/gemini-cli/pull/20203) -- feat(extensions): enforce folder trust for local extension install by @galz10 - in [#19703](https://github.com/google-gemini/gemini-cli/pull/19703) -- feat(hooks): adds support for RuntimeHook functions. by @mbleigh in - [#19598](https://github.com/google-gemini/gemini-cli/pull/19598) -- Docs: Update UI links. by @jkcinouye in - [#20224](https://github.com/google-gemini/gemini-cli/pull/20224) -- feat: prompt users to run /terminal-setup with yes/no by @ishaanxgupta in - [#16235](https://github.com/google-gemini/gemini-cli/pull/16235) -- fix: additional high vulnerabilities (minimatch, cross-spawn) by @adamfweidman - in [#20221](https://github.com/google-gemini/gemini-cli/pull/20221) -- feat(telemetry): Add context breakdown to API response event by @SandyTao520 - in [#19699](https://github.com/google-gemini/gemini-cli/pull/19699) -- Docs: Add nested sub-folders for related topics by @g-samroberts in - [#20235](https://github.com/google-gemini/gemini-cli/pull/20235) -- feat(plan): support automatic model switching for Plan Mode by @jerop in - [#20240](https://github.com/google-gemini/gemini-cli/pull/20240) -- fix(patch): cherry-pick 58df1c6 to release/v0.31.0-preview.0-pr-20374 to patch - version v0.31.0-preview.0 and create version 0.31.0-preview.1 by - @gemini-cli-robot in - [#20568](https://github.com/google-gemini/gemini-cli/pull/20568) -- fix(patch): cherry-pick ea48bd9 to release/v0.31.0-preview.1-pr-20577 - [CONFLICTS] by @gemini-cli-robot in - [#20592](https://github.com/google-gemini/gemini-cli/pull/20592) -- fix(patch): cherry-pick 32e777f to release/v0.31.0-preview.2-pr-20531 to patch - version v0.31.0-preview.2 and create version 0.31.0-preview.3 by - @gemini-cli-robot in - [#20607](https://github.com/google-gemini/gemini-cli/pull/20607) + [#20232](https://github.com/google-gemini/gemini-cli/pull/20232) +- docs: fix spelling typos in installation guide by @campox747 in + [#20579](https://github.com/google-gemini/gemini-cli/pull/20579) +- Promote stable tests to CI blocking. by @gundermanc in + [#20581](https://github.com/google-gemini/gemini-cli/pull/20581) +- feat(core): enable contiguous parallel admission for Kind.Agent tools by + @abhipatel12 in + [#20583](https://github.com/google-gemini/gemini-cli/pull/20583) +- Enforce import/no-duplicates as error by @Nixxx19 in + [#19797](https://github.com/google-gemini/gemini-cli/pull/19797) +- fix: merge duplicate imports in sdk and test-utils packages (1/4) by @Nixxx19 + in [#19777](https://github.com/google-gemini/gemini-cli/pull/19777) +- fix: merge duplicate imports in a2a-server package (2/4) by @Nixxx19 in + [#19781](https://github.com/google-gemini/gemini-cli/pull/19781) **Full Changelog**: -https://github.com/google-gemini/gemini-cli/compare/v0.30.1...v0.31.0 +https://github.com/google-gemini/gemini-cli/compare/v0.31.0...v0.32.1 diff --git a/docs/changelogs/preview.md b/docs/changelogs/preview.md index b08f4fa1b0..cc5c559365 100644 --- a/docs/changelogs/preview.md +++ b/docs/changelogs/preview.md @@ -1,6 +1,6 @@ -# Preview release: v0.32.0-preview.0 +# Preview release: v0.33.0-preview.4 -Released: February 27, 2026 +Released: March 06, 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). @@ -13,196 +13,189 @@ npm install -g @google/gemini-cli@preview ## Highlights -- **Plan Mode Enhancements**: Significant updates to Plan Mode, including - support for modifying plans in external editors, adaptive workflows based on - task complexity, and new integration tests. -- **Agent and Core Engine Updates**: Enabled the generalist agent, introduced - `Kind.Agent` for sub-agent classification, implemented task tracking - foundation, and improved Agent-to-Agent (A2A) streaming and content - extraction. -- **CLI & User Experience**: Introduced interactive shell autocompletion, added - a new verbosity mode for cleaner error reporting, enabled parallel loading of - extensions, and improved UI hints and shortcut handling. -- **Billing and Security**: Implemented G1 AI credits overage flow with enhanced - billing telemetry, updated the authentication handshake to specification, and - added support for a policy engine in extensions. -- **Stability and Bug Fixes**: Addressed numerous issues including 100% CPU - consumption by orphaned processes, enhanced retry logic for Code Assist, - reduced intrusive MCP errors, and merged duplicate imports across packages. +- **Plan Mode Enhancements**: Added support for annotating plans with feedback + for iteration, enabling built-in research subagents in plan mode, and a new + `copy` subcommand. +- **Agent and Skill Improvements**: Introduced the new `github-issue-creator` + skill, implemented HTTP authentication support for A2A remote agents, and + added support for authenticated A2A agent card discovery. +- **CLI UX/UI Updates**: Redesigned the header to be compact with an ASCII icon, + inverted the context window display to show usage, and directly indicate auth + required state for agents. +- **Core and ACP Enhancements**: Implemented slash command handling in ACP (for + `/memory`, `/init`, `/extensions`, and `/restore`), added a set models + interface to ACP, and centralized `read_file` limits while truncating large + MCP tool output. ## What's Changed -- feat(plan): add integration tests for plan mode by @Adib234 in - [#20214](https://github.com/google-gemini/gemini-cli/pull/20214) -- fix(acp): update auth handshake to spec by @skeshive in - [#19725](https://github.com/google-gemini/gemini-cli/pull/19725) -- feat(core): implement robust A2A streaming reassembly and fix task continuity - by @adamfweidman in - [#20091](https://github.com/google-gemini/gemini-cli/pull/20091) -- feat(cli): load extensions in parallel by @scidomino in - [#20229](https://github.com/google-gemini/gemini-cli/pull/20229) -- Plumb the maxAttempts setting through Config args by @kevinjwang1 in - [#20239](https://github.com/google-gemini/gemini-cli/pull/20239) -- fix(cli): skip 404 errors in setup-github file downloads by @h30s in - [#20287](https://github.com/google-gemini/gemini-cli/pull/20287) -- fix(cli): expose model.name setting in settings dialog for persistence by - @achaljhawar in - [#19605](https://github.com/google-gemini/gemini-cli/pull/19605) -- docs: remove legacy cmd examples in favor of powershell by @scidomino in - [#20323](https://github.com/google-gemini/gemini-cli/pull/20323) -- feat(core): Enable model steering in workspace. by @joshualitt in - [#20343](https://github.com/google-gemini/gemini-cli/pull/20343) -- fix: remove trailing comma in issue triage workflow settings json by @Nixxx19 - in [#20265](https://github.com/google-gemini/gemini-cli/pull/20265) -- feat(core): implement task tracker foundation and service by @anj-s in - [#19464](https://github.com/google-gemini/gemini-cli/pull/19464) -- test: support tests that include color information by @jacob314 in - [#20220](https://github.com/google-gemini/gemini-cli/pull/20220) -- feat(core): introduce Kind.Agent for sub-agent classification by @abhipatel12 - in [#20369](https://github.com/google-gemini/gemini-cli/pull/20369) -- Changelog for v0.30.0 by @gemini-cli-robot in - [#20252](https://github.com/google-gemini/gemini-cli/pull/20252) -- Update changelog workflow to reject nightly builds by @g-samroberts in - [#20248](https://github.com/google-gemini/gemini-cli/pull/20248) -- Changelog for v0.31.0-preview.0 by @gemini-cli-robot in - [#20249](https://github.com/google-gemini/gemini-cli/pull/20249) -- feat(cli): hide workspace policy update dialog and auto-accept by default by - @Abhijit-2592 in - [#20351](https://github.com/google-gemini/gemini-cli/pull/20351) -- feat(core): rename grep_search include parameter to include_pattern by +- 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 + [#20084](https://github.com/google-gemini/gemini-cli/pull/20084) +- 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 + @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 + [#20626](https://github.com/google-gemini/gemini-cli/pull/20626) +- 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 + [#20641](https://github.com/google-gemini/gemini-cli/pull/20641) +- 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 + [#20634](https://github.com/google-gemini/gemini-cli/pull/20634) +- 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 + [#20627](https://github.com/google-gemini/gemini-cli/pull/20627) +- 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 + @NTaylorMullen in + [#20598](https://github.com/google-gemini/gemini-cli/pull/20598) +- 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 + mismatches by @sehoon38 in + [#20706](https://github.com/google-gemini/gemini-cli/pull/20706) +- 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 + 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 + [#20850](https://github.com/google-gemini/gemini-cli/pull/20850) +- 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 + [#20477](https://github.com/google-gemini/gemini-cli/pull/20477) +- 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 @SandyTao520 in - [#20328](https://github.com/google-gemini/gemini-cli/pull/20328) -- feat(plan): support opening and modifying plan in external editor by @Adib234 - in [#20348](https://github.com/google-gemini/gemini-cli/pull/20348) -- feat(cli): implement interactive shell autocompletion by @mrpmohiburrahman in - [#20082](https://github.com/google-gemini/gemini-cli/pull/20082) -- fix(core): allow /memory add to work in plan mode by @Jefftree in - [#20353](https://github.com/google-gemini/gemini-cli/pull/20353) -- feat(core): add HTTP 499 to retryable errors and map to RetryableQuotaError by - @bdmorgan in [#20432](https://github.com/google-gemini/gemini-cli/pull/20432) -- feat(core): Enable generalist agent by @joshualitt in - [#19665](https://github.com/google-gemini/gemini-cli/pull/19665) -- Updated tests in TableRenderer.test.tsx to use SVG snapshots by @devr0306 in - [#20450](https://github.com/google-gemini/gemini-cli/pull/20450) -- Refactor Github Action per b/485167538 by @google-admin in - [#19443](https://github.com/google-gemini/gemini-cli/pull/19443) -- fix(github): resolve actionlint and yamllint regressions from #19443 by @jerop - in [#20467](https://github.com/google-gemini/gemini-cli/pull/20467) -- fix: action var usage by @galz10 in - [#20492](https://github.com/google-gemini/gemini-cli/pull/20492) -- feat(core): improve A2A content extraction by @adamfweidman in - [#20487](https://github.com/google-gemini/gemini-cli/pull/20487) -- fix(cli): support quota error fallbacks for all authentication types by - @sehoon38 in [#20475](https://github.com/google-gemini/gemini-cli/pull/20475) -- fix(core): flush transcript for pure tool-call responses to ensure BeforeTool - hooks see complete state by @krishdef7 in - [#20419](https://github.com/google-gemini/gemini-cli/pull/20419) -- feat(plan): adapt planning workflow based on complexity of task by @jerop in - [#20465](https://github.com/google-gemini/gemini-cli/pull/20465) -- fix: prevent orphaned processes from consuming 100% CPU when terminal closes - by @yuvrajangadsingh in - [#16965](https://github.com/google-gemini/gemini-cli/pull/16965) -- feat(core): increase fetch timeout and fix [object Object] error - stringification by @bdmorgan in - [#20441](https://github.com/google-gemini/gemini-cli/pull/20441) -- [Gemma x Gemini CLI] Add an Experimental Gemma Router that uses a LiteRT-LM - shim into the Composite Model Classifier Strategy by @sidwan02 in - [#17231](https://github.com/google-gemini/gemini-cli/pull/17231) -- docs(plan): update documentation regarding supporting editing of plan files - during plan approval by @Adib234 in - [#20452](https://github.com/google-gemini/gemini-cli/pull/20452) -- test(cli): fix flaky ToolResultDisplay overflow test by @jwhelangoog in - [#20518](https://github.com/google-gemini/gemini-cli/pull/20518) -- ui(cli): reduce length of Ctrl+O hint by @jwhelangoog in - [#20490](https://github.com/google-gemini/gemini-cli/pull/20490) -- fix(ui): correct styled table width calculations by @devr0306 in - [#20042](https://github.com/google-gemini/gemini-cli/pull/20042) -- Avoid overaggressive unescaping by @scidomino in - [#20520](https://github.com/google-gemini/gemini-cli/pull/20520) -- feat(telemetry) Instrument traces with more attributes and make them available - to OTEL users by @heaventourist in - [#20237](https://github.com/google-gemini/gemini-cli/pull/20237) -- Add support for policy engine in extensions by @chrstnb in - [#20049](https://github.com/google-gemini/gemini-cli/pull/20049) -- Docs: Update to Terms of Service & FAQ by @jkcinouye in - [#20488](https://github.com/google-gemini/gemini-cli/pull/20488) -- Fix bottom border rendering for search and add a regression test. by @jacob314 - in [#20517](https://github.com/google-gemini/gemini-cli/pull/20517) -- fix(core): apply retry logic to CodeAssistServer for all users by @bdmorgan in - [#20507](https://github.com/google-gemini/gemini-cli/pull/20507) -- Fix extension MCP server env var loading by @chrstnb in - [#20374](https://github.com/google-gemini/gemini-cli/pull/20374) -- feat(ui): add 'ctrl+o' hint to truncated content message by @jerop in - [#20529](https://github.com/google-gemini/gemini-cli/pull/20529) -- Fix flicker showing message to press ctrl-O again to collapse. by @jacob314 in - [#20414](https://github.com/google-gemini/gemini-cli/pull/20414) -- fix(cli): hide shortcuts hint while model is thinking or the user has typed a - prompt + add debounce to avoid flicker by @jacob314 in - [#19389](https://github.com/google-gemini/gemini-cli/pull/19389) -- feat(plan): update planning workflow to encourage multi-select with - descriptions of options by @Adib234 in - [#20491](https://github.com/google-gemini/gemini-cli/pull/20491) -- refactor(core,cli): useAlternateBuffer read from config by @psinha40898 in - [#20346](https://github.com/google-gemini/gemini-cli/pull/20346) -- fix(cli): ensure dialogs stay scrolled to bottom in alternate buffer mode by - @jacob314 in [#20527](https://github.com/google-gemini/gemini-cli/pull/20527) -- fix(core): revert auto-save of policies to user space by @Abhijit-2592 in - [#20531](https://github.com/google-gemini/gemini-cli/pull/20531) -- Demote unreliable test. by @gundermanc in - [#20571](https://github.com/google-gemini/gemini-cli/pull/20571) -- fix(core): handle optional response fields from code assist API by @sehoon38 - in [#20345](https://github.com/google-gemini/gemini-cli/pull/20345) -- fix(cli): keep thought summary when loading phrases are off by @LyalinDotCom - in [#20497](https://github.com/google-gemini/gemini-cli/pull/20497) -- feat(cli): add temporary flag to disable workspace policies by @Abhijit-2592 - in [#20523](https://github.com/google-gemini/gemini-cli/pull/20523) -- Disable expensive and scheduled workflows on personal forks by @dewitt in - [#20449](https://github.com/google-gemini/gemini-cli/pull/20449) -- Moved markdown parsing logic to a separate util file by @devr0306 in - [#20526](https://github.com/google-gemini/gemini-cli/pull/20526) -- fix(plan): prevent agent from using ask_user for shell command confirmation by - @Adib234 in [#20504](https://github.com/google-gemini/gemini-cli/pull/20504) -- fix(core): disable retries for code assist streaming requests by @sehoon38 in - [#20561](https://github.com/google-gemini/gemini-cli/pull/20561) -- feat(billing): implement G1 AI credits overage flow with billing telemetry by - @gsquared94 in - [#18590](https://github.com/google-gemini/gemini-cli/pull/18590) -- feat: better error messages by @gsquared94 in - [#20577](https://github.com/google-gemini/gemini-cli/pull/20577) -- fix(ui): persist expansion in AskUser dialog when navigating options by @jerop - in [#20559](https://github.com/google-gemini/gemini-cli/pull/20559) -- fix(cli): prevent sub-agent tool calls from leaking into UI by @abhipatel12 in - [#20580](https://github.com/google-gemini/gemini-cli/pull/20580) -- fix(cli): Shell autocomplete polish by @jacob314 in - [#20411](https://github.com/google-gemini/gemini-cli/pull/20411) -- Changelog for v0.31.0-preview.1 by @gemini-cli-robot in - [#20590](https://github.com/google-gemini/gemini-cli/pull/20590) -- Add slash command for promoting behavioral evals to CI blocking by @gundermanc - in [#20575](https://github.com/google-gemini/gemini-cli/pull/20575) -- Changelog for v0.30.1 by @gemini-cli-robot in - [#20589](https://github.com/google-gemini/gemini-cli/pull/20589) -- Add low/full CLI error verbosity mode for cleaner UI by @LyalinDotCom in - [#20399](https://github.com/google-gemini/gemini-cli/pull/20399) -- Disable Gemini PR reviews on draft PRs. by @gundermanc in - [#20362](https://github.com/google-gemini/gemini-cli/pull/20362) -- Docs: FAQ update by @jkcinouye in - [#20585](https://github.com/google-gemini/gemini-cli/pull/20585) -- fix(core): reduce intrusive MCP errors and deduplicate diagnostics by - @spencer426 in - [#20232](https://github.com/google-gemini/gemini-cli/pull/20232) -- docs: fix spelling typos in installation guide by @campox747 in - [#20579](https://github.com/google-gemini/gemini-cli/pull/20579) -- Promote stable tests to CI blocking. by @gundermanc in - [#20581](https://github.com/google-gemini/gemini-cli/pull/20581) -- feat(core): enable contiguous parallel admission for Kind.Agent tools by - @abhipatel12 in - [#20583](https://github.com/google-gemini/gemini-cli/pull/20583) -- Enforce import/no-duplicates as error by @Nixxx19 in - [#19797](https://github.com/google-gemini/gemini-cli/pull/19797) -- fix: merge duplicate imports in sdk and test-utils packages (1/4) by @Nixxx19 - in [#19777](https://github.com/google-gemini/gemini-cli/pull/19777) -- fix: merge duplicate imports in a2a-server package (2/4) by @Nixxx19 in - [#19781](https://github.com/google-gemini/gemini-cli/pull/19781) + [#20510](https://github.com/google-gemini/gemini-cli/pull/20510) +- 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 + [#20870](https://github.com/google-gemini/gemini-cli/pull/20870) +- 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 + [#20358](https://github.com/google-gemini/gemini-cli/pull/20358) +- 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 + [#19365](https://github.com/google-gemini/gemini-cli/pull/19365) +- 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 + [#17930](https://github.com/google-gemini/gemini-cli/pull/17930) +- 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 + [#20801](https://github.com/google-gemini/gemini-cli/pull/20801) +- 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 + 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 + @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 + in [#19281](https://github.com/google-gemini/gemini-cli/pull/19281) +- 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 + 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 + [#20890](https://github.com/google-gemini/gemini-cli/pull/20890) +- 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 + in [#20876](https://github.com/google-gemini/gemini-cli/pull/20876) +- 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 + [#19477](https://github.com/google-gemini/gemini-cli/pull/19477) +- 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 + [#20898](https://github.com/google-gemini/gemini-cli/pull/20898) +- Build binary by @aswinashok44 in + [#18933](https://github.com/google-gemini/gemini-cli/pull/18933) +- 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 + [#20919](https://github.com/google-gemini/gemini-cli/pull/20919) +- 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 + [#20914](https://github.com/google-gemini/gemini-cli/pull/20914) +- 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 + @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 + [#20972](https://github.com/google-gemini/gemini-cli/pull/20972) +- 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 + [#20904](https://github.com/google-gemini/gemini-cli/pull/20904) +- 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 + [#20620](https://github.com/google-gemini/gemini-cli/pull/20620) +- 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 + [#20917](https://github.com/google-gemini/gemini-cli/pull/20917) +- 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 + `/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 + [#20961](https://github.com/google-gemini/gemini-cli/pull/20961) +- 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 + in [#20987](https://github.com/google-gemini/gemini-cli/pull/20987) +- 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 + [#20501](https://github.com/google-gemini/gemini-cli/pull/20501) +- 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 + [#20991](https://github.com/google-gemini/gemini-cli/pull/20991) **Full Changelog**: -https://github.com/google-gemini/gemini-cli/compare/v0.31.0-preview.3...v0.32.0-preview.0 +https://github.com/google-gemini/gemini-cli/compare/v0.32.0-preview.0...v0.33.0-preview.4 diff --git a/docs/cli/cli-reference.md b/docs/cli/cli-reference.md index c1599df69e..6cafb7dd52 100644 --- a/docs/cli/cli-reference.md +++ b/docs/cli/cli-reference.md @@ -24,6 +24,21 @@ 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 | diff --git a/docs/cli/enterprise.md b/docs/cli/enterprise.md index 44d8ba9467..39c0f7c5c1 100644 --- a/docs/cli/enterprise.md +++ b/docs/cli/enterprise.md @@ -244,7 +244,7 @@ gemini You can significantly enhance security by controlling which tools the Gemini model can use. This is achieved through the `tools.core` setting and the [Policy Engine](../reference/policy-engine.md). For a list of available tools, -see the [Tools documentation](../tools/index.md). +see the [Tools reference](../reference/tools.md). ### Allowlisting with `coreTools` @@ -308,8 +308,8 @@ unintended tool execution. ## Managing custom tools (MCP servers) If your organization uses custom tools via -[Model-Context Protocol (MCP) servers](../reference/tools-api.md), it is crucial -to understand how server configurations are managed to apply security policies +[Model-Context Protocol (MCP) servers](../tools/mcp-server.md), it is crucial to +understand how server configurations are managed to apply security policies effectively. ### How MCP server configurations are merged diff --git a/docs/cli/gemini-md.md b/docs/cli/gemini-md.md index 95f46ae095..624b2fc566 100644 --- a/docs/cli/gemini-md.md +++ b/docs/cli/gemini-md.md @@ -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 refresh`**: Forces a re-scan and reload of all `GEMINI.md` files +- **`/memory reload`**: Forces a re-scan and reload of all `GEMINI.md` files from all configured locations. - **`/memory add `**: Appends your text to your global `~/.gemini/GEMINI.md` file. This lets you add persistent memories on the fly. diff --git a/docs/cli/notifications.md b/docs/cli/notifications.md new file mode 100644 index 0000000000..8326a1efb2 --- /dev/null +++ b/docs/cli/notifications.md @@ -0,0 +1,58 @@ +# 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). diff --git a/docs/cli/plan-mode.md b/docs/cli/plan-mode.md index a8511d9c42..41f8ededcd 100644 --- a/docs/cli/plan-mode.md +++ b/docs/cli/plan-mode.md @@ -1,7 +1,7 @@ # Plan Mode (experimental) Plan Mode is a read-only environment for architecting robust solutions before -implementation. It allows you to: +implementation. With Plan Mode, you can: - **Research:** Explore the project in a read-only state to prevent accidental changes. @@ -12,62 +12,48 @@ implementation. It allows you to: > feedback is invaluable as we refine this feature. If you have ideas, > suggestions, or encounter issues: > -> - [Open an issue](https://github.com/google-gemini/gemini-cli/issues) on -> GitHub. +> - [Open an issue] on GitHub. > - Use the **/bug** command within Gemini CLI to file an issue. -- [Enabling Plan Mode](#enabling-plan-mode) -- [How to use Plan Mode](#how-to-use-plan-mode) - - [Entering Plan Mode](#entering-plan-mode) - - [Planning Workflow](#planning-workflow) - - [Exiting Plan Mode](#exiting-plan-mode) -- [Tool Restrictions](#tool-restrictions) - - [Customizing Planning with Skills](#customizing-planning-with-skills) - - [Customizing Policies](#customizing-policies) - - [Example: Allow git commands in Plan Mode](#example-allow-git-commands-in-plan-mode) - - [Example: Enable custom subagents in Plan Mode](#example-enable-custom-subagents-in-plan-mode) - - [Custom Plan Directory and Policies](#custom-plan-directory-and-policies) -- [Automatic Model Routing](#automatic-model-routing) -- [Cleanup](#cleanup) +## How to enable Plan Mode -## Enabling Plan Mode +Enable Plan Mode in **Settings** or by editing your configuration file. -To use Plan Mode, enable it via **/settings** (search for **Plan**) or add the -following to your `settings.json`: - -```json -{ - "experimental": { - "plan": true - } -} -``` - -## How to use Plan Mode - -### Entering Plan Mode - -You can configure Gemini CLI to start in Plan Mode by default or enter it -manually during a session. - -- **Configuration:** Configure Gemini CLI to start directly in Plan Mode by - default: - 1. Type `/settings` in the CLI. - 2. Search for **Default Approval Mode**. - 3. Set the value to **Plan**. - - Alternatively, use the `gemini --approval-mode=plan` CLI flag or manually - update: +- **Settings:** Use the `/settings` command and set **Plan** to `true`. +- **Configuration:** Add the following to your `settings.json`: ```json { - "general": { - "defaultApprovalMode": "plan" + "experimental": { + "plan": true } } ``` -- **Keyboard Shortcut:** Press `Shift+Tab` to cycle through approval modes +## How to enter Plan Mode + +Plan Mode integrates seamlessly into your workflow, letting you switch between +planning and execution as needed. + +You can either configure Gemini CLI to start in Plan Mode by default or enter +Plan Mode manually during a session. + +### Launch in Plan Mode + +To start Gemini CLI directly in Plan Mode by default: + +1. Use the `/settings` command. +2. Set **Default Approval Mode** to `Plan`. + +To launch Gemini CLI in Plan Mode once: + +1. Use `gemini --approval-mode=plan` when launching Gemini CLI. + +### Enter Plan Mode manually + +To start Plan Mode while using Gemini CLI: + +- **Keyboard shortcut:** Press `Shift+Tab` to cycle through approval modes (`Default` -> `Auto-Edit` -> `Plan`). > **Note:** Plan Mode is automatically removed from the rotation when Gemini @@ -75,56 +61,54 @@ manually during a session. - **Command:** Type `/plan` in the input box. -- **Natural Language:** Ask Gemini CLI to "start a plan for...". Gemini CLI then +- **Natural Language:** Ask Gemini CLI to "start a plan for...". Gemini CLI calls the [`enter_plan_mode`] tool to switch modes. > **Note:** This tool is not available when Gemini CLI is in [YOLO mode]. -### Planning Workflow +## How to use Plan Mode -Plan Mode uses an adaptive planning workflow where the research depth, plan -structure, and consultation level are proportional to the task's complexity: +Plan Mode lets you collaborate with Gemini CLI to design a solution before +Gemini CLI takes action. -1. **Explore & Analyze:** Analyze requirements and use read-only tools to map - affected modules and identify dependencies. -2. **Consult:** The depth of consultation is proportional to the task's - complexity: - - **Simple Tasks:** Proceed directly to drafting. - - **Standard Tasks:** Present a summary of viable approaches via - [`ask_user`] for selection. - - **Complex Tasks:** Present detailed trade-offs for at least two viable - approaches via [`ask_user`] and obtain approval before drafting. -3. **Draft:** Write a detailed implementation plan to the - [plans directory](#custom-plan-directory-and-policies). The plan's structure - adapts to the task: - - **Simple Tasks:** Focused on specific **Changes** and **Verification** - steps. - - **Standard Tasks:** Includes an **Objective**, **Key Files & Context**, - **Implementation Steps**, and **Verification & Testing**. - - **Complex Tasks:** Comprehensive plans including **Background & - Motivation**, **Scope & Impact**, **Proposed Solution**, **Alternatives - Considered**, a phased **Implementation Plan**, **Verification**, and - **Migration & Rollback** strategies. -4. **Review & Approval:** Use the [`exit_plan_mode`] tool to present the plan - and formally request approval. - - **Approve:** Exit Plan Mode and start implementation. - - **Iterate:** Provide feedback to refine the plan. - - **Refine manually:** Press **Ctrl + X** to open the plan file in your - [preferred external editor]. This allows you to manually refine the plan - steps before approval. If you make any changes and save the file, the CLI - will automatically send the updated plan back to the agent for review and - iteration. +1. **Provide a goal:** Start by describing what you want to achieve. Gemini CLI + will then enter Plan Mode (if it's not already) to research the task. +2. **Review research and provide input:** As Gemini CLI analyzes your codebase, + it may ask you questions or present different implementation options using + [`ask_user`]. Provide your preferences to help guide the design. +3. **Review the plan:** Once Gemini CLI has a proposed strategy, it creates a + detailed implementation plan as a Markdown file in your plans directory. You + can open and read this file to understand the proposed changes. +4. **Approve or iterate:** Gemini CLI will present the finalized plan for your + approval. + - **Approve:** If you're satisfied with the plan, approve it to start the + implementation immediately: **Yes, automatically accept edits** or **Yes, + manually accept edits**. + - **Iterate:** If the plan needs adjustments, provide feedback. Gemini CLI + will refine the strategy and update the plan. + - **Cancel:** You can cancel your plan with `Esc`. For more complex or specialized planning tasks, you can -[customize the planning workflow with skills](#customizing-planning-with-skills). +[customize the planning workflow with skills](#custom-planning-with-skills). -### Exiting Plan Mode +## How to exit Plan Mode -To exit Plan Mode, you can: +You can exit Plan Mode at any time, whether you have finalized a plan or want to +switch back to another mode. -- **Keyboard Shortcut:** Press `Shift+Tab` to cycle to the desired mode. +- **Approve a plan:** When Gemini CLI presents a finalized plan, approving it + automatically exits Plan Mode and starts the implementation. +- **Keyboard shortcut:** Press `Shift+Tab` to cycle to the desired mode. +- **Natural language:** Ask Gemini CLI to "exit plan mode" or "stop planning." -- **Tool:** Gemini CLI calls the [`exit_plan_mode`] tool to present the - finalized plan for your approval. +## Customization and best practices + +Plan Mode is secure by default, but you can adapt it to fit your specific +workflows. You can customize how Gemini CLI plans by using skills, adjusting +safety policies, or changing where plans are stored. + +## Commands + +- **`/plan copy`**: Copy the currently approved plan to your clipboard. ## Tool Restrictions @@ -136,7 +120,7 @@ These are the only allowed tools: - **Search:** [`grep_search`], [`google_web_search`] - **Research Subagents:** [`codebase_investigator`], [`cli_help`] - **Interaction:** [`ask_user`] -- **MCP Tools (Read):** Read-only [MCP tools] (e.g., `github_read_issue`, +- **MCP tools (Read):** Read-only [MCP tools] (for example, `github_read_issue`, `postgres_read_schema`) are allowed. - **Planning (Write):** [`write_file`] and [`replace`] only allowed for `.md` files in the `~/.gemini/tmp///plans/` directory or your @@ -145,12 +129,12 @@ These are the only allowed tools: - **Skills:** [`activate_skill`] (allows loading specialized instructions and resources in a read-only manner) -### Customizing Planning with Skills +### Custom planning with skills -You can use [Agent Skills](./skills.md) to customize how Gemini CLI approaches -planning for specific types of tasks. When a skill is activated during Plan -Mode, its specialized instructions and procedural workflows will guide the -research, design and planning phases. +You can use [Agent Skills] to customize how Gemini CLI approaches planning for +specific types of tasks. When a skill is activated during Plan Mode, its +specialized instructions and procedural workflows will guide the research, +design, and planning phases. For example: @@ -165,7 +149,7 @@ To use a skill in Plan Mode, you can explicitly ask Gemini CLI to "use the `` skill to plan..." or Gemini CLI may autonomously activate it based on the task description. -### Customizing Policies +### Custom policies Plan Mode's default tool restrictions are managed by the [policy engine] and defined in the built-in [`plan.toml`] file. The built-in policy (Tier 1) @@ -189,10 +173,13 @@ priority = 100 modes = ["plan"] ``` +For more information on how the policy engine works, see the [policy engine] +docs. + #### Example: Allow git commands in Plan Mode -This rule allows you to check the repository status and see changes while in -Plan Mode. +This rule lets you check the repository status and see changes while in Plan +Mode. `~/.gemini/policies/git-research.toml` @@ -224,10 +211,7 @@ modes = ["plan"] Tell Gemini CLI it can use these tools in your prompt, for example: _"You can check ongoing changes in git."_ -For more information on how the policy engine works, see the [policy engine] -docs. - -### Custom Plan Directory and Policies +### Custom plan directory and policies By default, planning artifacts are stored in a managed temporary directory outside your project: `~/.gemini/tmp///plans/`. @@ -267,10 +251,59 @@ modes = ["plan"] argsPattern = "\"file_path\":\"[^\"]+[\\\\/]+\\.gemini[\\\\/]+plans[\\\\/]+[\\w-]+\\.md\"" ``` +## Planning workflows + +Plan Mode provides building blocks for structured research and design. These are +implemented as [extensions] using core planning tools like [`enter_plan_mode`], +[`exit_plan_mode`], and [`ask_user`]. + +### Built-in planning workflow + +The built-in planner uses an adaptive workflow to analyze your project, consult +you on trade-offs via [`ask_user`], and draft a plan for your approval. + +### Custom planning workflows + +You can install or create specialized planners to suit your workflow. + +#### Conductor + +[Conductor] is designed for spec-driven development. It organizes work into +"tracks" and stores persistent artifacts in your project's `conductor/` +directory: + +- **Automate transitions:** Switches to read-only mode via [`enter_plan_mode`]. +- **Streamline decisions:** Uses [`ask_user`] for architectural choices. +- **Maintain project context:** Stores artifacts in the project directory using + [custom plan directory and policies](#custom-plan-directory-and-policies). +- **Handoff execution:** Transitions to implementation via [`exit_plan_mode`]. + +#### Build your own + +Since Plan Mode is built on modular building blocks, you can develop your own +custom planning workflow as an [extensions]. By leveraging core tools and +[custom policies](#custom-policies), you can define how Gemini CLI researches +and stores plans for your specific domain. + +To build a custom planning workflow, you can use: + +- **Tool usage:** Use core tools like [`enter_plan_mode`], [`ask_user`], and + [`exit_plan_mode`] to manage the research and design process. +- **Customization:** Set your own storage locations and policy rules using + [custom plan directories](#custom-plan-directory-and-policies) and + [custom policies](#custom-policies). + +> **Note:** Use [Conductor] as a reference when building your own custom +> planning workflow. + +By using Plan Mode as its execution environment, your custom methodology can +enforce read-only safety during the design phase while benefiting from +high-reasoning model routing. + ## Automatic Model Routing -When using an [**auto model**], Gemini CLI automatically optimizes [**model -routing**] based on the current phase of your task: +When using an [auto model], Gemini CLI automatically optimizes [model routing] +based on the current phase of your task: 1. **Planning Phase:** While in Plan Mode, the CLI routes requests to a high-reasoning **Pro** model to ensure robust architectural decisions and @@ -321,8 +354,8 @@ those files are not automatically deleted and must be managed manually. [MCP tools]: /docs/tools/mcp-server.md [`save_memory`]: /docs/tools/memory.md [`activate_skill`]: /docs/cli/skills.md -[`codebase_investigator`]: /docs/core/subagents.md#codebase_investigator -[`cli_help`]: /docs/core/subagents.md#cli_help +[`codebase_investigator`]: /docs/core/subagents.md#codebase-investigator +[`cli_help`]: /docs/core/subagents.md#cli-help-agent [subagents]: /docs/core/subagents.md [custom subagents]: /docs/core/subagents.md#creating-custom-subagents [policy engine]: /docs/reference/policy-engine.md @@ -332,7 +365,11 @@ those files are not automatically deleted and must be managed manually. [YOLO mode]: /docs/reference/configuration.md#command-line-arguments [`plan.toml`]: https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/policy/policies/plan.toml -[auto model]: /docs/reference/configuration.md#model-settings +[auto model]: /docs/reference/configuration.md#model [model routing]: /docs/cli/telemetry.md#model-routing [preferred external editor]: /docs/reference/configuration.md#general [session retention]: /docs/cli/session-management.md#session-retention +[extensions]: /docs/extensions/ +[Conductor]: https://github.com/gemini-cli-extensions/conductor +[open an issue]: https://github.com/google-gemini/gemini-cli/issues +[Agent Skills]: /docs/cli/skills.md diff --git a/docs/cli/sandbox.md b/docs/cli/sandbox.md index 1d075989af..ec7e88f624 100644 --- a/docs/cli/sandbox.md +++ b/docs/cli/sandbox.md @@ -50,6 +50,74 @@ Cross-platform sandboxing with complete process isolation. **Note**: Requires building the sandbox image locally or using a published image from your organization's registry. +### 3. gVisor / runsc (Linux only) + +Strongest isolation available: runs containers inside a user-space kernel via +[gVisor](https://github.com/google/gvisor). gVisor intercepts all container +system calls and handles them in a sandboxed kernel written in Go, providing a +strong security barrier between AI operations and the host OS. + +**Prerequisites:** + +- Linux (gVisor supports Linux only) +- Docker installed and running +- gVisor/runsc runtime configured + +When you set `sandbox: "runsc"`, Gemini CLI runs +`docker run --runtime=runsc ...` to execute containers with gVisor isolation. +runsc is not auto-detected; you must specify it explicitly (e.g. +`GEMINI_SANDBOX=runsc` or `sandbox: "runsc"`). + +To set up runsc: + +1. Install the runsc binary. +2. Configure the Docker daemon to use the runsc runtime. +3. Verify the installation. + +### 4. LXC/LXD (Linux only, experimental) + +Full-system container sandboxing using LXC/LXD. Unlike Docker/Podman, LXC +containers run a complete Linux system with `systemd`, `snapd`, and other system +services. This is ideal for tools that don't work in standard Docker containers, +such as Snapcraft and Rockcraft. + +**Prerequisites**: + +- Linux only. +- LXC/LXD must be installed (`snap install lxd` or `apt install lxd`). +- A container must be created and running before starting Gemini CLI. Gemini + does **not** create the container automatically. + +**Quick setup**: + +```bash +# Initialize LXD (first time only) +lxd init --auto + +# Create and start an Ubuntu container +lxc launch ubuntu:24.04 gemini-sandbox + +# Enable LXC sandboxing +export GEMINI_SANDBOX=lxc +gemini -p "build the project" +``` + +**Custom container name**: + +```bash +export GEMINI_SANDBOX=lxc +export GEMINI_SANDBOX_IMAGE=my-snapcraft-container +gemini -p "build the snap" +``` + +**Limitations**: + +- Linux only (LXC is not available on macOS or Windows). +- The container must already exist and be running. +- The workspace directory is bind-mounted into the container at the same + absolute path — the path must be writable inside the container. +- Used with tools like Snapcraft or Rockcraft that require a full system. + ## Quickstart ```bash @@ -88,7 +156,8 @@ gemini -p "run the test suite" ### Enable sandboxing (in order of precedence) 1. **Command flag**: `-s` or `--sandbox` -2. **Environment variable**: `GEMINI_SANDBOX=true|docker|podman|sandbox-exec` +2. **Environment variable**: + `GEMINI_SANDBOX=true|docker|podman|sandbox-exec|runsc|lxc` 3. **Settings file**: `"sandbox": true` in the `tools` object of your `settings.json` file (e.g., `{"tools": {"sandbox": true}}`). diff --git a/docs/cli/session-management.md b/docs/cli/session-management.md index 442069bdac..8e60f61630 100644 --- a/docs/cli/session-management.md +++ b/docs/cli/session-management.md @@ -61,6 +61,15 @@ Browser**: /resume ``` +When typing `/resume` (or `/chat`) in slash completion, commands are grouped +under titled separators: + +- `-- auto --` (session browser) + - `list` is selectable and opens the session browser +- `-- checkpoints --` (manual tagged checkpoint commands) + +Unique prefixes such as `/resum` and `/cha` resolve to the same grouped menu. + The Session Browser provides an interactive interface where you can perform the following actions: @@ -72,6 +81,21 @@ following actions: - **Select:** Press **Enter** to resume the selected session. - **Esc:** Press **Esc** to exit the Session Browser. +### Manual chat checkpoints + +For named branch points inside a session, use chat checkpoints: + +```text +/resume save decision-point +/resume list +/resume resume decision-point +``` + +Compatibility aliases: + +- `/chat ...` works for the same commands. +- `/resume checkpoints ...` also remains supported during migration. + ## Managing sessions You can list and delete sessions to keep your history organized and manage disk diff --git a/docs/cli/settings.md b/docs/cli/settings.md index 37508fc04e..182217fc0e 100644 --- a/docs/cli/settings.md +++ b/docs/cli/settings.md @@ -57,7 +57,7 @@ they appear in the UI. | Show Shortcuts Hint | `ui.showShortcutsHint` | Show the "? for shortcuts" hint above the input. | `true` | | Hide Banner | `ui.hideBanner` | Hide the application banner | `false` | | Hide Context Summary | `ui.hideContextSummary` | Hide the context summary (GEMINI.md, MCP servers) above the input. | `false` | -| Hide CWD | `ui.footer.hideCWD` | Hide the current working directory path in the footer. | `false` | +| Hide CWD | `ui.footer.hideCWD` | Hide the current working directory in the footer. | `false` | | Hide Sandbox Status | `ui.footer.hideSandboxStatus` | Hide the sandbox status indicator in the footer. | `false` | | Hide Model Info | `ui.footer.hideModelInfo` | Hide the model name and context usage in the footer. | `false` | | Hide Context Window Percentage | `ui.footer.hideContextPercentage` | Hides the context window usage percentage. | `true` | @@ -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 refresh 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 reload 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,7 +147,6 @@ 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 diff --git a/docs/cli/tutorials/mcp-setup.md b/docs/cli/tutorials/mcp-setup.md index 03b6e56376..8723a65892 100644 --- a/docs/cli/tutorials/mcp-setup.md +++ b/docs/cli/tutorials/mcp-setup.md @@ -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 refresh` to force the CLI to re-query the - server for its capabilities. +- **Tools not found?** Run `/mcp reload` to force the CLI to re-query the server + for its capabilities. ## Next steps diff --git a/docs/cli/tutorials/memory-management.md b/docs/cli/tutorials/memory-management.md index 829fbecbd4..4cbca4bda9 100644 --- a/docs/cli/tutorials/memory-management.md +++ b/docs/cli/tutorials/memory-management.md @@ -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 refresh` +**Command:** `/memory reload` ## Best practices diff --git a/docs/cli/tutorials/session-management.md b/docs/cli/tutorials/session-management.md index 7815aa94d6..6b50358b2c 100644 --- a/docs/cli/tutorials/session-management.md +++ b/docs/cli/tutorials/session-management.md @@ -89,9 +89,9 @@ Gemini gives you granular control over the undo process. You can choose to: Sometimes you want to try two different approaches to the same problem. 1. Start a session and get to a decision point. -2. Save the current state with `/chat save decision-point`. +2. Save the current state with `/resume save decision-point`. 3. Try your first approach. -4. Later, use `/chat resume decision-point` to fork the conversation back to +4. Later, use `/resume resume decision-point` to fork the conversation back to that moment and try a different approach. This creates a new branch of history without losing your original work. @@ -101,5 +101,5 @@ This creates a new branch of history without losing your original work. - Learn about [Checkpointing](../../cli/checkpointing.md) to understand the underlying safety mechanism. - Explore [Task planning](task-planning.md) to keep complex sessions organized. -- See the [Command reference](../../reference/commands.md) for all `/chat` and - `/resume` options. +- See the [Command reference](../../reference/commands.md) for `/resume` + options, grouped checkpoint menus, and `/chat` compatibility aliases. diff --git a/docs/cli/tutorials/shell-commands.md b/docs/cli/tutorials/shell-commands.md index 22e945407e..3eaaf2049e 100644 --- a/docs/cli/tutorials/shell-commands.md +++ b/docs/cli/tutorials/shell-commands.md @@ -17,9 +17,10 @@ prefix. **Example:** `!ls -la` -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. +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. ### Scenario: Entering Shell mode diff --git a/docs/core/index.md b/docs/core/index.md index 53aa647dc2..adf186116f 100644 --- a/docs/core/index.md +++ b/docs/core/index.md @@ -9,8 +9,8 @@ requests sent from `packages/cli`. For a general overview of Gemini CLI, see the - **[Sub-agents (experimental)](./subagents.md):** Learn how to create and use specialized sub-agents for complex tasks. -- **[Core tools API](../reference/tools-api.md):** Information on how tools are - defined, registered, and used by the core. +- **[Core tools reference](../reference/tools.md):** Information on how tools + are defined, registered, and used by the core. - **[Memory Import Processor](../reference/memport.md):** Documentation for the modular GEMINI.md import feature using @file.md syntax. - **[Policy Engine](../reference/policy-engine.md):** Use the Policy Engine for diff --git a/docs/core/remote-agents.md b/docs/core/remote-agents.md index 3e5b8b06d1..a01f015672 100644 --- a/docs/core/remote-agents.md +++ b/docs/core/remote-agents.md @@ -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 refresh`: Reloads the agent registry. Use this after adding or +- `/agents reload`: Reloads the agent registry. Use this after adding or modifying agent definition files. - `/agents enable `: Enables a specific subagent. - `/agents disable `: Disables a specific subagent. diff --git a/docs/get-started/authentication.md b/docs/get-started/authentication.md index 61d4a5c040..8b8f592335 100644 --- a/docs/get-started/authentication.md +++ b/docs/get-started/authentication.md @@ -4,6 +4,10 @@ To use Gemini CLI, you'll need to authenticate with Google. This guide helps you quickly find the best way to sign in based on your account type and how you're using the CLI. +> **Note:** Looking for a high-level comparison of all available subscriptions? +> To compare features and find the right quota for your needs, see our +> [Plans page](/plans/). + For most users, we recommend starting Gemini CLI and logging in with your personal Google account. diff --git a/docs/get-started/gemini-3.md b/docs/get-started/gemini-3.md index a5eed9ab1d..bc83d990d5 100644 --- a/docs/get-started/gemini-3.md +++ b/docs/get-started/gemini-3.md @@ -39,6 +39,10 @@ When you encounter that limit, you’ll be given the option to switch to Gemini 2.5 Pro, upgrade for higher limits, or stop. You’ll also be told when your usage limit resets and Gemini 3 Pro can be used again. +> **Note:** Looking to upgrade for higher limits? To compare subscription +> options and find the right quota for your needs, see our +> [Plans page](/plans/). + Similarly, when you reach your daily usage limit for Gemini 2.5 Pro, you’ll see a message prompting fallback to Gemini 2.5 Flash. diff --git a/docs/get-started/index.md b/docs/get-started/index.md index bc29581d2f..c516f90ac4 100644 --- a/docs/get-started/index.md +++ b/docs/get-started/index.md @@ -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 diff --git a/docs/hooks/reference.md b/docs/hooks/reference.md index 9b7226ac05..445035b1aa 100644 --- a/docs/hooks/reference.md +++ b/docs/hooks/reference.md @@ -82,8 +82,8 @@ For `BeforeTool` and `AfterTool` events, the `matcher` field in your settings is compared against the name of the tool being executed. - **Built-in Tools**: You can match any built-in tool (e.g., `read_file`, - `run_shell_command`). See the [Tools Reference](/docs/tools) for a full list - of available tool names. + `run_shell_command`). See the [Tools Reference](/docs/reference/tools) for a + full list of available tool names. - **MCP Tools**: Tools from MCP servers follow the naming pattern `mcp____`. - **Regex Support**: Matchers support regular expressions (e.g., diff --git a/docs/index.md b/docs/index.md index 3ccaf3b797..af1915bb8f 100644 --- a/docs/index.md +++ b/docs/index.md @@ -108,8 +108,8 @@ Deep technical documentation and API specifications. processes memory from various sources. - **[Policy engine](./reference/policy-engine.md):** Fine-grained execution control. -- **[Tools API](./reference/tools-api.md):** The API for defining and using - tools. +- **[Tools reference](./reference/tools.md):** Information on how tools are + defined, registered, and used. ## Resources diff --git a/docs/issue-and-pr-automation.md b/docs/issue-and-pr-automation.md index 27185de11c..6c023b651b 100644 --- a/docs/issue-and-pr-automation.md +++ b/docs/issue-and-pr-automation.md @@ -113,7 +113,45 @@ process. ensure every issue is eventually categorized, even if the initial triage fails. -### 5. Release automation +### 5. Automatic unassignment of inactive contributors: `Unassign Inactive Issue Assignees` + +To keep the list of open `help wanted` issues accessible to all contributors, +this workflow automatically removes **external contributors** who have not +opened a linked pull request within **7 days** of being assigned. Maintainers, +org members, and repo collaborators with write access or above are always exempt +and will never be auto-unassigned. + +- **Workflow File**: `.github/workflows/unassign-inactive-assignees.yml` +- **When it runs**: Every day at 09:00 UTC, and can be triggered manually with + an optional `dry_run` mode. +- **What it does**: + 1. Finds every open issue labeled `help wanted` that has at least one + assignee. + 2. Identifies privileged users (team members, repo collaborators with write+ + access, maintainers) and skips them entirely. + 3. For each remaining (external) assignee it reads the issue's timeline to + determine: + - The exact date they were assigned (using `assigned` timeline events). + - Whether they have opened a PR that is already linked/cross-referenced to + the issue. + 4. Each cross-referenced PR is fetched to verify it is **ready for review**: + open and non-draft, or already merged. Draft PRs do not count. + 5. If an assignee has been assigned for **more than 7 days** and no qualifying + PR is found, they are automatically unassigned and a comment is posted + explaining the reason and how to re-claim the issue. + 6. Assignees who have a non-draft, open or merged PR linked to the issue are + **never** unassigned by this workflow. +- **What you should do**: + - **Open a real PR, not a draft**: Within 7 days of being assigned, open a PR + that is ready for review and include `Fixes #` in the + description. Draft PRs do not satisfy the requirement and will not prevent + auto-unassignment. + - **Re-assign if unassigned by mistake**: Comment `/assign` on the issue to + assign yourself again. + - **Unassign yourself** if you can no longer work on the issue by commenting + `/unassign`, so other contributors can pick it up right away. + +### 6. Release automation This workflow handles the process of packaging and publishing new versions of the Gemini CLI. diff --git a/docs/redirects.json b/docs/redirects.json index 5183d0d476..598f42cccf 100644 --- a/docs/redirects.json +++ b/docs/redirects.json @@ -8,7 +8,8 @@ "/docs/core/concepts": "/docs", "/docs/core/memport": "/docs/reference/memport", "/docs/core/policy-engine": "/docs/reference/policy-engine", - "/docs/core/tools-api": "/docs/reference/tools-api", + "/docs/core/tools-api": "/docs/reference/tools", + "/docs/reference/tools-api": "/docs/reference/tools", "/docs/faq": "/docs/resources/faq", "/docs/get-started/configuration": "/docs/reference/configuration", "/docs/get-started/configuration-v1": "/docs/reference/configuration", diff --git a/docs/reference/commands.md b/docs/reference/commands.md index ceb064a9bf..b23f545501 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -28,24 +28,33 @@ Slash commands provide meta-level control over the CLI itself. ### `/chat` -- **Description:** Save and resume conversation history for branching - conversation state interactively, or resuming a previous state from a later - session. +- **Description:** Alias for `/resume`. Both commands now expose the same + session browser action and checkpoint subcommands. +- **Menu layout when typing `/chat` (or `/resume`)**: + - `-- auto --` + - `list` (selecting this opens the auto-saved session browser) + - `-- checkpoints --` + - `list`, `save`, `resume`, `delete`, `share` (manual tagged checkpoints) + - **Note:** Unique prefixes (for example `/cha` or `/resum`) resolve to the + same grouped menu. - **Sub-commands:** - **`debug`** - **Description:** Export the most recent API request as a JSON payload. - **`delete `** - **Description:** Deletes a saved conversation checkpoint. + - **Equivalent:** `/resume delete ` - **`list`** - - **Description:** Lists available tags for chat state resumption. + - **Description:** Lists available tags for manually saved checkpoints. - **Note:** This command only lists chats saved within the current project. Because chat history is project-scoped, chats saved in other project directories will not be displayed. + - **Equivalent:** `/resume list` - **`resume `** - **Description:** Resumes a conversation from a previous save. - **Note:** You can only resume chats that were saved within the current project. To resume a chat from a different project, you must run the Gemini CLI from that project's directory. + - **Equivalent:** `/resume resume ` - **`save `** - **Description:** Saves the current conversation history. You must add a `` for identifying the conversation state. @@ -60,10 +69,12 @@ Slash commands provide meta-level control over the CLI itself. conversation states. For automatic checkpoints created before file modifications, see the [Checkpointing documentation](../cli/checkpointing.md). + - **Equivalent:** `/resume save ` - **`share [filename]`** - **Description** Writes the current conversation to a provided Markdown or JSON file. If no filename is provided, then the CLI will generate one. - **Usage** `/chat share file.md` or `/chat share file.json`. + - **Equivalent:** `/resume share [filename]` ### `/clear` @@ -270,6 +281,9 @@ Slash commands provide meta-level control over the CLI itself. one has been generated. - **Note:** This feature requires the `experimental.plan` setting to be enabled in your configuration. +- **Sub-commands:** + - **`copy`**: + - **Description:** Copy the currently approved plan to your clipboard. ### `/policies` @@ -311,10 +325,13 @@ Slash commands provide meta-level control over the CLI itself. ### `/resume` -- **Description:** Browse and resume previous conversation sessions. Opens an - interactive session browser where you can search, filter, and select from - automatically saved conversations. +- **Description:** Browse and resume previous conversation sessions, and manage + manual chat checkpoints. - **Features:** + - **Auto sessions:** Run `/resume` to open the interactive session browser for + automatically saved conversations. + - **Chat checkpoints:** Use checkpoint subcommands directly (`/resume save`, + `/resume resume`, etc.). - **Management:** Delete unwanted sessions directly from the browser - **Resume:** Select any session to resume and continue the conversation - **Search:** Use `/` to search through conversation content across all @@ -325,6 +342,23 @@ Slash commands provide meta-level control over the CLI itself. - **Note:** All conversations are automatically saved as you chat - no manual saving required. See [Session Management](../cli/session-management.md) for complete details. +- **Alias:** `/chat` provides the same behavior and subcommands. +- **Sub-commands:** + - **`list`** + - **Description:** Lists available tags for manual chat checkpoints. + - **`save `** + - **Description:** Saves the current conversation as a tagged checkpoint. + - **`resume `** (alias: `load`) + - **Description:** Loads a previously saved tagged checkpoint. + - **`delete `** + - **Description:** Deletes a tagged checkpoint. + - **`share [filename]`** + - **Description:** Exports the current conversation to Markdown or JSON. + - **`debug`** + - **Description:** Export the most recent API request as JSON payload + (nightly builds). + - **Compatibility alias:** `/resume checkpoints ...` is still accepted for the + same checkpoint commands. ### `/settings` diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 49954da8c6..9b89fe75a8 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -250,8 +250,18 @@ their corresponding top-level category object in your `settings.json` file. input. - **Default:** `false` +- **`ui.footer.items`** (array): + - **Description:** List of item IDs to display in the footer. Rendered in + order + - **Default:** `undefined` + +- **`ui.footer.showLabels`** (boolean): + - **Description:** Display a second line above the footer items with + descriptive headers (e.g., /model). + - **Default:** `true` + - **`ui.footer.hideCWD`** (boolean): - - **Description:** Hide the current working directory path in the footer. + - **Description:** Hide the current working directory in the footer. - **Default:** `false` - **`ui.footer.hideSandboxStatus`** (boolean): @@ -709,7 +719,7 @@ their corresponding top-level category object in your `settings.json` file. - **Default:** `[]` - **`context.loadMemoryFromIncludeDirectories`** (boolean): - - **Description:** Controls how /memory refresh loads GEMINI.md files. When + - **Description:** Controls how /memory reload loads GEMINI.md files. When true, include directories are scanned; when false, only the current directory is used. - **Default:** `false` @@ -747,7 +757,8 @@ their corresponding top-level category object in your `settings.json` file. - **`tools.sandbox`** (boolean | string): - **Description:** Sandbox execution environment. Set to a boolean to enable - or disable the sandbox, or provide a string path to a sandbox profile. + or disable the sandbox, provide a string path to a sandbox profile, or + specify an explicit sandbox command (e.g., "docker", "podman", "lxc"). - **Default:** `undefined` - **Requires restart:** Yes @@ -1014,6 +1025,11 @@ their corresponding top-level category object in your `settings.json` file. - **Default:** `false` - **Requires restart:** Yes +- **`experimental.taskTracker`** (boolean): + - **Description:** Enable task tracker tools. + - **Default:** `false` + - **Requires restart:** Yes + - **`experimental.modelSteering`** (boolean): - **Description:** Enable model steering (user hints) to guide the model during tool execution. @@ -1025,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. Requires a local endpoint - serving Gemma via the Gemini API using LiteRT-LM shim. + - **Description:** Enable the Gemma Model Router (experimental). Requires a + local endpoint serving Gemma via the Gemini API using LiteRT-LM shim. - **Default:** `false` - **Requires restart:** Yes @@ -1689,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 `refresh`). + the `/memory` command and its sub-commands (`show` and `reload`). By understanding and utilizing these configuration layers and the hierarchical nature of context files, you can effectively manage the AI's memory and tailor diff --git a/docs/reference/keyboard-shortcuts.md b/docs/reference/keyboard-shortcuts.md index e5691c43ee..7b396b73d4 100644 --- a/docs/reference/keyboard-shortcuts.md +++ b/docs/reference/keyboard-shortcuts.md @@ -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`
`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`
`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`
`Home (no Shift, Ctrl)` | -| Move the cursor to the end of the line. | `Ctrl + E`
`End (no Shift, Ctrl)` | -| Move the cursor up one line. | `Up Arrow (no Shift, Alt, Ctrl, Cmd)` | -| Move the cursor down one line. | `Down Arrow (no Shift, Alt, Ctrl, Cmd)` | -| Move the cursor one character to the left. | `Left Arrow (no Shift, Alt, Ctrl, Cmd)` | -| Move the cursor one character to the right. | `Right Arrow (no Shift, Alt, Ctrl, Cmd)`
`Ctrl + F` | -| Move the cursor one word to the left. | `Ctrl + Left Arrow`
`Alt + Left Arrow`
`Alt + B` | -| Move the cursor one word to the right. | `Ctrl + Right Arrow`
`Alt + Right Arrow`
`Alt + F` | +| Action | Keys | +| ------------------------------------------- | ------------------------------------------ | +| Move the cursor to the start of the line. | `Ctrl+A`
`Home` | +| Move the cursor to the end of the line. | `Ctrl+E`
`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`
`Ctrl+F` | +| Move the cursor one word to the left. | `Ctrl+Left`
`Alt+Left`
`Alt+B` | +| Move the cursor one word to the right. | `Ctrl+Right`
`Alt+Right`
`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`
`Alt + Backspace`
`Ctrl + W` | -| Delete the next word. | `Ctrl + Delete`
`Alt + Delete`
`Alt + D` | -| Delete the character to the left. | `Backspace`
`Ctrl + H` | -| Delete the character to the right. | `Delete`
`Ctrl + D` | -| Undo the most recent text edit. | `Cmd + Z (no Shift)`
`Alt + Z (no Shift)` | -| Redo the most recent undone text edit. | `Shift + Ctrl + Z`
`Shift + Cmd + Z`
`Shift + Alt + 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`
`Alt+Backspace`
`Ctrl+W` | +| Delete the next word. | `Ctrl+Delete`
`Alt+Delete`
`Alt+D` | +| Delete the character to the left. | `Backspace`
`Ctrl+H` | +| Delete the character to the right. | `Delete`
`Ctrl+D` | +| Undo the most recent text edit. | `Cmd/Win+Z`
`Alt+Z` | +| Redo the most recent undone text edit. | `Ctrl+Shift+Z`
`Shift+Cmd/Win+Z`
`Alt+Shift+Z` | #### Scrolling -| Action | Keys | -| ------------------------ | --------------------------------- | -| Scroll content up. | `Shift + Up Arrow` | -| Scroll content down. | `Shift + Down Arrow` | -| Scroll to the top. | `Ctrl + Home`
`Shift + Home` | -| Scroll to the bottom. | `Ctrl + End`
`Shift + End` | -| Scroll up by one page. | `Page Up` | -| Scroll down by one page. | `Page Down` | +| Action | Keys | +| ------------------------ | ----------------------------- | +| Scroll content up. | `Shift+Up` | +| Scroll content down. | `Shift+Down` | +| Scroll to the top. | `Ctrl+Home`
`Shift+Home` | +| Scroll to the bottom. | `Ctrl+End`
`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 (no Shift)` | -| Show the next entry in history. | `Ctrl + N (no Shift)` | -| Start reverse search through history. | `Ctrl + R` | -| Submit the selected reverse-search match. | `Enter (no Ctrl)` | -| Accept a suggestion while reverse searching. | `Tab (no Shift)` | -| Browse and rewind previous interactions. | `Double Esc` | +| 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` | +| 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 Arrow (no Shift)` | -| Move selection down in lists. | `Down Arrow (no Shift)` | -| Move up within dialog options. | `Up Arrow (no Shift)`
`K (no Shift)` | -| Move down within dialog options. | `Down Arrow (no Shift)`
`J (no Shift)` | -| Move to the next item or question in a dialog. | `Tab (no Shift)` | -| Move to the previous item or question in a dialog. | `Shift + Tab` | +| Action | Keys | +| -------------------------------------------------- | --------------- | +| Move selection up in lists. | `Up` | +| Move selection down in lists. | `Down` | +| Move up within dialog options. | `Up`
`K` | +| Move down within dialog options. | `Down`
`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 (no Shift)`
`Enter (no Ctrl)` | -| Move to the previous completion option. | `Up Arrow (no Shift)`
`Ctrl + P (no Shift)` | -| Move to the next completion option. | `Down Arrow (no Shift)`
`Ctrl + N (no Shift)` | -| Expand an inline suggestion. | `Right Arrow` | -| Collapse an inline suggestion. | `Left Arrow` | +| Action | Keys | +| --------------------------------------- | -------------------- | +| Accept the inline suggestion. | `Tab`
`Enter` | +| Move to the previous completion option. | `Up`
`Ctrl+P` | +| Move to the next completion option. | `Down`
`Ctrl+N` | +| Expand an inline suggestion. | `Right` | +| Collapse an inline suggestion. | `Left` | #### Text Input -| Action | Keys | -| ---------------------------------------------------------- | ----------------------------------------------------------------------------------------- | -| Submit the current prompt. | `Enter (no Shift, Alt, Ctrl, Cmd)` | -| Insert a newline without submitting. | `Ctrl + Enter`
`Cmd + Enter`
`Alt + Enter`
`Shift + Enter`
`Ctrl + J` | -| Open the current prompt or the plan in an external editor. | `Ctrl + X` | -| Paste from the clipboard. | `Ctrl + V`
`Cmd + V`
`Alt + V` | +| Action | Keys | +| ---------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| Submit the current prompt. | `Enter` | +| Insert a newline without submitting. | `Ctrl+Enter`
`Cmd/Win+Enter`
`Alt+Enter`
`Shift+Enter`
`Ctrl+J` | +| Open the current prompt or the plan in an external editor. | `Ctrl+X` | +| Paste from the clipboard. | `Ctrl+V`
`Cmd/Win+V`
`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 (no Shift)` | -| Show warning when trying to move focus away from background shell. | `Tab (no Shift)` | -| Show warning when trying to move focus away from shell input. | `Tab (no Shift)` | -| Move focus from Gemini to the active shell. | `Tab (no Shift)` | -| Move focus from the shell back to Gemini. | `Shift + Tab` | -| Clear the terminal screen and redraw the UI. | `Ctrl + L` | -| Restart the application. | `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`
`Shift+R` | +| Suspend the CLI and move it to the background. | `Ctrl+Z` | @@ -156,7 +156,7 @@ available combinations. ## Limitations - On [Windows Terminal](https://en.wikipedia.org/wiki/Windows_Terminal): - - `shift+enter` is not supported. + - `shift+enter` is only supported in version 1.25 and higher. - `shift+tab` [is not supported](https://github.com/google-gemini/gemini-cli/issues/20314) on Node 20 and earlier versions of Node 22. diff --git a/docs/reference/tools-api.md b/docs/reference/tools-api.md deleted file mode 100644 index 91fae3f720..0000000000 --- a/docs/reference/tools-api.md +++ /dev/null @@ -1,131 +0,0 @@ -# Gemini CLI core: Tools API - -The Gemini CLI core (`packages/core`) features a robust system for defining, -registering, and executing tools. These tools extend the capabilities of the -Gemini model, allowing it to interact with the local environment, fetch web -content, and perform various actions beyond simple text generation. - -## Core concepts - -- **Tool (`tools.ts`):** An interface and base class (`BaseTool`) that defines - the contract for all tools. Each tool must have: - - `name`: A unique internal name (used in API calls to Gemini). - - `displayName`: A user-friendly name. - - `description`: A clear explanation of what the tool does, which is provided - to the Gemini model. - - `parameterSchema`: A JSON schema defining the parameters that the tool - accepts. This is crucial for the Gemini model to understand how to call the - tool correctly. - - `validateToolParams()`: A method to validate incoming parameters. - - `getDescription()`: A method to provide a human-readable description of what - the tool will do with specific parameters before execution. - - `shouldConfirmExecute()`: A method to determine if user confirmation is - required before execution (e.g., for potentially destructive operations). - - `execute()`: The core method that performs the tool's action and returns a - `ToolResult`. - -- **`ToolResult` (`tools.ts`):** An interface defining the structure of a tool's - execution outcome: - - `llmContent`: The factual content to be included in the history sent back to - the LLM for context. This can be a simple string or a `PartListUnion` (an - array of `Part` objects and strings) for rich content. - - `returnDisplay`: A user-friendly string (often Markdown) or a special object - (like `FileDiff`) for display in the CLI. - -- **Returning rich content:** Tools are not limited to returning simple text. - The `llmContent` can be a `PartListUnion`, which is an array that can contain - a mix of `Part` objects (for images, audio, etc.) and `string`s. This allows a - single tool execution to return multiple pieces of rich content. - -- **Tool registry (`tool-registry.ts`):** A class (`ToolRegistry`) responsible - for: - - **Registering tools:** Holding a collection of all available built-in tools - (e.g., `ReadFileTool`, `ShellTool`). - - **Discovering tools:** It can also discover tools dynamically: - - **Command-based discovery:** If `tools.discoveryCommand` is configured in - settings, this command is executed. It's expected to output JSON - describing custom tools, which are then registered as `DiscoveredTool` - instances. - - **MCP-based discovery:** If `mcp.serverCommand` is configured, the - registry can connect to a Model Context Protocol (MCP) server to list and - register tools (`DiscoveredMCPTool`). - - **Providing schemas:** Exposing the `FunctionDeclaration` schemas of all - registered tools to the Gemini model, so it knows what tools are available - and how to use them. - - **Retrieving tools:** Allowing the core to get a specific tool by name for - execution. - -## Built-in tools - -The core comes with a suite of pre-defined tools, typically found in -`packages/core/src/tools/`. These include: - -- **File system tools:** - - `LSTool` (`ls.ts`): Lists directory contents. - - `ReadFileTool` (`read-file.ts`): Reads the content of a single file. - - `WriteFileTool` (`write-file.ts`): Writes content to a file. - - `GrepTool` (`grep.ts`): Searches for patterns in files. - - `GlobTool` (`glob.ts`): Finds files matching glob patterns. - - `EditTool` (`edit.ts`): Performs in-place modifications to files (often - requiring confirmation). - - `ReadManyFilesTool` (`read-many-files.ts`): Reads and concatenates content - from multiple files or glob patterns (used by the `@` command in CLI). -- **Execution tools:** - - `ShellTool` (`shell.ts`): Executes arbitrary shell commands (requires - careful sandboxing and user confirmation). -- **Web tools:** - - `WebFetchTool` (`web-fetch.ts`): Fetches content from a URL. - - `WebSearchTool` (`web-search.ts`): Performs a web search. -- **Memory tools:** - - `MemoryTool` (`memoryTool.ts`): Interacts with the AI's memory. - -Each of these tools extends `BaseTool` and implements the required methods for -its specific functionality. - -## Tool execution flow - -1. **Model request:** The Gemini model, based on the user's prompt and the - provided tool schemas, decides to use a tool and returns a `FunctionCall` - part in its response, specifying the tool name and arguments. -2. **Core receives request:** The core parses this `FunctionCall`. -3. **Tool retrieval:** It looks up the requested tool in the `ToolRegistry`. -4. **Parameter validation:** The tool's `validateToolParams()` method is - called. -5. **Confirmation (if needed):** - - The tool's `shouldConfirmExecute()` method is called. - - If it returns details for confirmation, the core communicates this back to - the CLI, which prompts the user. - - The user's decision (e.g., proceed, cancel) is sent back to the core. -6. **Execution:** If validated and confirmed (or if no confirmation is needed), - the core calls the tool's `execute()` method with the provided arguments and - an `AbortSignal` (for potential cancellation). -7. **Result processing:** The `ToolResult` from `execute()` is received by the - core. -8. **Response to model:** The `llmContent` from the `ToolResult` is packaged as - a `FunctionResponse` and sent back to the Gemini model so it can continue - generating a user-facing response. -9. **Display to user:** The `returnDisplay` from the `ToolResult` is sent to - the CLI to show the user what the tool did. - -## Extending with custom tools - -While direct programmatic registration of new tools by users isn't explicitly -detailed as a primary workflow in the provided files for typical end-users, the -architecture supports extension through: - -- **Command-based discovery:** Advanced users or project administrators can - define a `tools.discoveryCommand` in `settings.json`. This command, when run - by the Gemini CLI core, should output a JSON array of `FunctionDeclaration` - objects. The core will then make these available as `DiscoveredTool` - instances. The corresponding `tools.callCommand` would then be responsible for - actually executing these custom tools. -- **MCP server(s):** For more complex scenarios, one or more MCP servers can be - set up and configured via the `mcpServers` setting in `settings.json`. The - Gemini CLI core can then discover and use tools exposed by these servers. As - mentioned, if you have multiple MCP servers, the tool names will be prefixed - with the server name from your configuration (e.g., - `serverAlias__actualToolName`). - -This tool system provides a flexible and powerful way to augment the Gemini -model's capabilities, making the Gemini CLI a versatile assistant for a wide -range of tasks. diff --git a/docs/reference/tools.md b/docs/reference/tools.md new file mode 100644 index 0000000000..e1a0958866 --- /dev/null +++ b/docs/reference/tools.md @@ -0,0 +1,106 @@ +# Tools reference + +Gemini CLI uses tools to interact with your local environment, access +information, and perform actions on your behalf. These tools extend the model's +capabilities beyond text generation, letting it read files, execute commands, +and search the web. + +## How to use Gemini CLI's tools + +Tools are generally invoked automatically by Gemini CLI when it needs to perform +an action. However, you can also trigger specific tools manually using shorthand +syntax. + +### Automatic execution and security + +When the model wants to use a tool, Gemini CLI evaluates the request against its +security policies. + +- **User confirmation:** You must manually approve tools that modify files or + execute shell commands (mutators). The CLI shows you a diff or the exact + command before you confirm. +- **Sandboxing:** You can run tool executions in secure, containerized + environments to isolate changes from your host system. For more details, see + the [Sandboxing](../cli/sandbox.md) guide. +- **Trusted folders:** You can configure which directories allow the model to + use system tools. For more details, see the + [Trusted folders](../cli/trusted-folders.md) guide. + +Review confirmation prompts carefully before allowing a tool to execute. + +### How to use manually-triggered tools + +You can directly trigger key tools using special syntax in your prompt: + +- **[File access](../tools/file-system.md#read_many_files) (`@`):** Use the `@` + symbol followed by a file or directory path to include its content in your + prompt. This triggers the `read_many_files` tool. +- **[Shell commands](../tools/shell.md) (`!`):** Use the `!` symbol followed by + a system command to execute it directly. This triggers the `run_shell_command` + tool. + +## How to manage tools + +Using built-in commands, you can inspect available tools and configure how they +behave. + +### Tool discovery + +Use the `/tools` command to see what tools are currently active in your session. + +- **`/tools`**: Lists all registered tools with their display names. +- **`/tools desc`**: Lists all tools with their full descriptions. + +This is especially useful for verifying that +[MCP servers](../tools/mcp-server.md) or custom tools are loaded correctly. + +### Tool configuration + +You can enable, disable, or configure specific tools in your settings. For +example, you can set a specific pager for shell commands or configure the +browser used for web searches. See the [Settings](../cli/settings.md) guide for +details. + +## Available tools + +The following table lists all available tools, categorized by their primary +function. + +| Category | Tool | Kind | Description | +| :---------- | :----------------------------------------------- | :------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Execution | [`run_shell_command`](../tools/shell.md) | `Execute` | Executes arbitrary shell commands. Supports interactive sessions and background processes. Requires manual confirmation.

**Parameters:** `command`, `description`, `dir_path`, `is_background` | +| File System | [`glob`](../tools/file-system.md) | `Search` | Finds files matching specific glob patterns across the workspace.

**Parameters:** `pattern`, `dir_path`, `case_sensitive`, `respect_git_ignore`, `respect_gemini_ignore` | +| File System | [`grep_search`](../tools/file-system.md) | `Search` | Searches for a regular expression pattern within file contents. Legacy alias: `search_file_content`.

**Parameters:** `pattern`, `dir_path`, `include`, `exclude_pattern`, `names_only`, `max_matches_per_file`, `total_max_matches` | +| File System | [`list_directory`](../tools/file-system.md) | `Read` | Lists the names of files and subdirectories within a specified path.

**Parameters:** `dir_path`, `ignore`, `file_filtering_options` | +| File System | [`read_file`](../tools/file-system.md) | `Read` | Reads the content of a specific file. Supports text, images, audio, and PDF.

**Parameters:** `file_path`, `start_line`, `end_line` | +| File System | [`read_many_files`](../tools/file-system.md) | `Read` | Reads and concatenates content from multiple files. Often triggered by the `@` symbol in your prompt.

**Parameters:** `include`, `exclude`, `recursive`, `useDefaultExcludes`, `file_filtering_options` | +| File System | [`replace`](../tools/file-system.md) | `Edit` | Performs precise text replacement within a file. Requires manual confirmation.

**Parameters:** `file_path`, `instruction`, `old_string`, `new_string`, `allow_multiple` | +| File System | [`write_file`](../tools/file-system.md) | `Edit` | Creates or overwrites a file with new content. Requires manual confirmation.

**Parameters:** `file_path`, `content` | +| Interaction | [`ask_user`](../tools/ask-user.md) | `Communicate` | Requests clarification or missing information via an interactive dialog.

**Parameters:** `questions` | +| Interaction | [`write_todos`](../tools/todos.md) | `Other` | Maintains an internal list of subtasks. The model uses this to track its own progress and display it to you.

**Parameters:** `todos` | +| Memory | [`activate_skill`](../tools/activate-skill.md) | `Other` | Loads specialized procedural expertise for specific tasks from the `.gemini/skills` directory.

**Parameters:** `name` | +| Memory | [`get_internal_docs`](../tools/internal-docs.md) | `Think` | Accesses Gemini CLI's own documentation to provide more accurate answers about its capabilities.

**Parameters:** `path` | +| Memory | [`save_memory`](../tools/memory.md) | `Think` | Persists specific facts and project details to your `GEMINI.md` file to retain context.

**Parameters:** `fact` | +| Planning | [`enter_plan_mode`](../tools/planning.md) | `Plan` | Switches the CLI to a safe, read-only "Plan Mode" for researching complex changes.

**Parameters:** `reason` | +| Planning | [`exit_plan_mode`](../tools/planning.md) | `Plan` | Finalizes a plan, presents it for review, and requests approval to start implementation.

**Parameters:** `plan` | +| System | `complete_task` | `Other` | Finalizes a subagent's mission and returns the result to the parent agent. This tool is not available to the user.

**Parameters:** `result` | +| Web | [`google_web_search`](../tools/web-search.md) | `Search` | Performs a Google Search to find up-to-date information.

**Parameters:** `query` | +| Web | [`web_fetch`](../tools/web-fetch.md) | `Fetch` | Retrieves and processes content from specific URLs. **Warning:** This tool can access local and private network addresses (e.g., localhost), which may pose a security risk if used with untrusted prompts.

**Parameters:** `prompt` | + +## Under the hood + +For developers, the tool system is designed to be extensible and robust. The +`ToolRegistry` class manages all available tools. + +You can extend Gemini CLI with custom tools by configuring +`tools.discoveryCommand` in your settings or by connecting to MCP servers. + +> **Note:** For a deep dive into the internal Tool API and how to implement your +> own tools in the codebase, see the `packages/core/src/tools/` directory in +> GitHub. + +## Next steps + +- Learn how to [Set up an MCP server](../tools/mcp-server.md). +- Explore [Agent Skills](../cli/skills.md) for specialized expertise. +- See the [Command reference](./commands.md) for slash commands. diff --git a/docs/resources/quota-and-pricing.md b/docs/resources/quota-and-pricing.md index d4ed22a1cb..3d03dc395e 100644 --- a/docs/resources/quota-and-pricing.md +++ b/docs/resources/quota-and-pricing.md @@ -1,14 +1,13 @@ # Gemini CLI: Quotas and pricing Gemini CLI offers a generous free tier that covers many individual developers' -use cases. For enterprise or professional usage, or if you need higher limits, +use cases. For enterprise or professional usage, or if you need increased quota, several options are available depending on your authentication account type. -See [privacy and terms](./tos-privacy.md) for details on the Privacy Policy and -Terms of Service. +For a high-level comparison of available subscriptions and to select the right +quota for your needs, see the [Plans page](/plans/). -> **Note:** Published prices are list price; additional negotiated commercial -> discounting may apply. +## Overview This article outlines the specific quotas and pricing applicable to Gemini CLI when using different authentication methods. @@ -23,10 +22,11 @@ Generally, there are three categories to choose from: ## Free usage -Your journey begins with a generous free tier, perfect for experimentation and -light use. +Access to Gemini CLI begins with a generous free tier, perfect for +experimentation and light use. -Your free usage limits depend on your authorization type. +Your free usage is governed by the following limits, which depend on your +authorization type. ### Log in with Google (Gemini Code Assist for individuals) @@ -69,6 +69,19 @@ 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. @@ -78,14 +91,26 @@ Gemini CLI by upgrading to one of the following subscriptions: Learn more at [Gemini Code Assist Quotas and Limits](https://developers.google.com/gemini-code-assist/resources/quotas) -- [Purchase a Gemini Code Assist Subscription through Google Cloud ](https://cloud.google.com/gemini/docs/codeassist/overview) - by signing up in the Google Cloud console. Learn more at - [Set up Gemini Code Assist](https://cloud.google.com/gemini/docs/discover/set-up-gemini). +### 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 license seats. For predictable costs, you can sign in with Google. - This includes: + This includes the following request limits: - Gemini Code Assist Standard edition: - 1500 model requests / user / day - 120 model requests / user / minute @@ -95,7 +120,7 @@ Gemini CLI by upgrading to one of the following subscriptions: - Model requests will be made across the Gemini model family as determined by 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). + [Learn more about Gemini Code Assist license limits](https://developers.google.com/gemini-code-assist/resources/quotas#quotas-for-agent-mode-gemini-cli). ## Pay as you go @@ -106,18 +131,27 @@ recommended path for uninterrupted access. To do this, log in using a Gemini API key or Vertex AI. -- Vertex AI (Regular Mode): - - Quota: Governed by a dynamic shared quota system or pre-purchased - provisioned throughput. - - Cost: Based on model and token usage. +### Vertex AI (regular mode) + +An enterprise-grade platform for building, deploying, and managing AI models, +including Gemini. It offers enhanced security, data governance, and integration +with other Google Cloud services. + +- Quota: Governed by a dynamic shared quota system or pre-purchased provisioned + throughput. +- Cost: Based on model and token usage. Learn more at [Vertex AI Dynamic Shared Quota](https://cloud.google.com/vertex-ai/generative-ai/docs/resources/dynamic-shared-quota) and [Vertex AI Pricing](https://cloud.google.com/vertex-ai/pricing). -- Gemini API key: - - Quota: Varies by pricing tier. - - Cost: Varies by pricing tier and model/token usage. +### Gemini API key + +Ideal for developers who want to quickly build applications with the Gemini +models. This is the most direct way to use the models. + +- Quota: Varies by pricing tier. +- Cost: Varies by pricing tier and model/token usage. Learn more at [Gemini API Rate Limits](https://ai.google.dev/gemini-api/docs/rate-limits), @@ -125,7 +159,8 @@ Learn more at It’s important to highlight that when using an API key, you pay per token/call. This can be more expensive for many small calls with few tokens, but it's the -only way to ensure your workflow isn't interrupted by quota limits. +only way to ensure your workflow isn't interrupted by reaching a limit on your +quota. ## Gemini for workspace plans @@ -135,31 +170,30 @@ Flow video editor). These plans do not apply to the API usage which powers the Gemini CLI. Supporting these plans is under active consideration for future support. -## Check usage and quota +## Check usage and limits -You can check your current token usage and quota information using the +You can check your current token usage and applicable limits using the `/stats model` command. This command provides a snapshot of your current -session's token usage, as well as your overall quota and usage for the supported -models. +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. ## Tips to avoid high costs -When using a Pay as you Go API key, be mindful of your usage to avoid unexpected +When using a pay-as-you-go plan, be mindful of your usage to avoid unexpected costs. -- Don't blindly accept every suggestion, especially for computationally - intensive tasks like refactoring large codebases. -- Be intentional with your prompts and commands. You are paying per call, so - think about the most efficient way to get the job done. - -## Gemini API vs. Vertex - -- Gemini API (gemini developer api): This is the fastest way to use the Gemini - models directly. -- Vertex AI: This is the enterprise-grade platform for building, deploying, and - managing Gemini models with specific security and control requirements. +- **Be selective with suggestions**: Before accepting a suggestion, especially + for a computationally intensive task like refactoring a large codebase, + consider if it's the most cost-effective approach. +- **Use precise prompts**: You are paying per call, so think about the most + efficient way to get your desired result. A well-crafted prompt can often get + you the answer you need in a single call, rather than multiple back-and-forth + interactions. +- **Monitor your usage**: Use the `/stats model` command to track your token + usage during a session. This can help you stay aware of your spending in real + time. diff --git a/docs/sidebar.json b/docs/sidebar.json index c2c6295bfa..7c201e0071 100644 --- a/docs/sidebar.json +++ b/docs/sidebar.json @@ -94,11 +94,23 @@ { "label": "Agent Skills", "slug": "docs/cli/skills" }, { "label": "Checkpointing", "slug": "docs/cli/checkpointing" }, { "label": "Headless mode", "slug": "docs/cli/headless" }, - { "label": "Hooks", "slug": "docs/hooks" }, + { + "label": "Hooks", + "collapsed": true, + "items": [ + { "label": "Overview", "slug": "docs/hooks" }, + { "label": "Reference", "slug": "docs/hooks/reference" } + ] + }, { "label": "IDE integration", "slug": "docs/ide-integration" }, { "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", @@ -181,7 +193,7 @@ "slug": "docs/reference/memport" }, { "label": "Policy engine", "slug": "docs/reference/policy-engine" }, - { "label": "Tools API", "slug": "docs/reference/tools-api" } + { "label": "Tools reference", "slug": "docs/reference/tools" } ] } ] diff --git a/docs/tools/index.md b/docs/tools/index.md deleted file mode 100644 index 6bdf298fea..0000000000 --- a/docs/tools/index.md +++ /dev/null @@ -1,105 +0,0 @@ -# Gemini CLI tools - -Gemini CLI uses tools to interact with your local environment, access -information, and perform actions on your behalf. These tools extend the model's -capabilities beyond text generation, letting it read files, execute commands, -and search the web. - -## User-triggered tools - -You can directly trigger these tools using special syntax in your prompts. - -- **[File access](./file-system.md#read_many_files) (`@`):** Use the `@` symbol - followed by a file or directory path to include its content in your prompt. - This triggers the `read_many_files` tool. -- **[Shell commands](./shell.md) (`!`):** Use the `!` symbol followed by a - system command to execute it directly. This triggers the `run_shell_command` - tool. - -## Model-triggered tools - -The Gemini model automatically requests these tools when it needs to perform -specific actions or gather information to fulfill your requests. You do not call -these tools manually. - -### File management - -These tools let the model explore and modify your local codebase. - -- **[Directory listing](./file-system.md#list_directory) (`list_directory`):** - Lists files and subdirectories. -- **[File reading](./file-system.md#read_file) (`read_file`):** Reads the - content of a specific file. -- **[File writing](./file-system.md#write_file) (`write_file`):** Creates or - overwrites a file with new content. -- **[File search](./file-system.md#glob) (`glob`):** Finds files matching a glob - pattern. -- **[Text search](./file-system.md#search_file_content) - (`search_file_content`):** Searches for text within files using grep or - ripgrep. -- **[Text replacement](./file-system.md#replace) (`replace`):** Performs precise - edits within a file. - -### Agent coordination - -These tools help the model manage its plan and interact with you. - -- **Ask user (`ask_user`):** Requests clarification or missing information from - you via an interactive dialog. -- **[Memory](./memory.md) (`save_memory`):** Saves important facts to your - long-term memory (`GEMINI.md`). -- **[Todos](./todos.md) (`write_todos`):** Manages a list of subtasks for - complex plans. -- **[Agent Skills](../cli/skills.md) (`activate_skill`):** Loads specialized - procedural expertise when needed. -- **[Browser agent](../core/subagents.md#browser-agent-experimental) - (`browser_agent`):** Automates web browser tasks through the accessibility - tree. -- **Internal docs (`get_internal_docs`):** Accesses Gemini CLI's own - documentation to help answer your questions. - -### Information gathering - -These tools provide the model with access to external data. - -- **[Web fetch](./web-fetch.md) (`web_fetch`):** Retrieves and processes content - from specific URLs. -- **[Web search](./web-search.md) (`google_web_search`):** Performs a Google - Search to find up-to-date information. - -## How to use tools - -You use tools indirectly by providing natural language prompts to Gemini CLI. - -1. **Prompt:** You enter a request or use syntax like `@` or `!`. -2. **Request:** The model analyzes your request and identifies if a tool is - required. -3. **Validation:** If a tool is needed, the CLI validates the parameters and - checks your security settings. -4. **Confirmation:** For sensitive operations (like writing files), the CLI - prompts you for approval. -5. **Execution:** The tool runs, and its output is sent back to the model. -6. **Response:** The model uses the results to generate a final, grounded - answer. - -## Security and confirmation - -Safety is a core part of the tool system. To protect your system, Gemini CLI -implements several safeguards. - -- **User confirmation:** You must manually approve tools that modify files or - execute shell commands. The CLI shows you a diff or the exact command before - you confirm. -- **Sandboxing:** You can run tool executions in secure, containerized - environments to isolate changes from your host system. For more details, see - the [Sandboxing](../cli/sandbox.md) guide. -- **Trusted folders:** You can configure which directories allow the model to - use system tools. - -Always review confirmation prompts carefully before allowing a tool to execute. - -## Next steps - -- Learn how to [Provide context](../cli/gemini-md.md) to guide tool use. -- Explore the [Command reference](../reference/commands.md) for tool-related - slash commands. diff --git a/docs/tools/mcp-server.md b/docs/tools/mcp-server.md index 202325a83d..bbb5c62aba 100644 --- a/docs/tools/mcp-server.md +++ b/docs/tools/mcp-server.md @@ -372,7 +372,7 @@ To authenticate with a server using Service Account Impersonation, you must set the `authProviderType` to `service_account_impersonation` and provide the following properties: -- **`targetAudience`** (string): The OAuth Client ID allowslisted on the +- **`targetAudience`** (string): The OAuth Client ID allowlisted on the IAP-protected application you are trying to access. - **`targetServiceAccount`** (string): The email address of the Google Cloud Service Account to impersonate. diff --git a/docs/tools/planning.md b/docs/tools/planning.md index 458b172510..9e9ab3d044 100644 --- a/docs/tools/planning.md +++ b/docs/tools/planning.md @@ -1,8 +1,8 @@ # Gemini CLI planning tools -Planning tools allow the Gemini model to switch into a safe, read-only "Plan -Mode" for researching and planning complex changes, and to signal the -finalization of a plan to the user. +Planning tools let Gemini CLI switch into a safe, read-only "Plan Mode" for +researching and planning complex changes, and to signal the finalization of a +plan to the user. ## 1. `enter_plan_mode` (EnterPlanMode) @@ -18,11 +18,12 @@ and planning. - **File:** `enter-plan-mode.ts` - **Parameters:** - `reason` (string, optional): A short reason explaining why the agent is - entering plan mode (e.g., "Starting a complex feature implementation"). + entering plan mode (for example, "Starting a complex feature + implementation"). - **Behavior:** - Switches the CLI's approval mode to `PLAN`. - Notifies the user that the agent has entered Plan Mode. -- **Output (`llmContent`):** A message indicating the switch, e.g., +- **Output (`llmContent`):** A message indicating the switch, for example, `Switching to Plan mode.` - **Confirmation:** Yes. The user is prompted to confirm entering Plan Mode. @@ -37,7 +38,7 @@ finalized plan to the user and requests approval to start the implementation. - **Parameters:** - `plan_path` (string, required): The path to the finalized Markdown plan file. This file MUST be located within the project's temporary plans - directory (e.g., `~/.gemini/tmp//plans/`). + directory (for example, `~/.gemini/tmp//plans/`). - **Behavior:** - Validates that the `plan_path` is within the allowed directory and that the file exists and has content. diff --git a/eslint.config.js b/eslint.config.js index d305f75f87..d3a267f30a 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -132,7 +132,16 @@ export default tseslint.config( 'no-cond-assign': 'error', 'no-debugger': 'error', 'no-duplicate-case': 'error', - 'no-restricted-syntax': ['error', ...commonRestrictedSyntaxRules], + '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-unsafe-finally': 'error', 'no-unused-expressions': 'off', // Disable base rule '@typescript-eslint/no-unused-expressions': [ @@ -263,6 +272,7 @@ export default tseslint.config( ...vitest.configs.recommended.rules, 'vitest/expect-expect': 'off', 'vitest/no-commented-out-tests': 'off', + 'no-restricted-syntax': ['error', ...commonRestrictedSyntaxRules], }, }, { diff --git a/evals/ask_user.eval.ts b/evals/ask_user.eval.ts new file mode 100644 index 0000000000..c67f995168 --- /dev/null +++ b/evals/ask_user.eval.ts @@ -0,0 +1,92 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, expect } from 'vitest'; +import { evalTest } from './test-helper.js'; + +describe('ask_user', () => { + evalTest('USUALLY_PASSES', { + name: 'Agent uses AskUser tool to present multiple choice options', + prompt: `Use the ask_user tool to ask me what my favorite color is. Provide 3 options: red, green, or blue.`, + assert: async (rig) => { + const wasToolCalled = await rig.waitForToolCall('ask_user'); + expect(wasToolCalled, 'Expected ask_user tool to be called').toBe(true); + }, + }); + + evalTest('USUALLY_PASSES', { + name: 'Agent uses AskUser tool to clarify ambiguous requirements', + files: { + 'package.json': JSON.stringify({ name: 'my-app', version: '1.0.0' }), + }, + prompt: `I want to build a new feature in this app. Ask me questions to clarify the requirements before proceeding.`, + assert: async (rig) => { + const wasToolCalled = await rig.waitForToolCall('ask_user'); + expect(wasToolCalled, 'Expected ask_user tool to be called').toBe(true); + }, + }); + + evalTest('USUALLY_PASSES', { + name: 'Agent uses AskUser tool before performing significant ambiguous rework', + files: { + 'packages/core/src/index.ts': '// index\nexport const version = "1.0.0";', + 'packages/core/src/util.ts': '// util\nexport function help() {}', + 'packages/core/package.json': JSON.stringify({ + name: '@google/gemini-cli-core', + }), + 'README.md': '# Gemini CLI', + }, + prompt: `Refactor the entire core package to be better.`, + assert: async (rig) => { + const wasPlanModeCalled = await rig.waitForToolCall('enter_plan_mode'); + expect(wasPlanModeCalled, 'Expected enter_plan_mode to be called').toBe( + true, + ); + + const wasAskUserCalled = await rig.waitForToolCall('ask_user'); + expect( + wasAskUserCalled, + 'Expected ask_user tool to be called to clarify the significant rework', + ).toBe(true); + }, + }); + + // --- Regression Tests for Recent Fixes --- + + // Regression test for issue #20177: Ensure the agent does not use `ask_user` to + // confirm shell commands. Fixed via prompt refinements and tool definition + // updates to clarify that shell command confirmation is handled by the UI. + // See fix: https://github.com/google-gemini/gemini-cli/pull/20504 + evalTest('USUALLY_PASSES', { + name: 'Agent does NOT use AskUser to confirm shell commands', + files: { + 'package.json': JSON.stringify({ + scripts: { build: 'echo building' }, + }), + }, + prompt: `Run 'npm run build' in the current directory.`, + assert: async (rig) => { + await rig.waitForTelemetryReady(); + + const toolLogs = rig.readToolLogs(); + const wasShellCalled = toolLogs.some( + (log) => log.toolRequest.name === 'run_shell_command', + ); + const wasAskUserCalled = toolLogs.some( + (log) => log.toolRequest.name === 'ask_user', + ); + + expect( + wasShellCalled, + 'Expected run_shell_command tool to be called', + ).toBe(true); + expect( + wasAskUserCalled, + 'ask_user should not be called to confirm shell commands', + ).toBe(false); + }, + }); +}); diff --git a/evals/concurrency-safety.eval.ts b/evals/concurrency-safety.eval.ts new file mode 100644 index 0000000000..f2f9e24be9 --- /dev/null +++ b/evals/concurrency-safety.eval.ts @@ -0,0 +1,56 @@ +/** + * @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); + }, + }); +}); diff --git a/evals/test-helper.ts b/evals/test-helper.ts index 44c538c197..786ec0e418 100644 --- a/evals/test-helper.ts +++ b/evals/test-helper.ts @@ -112,6 +112,7 @@ 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); } diff --git a/integration-tests/acp-env-auth.test.ts b/integration-tests/acp-env-auth.test.ts index c83dbafce5..65f8adbf22 100644 --- a/integration-tests/acp-env-auth.test.ts +++ b/integration-tests/acp-env-auth.test.ts @@ -55,7 +55,7 @@ describe.skip('ACP Environment and Auth', () => { const bundlePath = join(import.meta.dirname, '..', 'bundle/gemini.js'); - child = spawn('node', [bundlePath, '--experimental-acp'], { + child = spawn('node', [bundlePath, '--acp'], { cwd: rig.homeDir!, stdio: ['pipe', 'pipe', 'inherit'], env: { @@ -120,7 +120,7 @@ describe.skip('ACP Environment and Auth', () => { const bundlePath = join(import.meta.dirname, '..', 'bundle/gemini.js'); - child = spawn('node', [bundlePath, '--experimental-acp'], { + child = spawn('node', [bundlePath, '--acp'], { cwd: rig.homeDir!, stdio: ['pipe', 'pipe', 'inherit'], env: { diff --git a/integration-tests/acp-telemetry.test.ts b/integration-tests/acp-telemetry.test.ts index 393156df3e..f883b977bf 100644 --- a/integration-tests/acp-telemetry.test.ts +++ b/integration-tests/acp-telemetry.test.ts @@ -58,7 +58,7 @@ describe('ACP telemetry', () => { 'node', [ bundlePath, - '--experimental-acp', + '--acp', '--fake-responses', join(rig.testDir!, 'fake-responses.json'), ], diff --git a/integration-tests/api-resilience.responses b/integration-tests/api-resilience.responses new file mode 100644 index 0000000000..d30d29906e --- /dev/null +++ b/integration-tests/api-resilience.responses @@ -0,0 +1 @@ +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"Part 1. "}],"role":"model"},"index":0}]},{"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":10,"totalTokenCount":110}},{"candidates":[{"content":{"parts":[{"text":"Part 2."}],"role":"model"},"index":0}],"finishReason":"STOP"}]} diff --git a/integration-tests/api-resilience.test.ts b/integration-tests/api-resilience.test.ts new file mode 100644 index 0000000000..870adf701a --- /dev/null +++ b/integration-tests/api-resilience.test.ts @@ -0,0 +1,50 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { TestRig } from './test-helper.js'; +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +describe('API Resilience E2E', () => { + let rig: TestRig; + + beforeEach(() => { + rig = new TestRig(); + }); + + afterEach(async () => { + await rig.cleanup(); + }); + + it('should not crash when receiving metadata-only chunks in a stream', async () => { + await rig.setup('api-resilience-metadata-only', { + fakeResponsesPath: join( + dirname(fileURLToPath(import.meta.url)), + 'api-resilience.responses', + ), + settings: { + planSettings: { modelRouting: false }, + }, + }); + + // Run the CLI with a simple prompt. + // The fake responses will provide a stream with a metadata-only chunk in the middle. + // We use gemini-3-pro-preview to minimize internal service calls. + const result = await rig.run({ + args: ['hi', '--model', 'gemini-3-pro-preview'], + }); + + // Verify the output contains text from the normal chunks. + // If the CLI crashed on the metadata chunk, rig.run would throw. + expect(result).toContain('Part 1.'); + expect(result).toContain('Part 2.'); + + // Verify telemetry event for the prompt was still generated + const hasUserPromptEvent = await rig.waitForTelemetryEvent('user_prompt'); + expect(hasUserPromptEvent).toBe(true); + }); +}); diff --git a/integration-tests/browser-agent.cleanup.responses b/integration-tests/browser-agent.cleanup.responses new file mode 100644 index 0000000000..988f2fa456 --- /dev/null +++ b/integration-tests/browser-agent.cleanup.responses @@ -0,0 +1,2 @@ +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I'll open https://example.com and check the page title for you."},{"functionCall":{"name":"browser_agent","args":{"task":"Open https://example.com and get the page title"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":35,"totalTokenCount":135}}]} +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"The page title of https://example.com is \"Example Domain\". The browser session has been completed and cleaned up successfully."}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":200,"candidatesTokenCount":30,"totalTokenCount":230}}]} diff --git a/integration-tests/browser-agent.interaction.responses b/integration-tests/browser-agent.interaction.responses new file mode 100644 index 0000000000..98474d6b59 --- /dev/null +++ b/integration-tests/browser-agent.interaction.responses @@ -0,0 +1,2 @@ +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I'll navigate to https://example.com and analyze the links on the page."},{"functionCall":{"name":"browser_agent","args":{"task":"Go to https://example.com and find all links on the page, then describe them"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":40,"totalTokenCount":140}}]} +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"After analyzing https://example.com, I found the following links:\n\n1. **\"More information...\"** - This is the main link on the page that points to the IANA (Internet Assigned Numbers Authority) website for more details about reserved domains.\n\nThe page is quite minimal with just this single informational link, which is typical for example domains used in documentation."}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":200,"candidatesTokenCount":70,"totalTokenCount":270}}]} diff --git a/integration-tests/browser-agent.navigate-snapshot.responses b/integration-tests/browser-agent.navigate-snapshot.responses new file mode 100644 index 0000000000..481520234d --- /dev/null +++ b/integration-tests/browser-agent.navigate-snapshot.responses @@ -0,0 +1,2 @@ +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I'll help you open https://example.com and analyze the page. Let me use the browser agent to navigate and capture the page information."},{"functionCall":{"name":"browser_agent","args":{"task":"Navigate to https://example.com and capture the accessibility tree to get the page title and main content"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":50,"totalTokenCount":150}}]} +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"Based on the browser analysis of https://example.com:\n\n**Page Title**: Example Domain\n\n**Main Content**: The page contains a simple heading \"Example Domain\" and explanatory text stating \"This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.\"\n\nThe page has a clean, minimal layout typical of placeholder domains used for documentation and examples."}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":200,"candidatesTokenCount":80,"totalTokenCount":280}}]} diff --git a/integration-tests/browser-agent.screenshot.responses b/integration-tests/browser-agent.screenshot.responses new file mode 100644 index 0000000000..c9abaa4268 --- /dev/null +++ b/integration-tests/browser-agent.screenshot.responses @@ -0,0 +1,2 @@ +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I'll navigate to https://example.com and take a screenshot for you."},{"functionCall":{"name":"browser_agent","args":{"task":"Navigate to https://example.com and take a screenshot of the page"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":40,"totalTokenCount":140}}]} +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I've successfully navigated to https://example.com and captured a screenshot. The page shows the familiar \"Example Domain\" header with explanatory text below it. The screenshot captures the clean, minimal layout of this demonstration website."}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":200,"candidatesTokenCount":50,"totalTokenCount":250}}]} diff --git a/integration-tests/browser-agent.sequential.responses b/integration-tests/browser-agent.sequential.responses new file mode 100644 index 0000000000..74732998aa --- /dev/null +++ b/integration-tests/browser-agent.sequential.responses @@ -0,0 +1,2 @@ +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I'll help you navigate to https://example.com and perform both operations - capturing the accessibility tree and taking a screenshot."},{"functionCall":{"name":"browser_agent","args":{"task":"Navigate to https://example.com, take a snapshot of the accessibility tree, then take a screenshot"}}}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":45,"totalTokenCount":145}}]} +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I've successfully completed both operations on https://example.com:\n\n**Accessibility Tree Snapshot**: The page has a clear structure with the main heading \"Example Domain\" and descriptive text about the domain's purpose for documentation examples.\n\n**Screenshot**: Captured a visual representation of the page showing the clean, minimal layout with the heading and explanatory text.\n\nBoth the accessibility data and visual screenshot confirm this is the standard example domain page used for documentation purposes."}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":200,"candidatesTokenCount":80,"totalTokenCount":280}}]} diff --git a/integration-tests/browser-agent.test.ts b/integration-tests/browser-agent.test.ts new file mode 100644 index 0000000000..0fdb3e717b --- /dev/null +++ b/integration-tests/browser-agent.test.ts @@ -0,0 +1,206 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * Integration tests for the browser agent. + * + * These tests verify the complete end-to-end flow from CLI prompt through + * browser_agent delegation to MCP/Chrome DevTools and back. Unlike the unit + * tests in packages/core/src/agents/browser/ which mock all MCP components, + * these tests launch real Chrome instances in headless mode. + * + * Tests are skipped on systems without Chrome/Chromium installed. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { TestRig, assertModelHasOutput } from './test-helper.js'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { execSync } from 'node:child_process'; +import { existsSync } from 'node:fs'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +const chromeAvailable = (() => { + try { + if (process.platform === 'darwin') { + execSync( + 'test -d "/Applications/Google Chrome.app" || test -d "/Applications/Chromium.app"', + { + stdio: 'ignore', + }, + ); + } else if (process.platform === 'linux') { + execSync( + 'which google-chrome || which chromium-browser || which chromium', + { stdio: 'ignore' }, + ); + } else if (process.platform === 'win32') { + // Check standard Windows installation paths using Node.js fs + const chromePaths = [ + 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', + 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe', + `${process.env['LOCALAPPDATA'] ?? ''}\\Google\\Chrome\\Application\\chrome.exe`, + ]; + const found = chromePaths.some((p) => existsSync(p)); + if (!found) { + // Fall back to PATH check + execSync('where chrome || where chromium', { stdio: 'ignore' }); + } + } else { + return false; + } + return true; + } catch { + return false; + } +})(); + +describe.skipIf(!chromeAvailable)('browser-agent', () => { + let rig: TestRig; + + beforeEach(() => { + rig = new TestRig(); + }); + + afterEach(async () => await rig.cleanup()); + + it('should navigate to a page and capture accessibility tree', async () => { + rig.setup('browser-navigate-and-snapshot', { + fakeResponsesPath: join( + __dirname, + 'browser-agent.navigate-snapshot.responses', + ), + settings: { + agents: { + browser_agent: { + headless: true, + sessionMode: 'isolated', + }, + }, + }, + }); + + const result = await rig.run({ + args: 'Open https://example.com in the browser and tell me the page title and main content.', + }); + + assertModelHasOutput(result); + + const toolLogs = rig.readToolLogs(); + const browserAgentCall = toolLogs.find( + (t) => t.toolRequest.name === 'browser_agent', + ); + expect( + browserAgentCall, + 'Expected browser_agent to be called', + ).toBeDefined(); + }); + + it('should take screenshots of web pages', async () => { + rig.setup('browser-screenshot', { + fakeResponsesPath: join(__dirname, 'browser-agent.screenshot.responses'), + settings: { + agents: { + browser_agent: { + headless: true, + sessionMode: 'isolated', + }, + }, + }, + }); + + const result = await rig.run({ + args: 'Navigate to https://example.com and take a screenshot.', + }); + + const toolLogs = rig.readToolLogs(); + const browserCalls = toolLogs.filter( + (t) => t.toolRequest.name === 'browser_agent', + ); + expect(browserCalls.length).toBeGreaterThan(0); + + assertModelHasOutput(result); + }); + + it('should interact with page elements', async () => { + rig.setup('browser-interaction', { + fakeResponsesPath: join(__dirname, 'browser-agent.interaction.responses'), + settings: { + agents: { + browser_agent: { + headless: true, + sessionMode: 'isolated', + }, + }, + }, + }); + + const result = await rig.run({ + args: 'Go to https://example.com, find any links on the page, and describe them.', + }); + + const toolLogs = rig.readToolLogs(); + const browserAgentCall = toolLogs.find( + (t) => t.toolRequest.name === 'browser_agent', + ); + expect( + browserAgentCall, + 'Expected browser_agent to be called', + ).toBeDefined(); + + assertModelHasOutput(result); + }); + + it('should clean up browser processes after completion', async () => { + rig.setup('browser-cleanup', { + fakeResponsesPath: join(__dirname, 'browser-agent.cleanup.responses'), + settings: { + agents: { + browser_agent: { + headless: true, + sessionMode: 'isolated', + }, + }, + }, + }); + + await rig.run({ + args: 'Open https://example.com in the browser and check the page title.', + }); + + // Test passes if we reach here, relying on Vitest's timeout mechanism + // to detect hanging browser processes. + }); + + it('should handle multiple browser operations in sequence', async () => { + rig.setup('browser-sequential', { + fakeResponsesPath: join(__dirname, 'browser-agent.sequential.responses'), + settings: { + agents: { + browser_agent: { + headless: true, + sessionMode: 'isolated', + }, + }, + }, + }); + + const result = await rig.run({ + args: 'Navigate to https://example.com, take a snapshot of the accessibility tree, then take a screenshot.', + }); + + const toolLogs = rig.readToolLogs(); + const browserCalls = toolLogs.filter( + (t) => t.toolRequest.name === 'browser_agent', + ); + expect(browserCalls.length).toBeGreaterThan(0); + + // Should successfully complete all operations + assertModelHasOutput(result); + }); +}); diff --git a/integration-tests/extensions-reload.test.ts b/integration-tests/extensions-reload.test.ts index 520076d7c6..9d451cedcf 100644 --- a/integration-tests/extensions-reload.test.ts +++ b/integration-tests/extensions-reload.test.ts @@ -104,7 +104,7 @@ describe('extension reloading', () => { return ( output.includes( 'test-server (from test-extension) - Ready (1 tool)', - ) && output.includes('- hello') + ) && output.includes('- mcp_test-server_hello') ); }, 30000, // 30s timeout @@ -148,7 +148,7 @@ describe('extension reloading', () => { return ( output.includes( 'test-server (from test-extension) - Ready (1 tool)', - ) && output.includes('- goodbye') + ) && output.includes('- mcp_test-server_goodbye') ); }, 30000, diff --git a/integration-tests/hooks-agent-flow.test.ts b/integration-tests/hooks-agent-flow.test.ts index 949770308b..b602737a39 100644 --- a/integration-tests/hooks-agent-flow.test.ts +++ b/integration-tests/hooks-agent-flow.test.ts @@ -182,14 +182,22 @@ describe('Hooks Agent Flow', () => { ); const afterAgentScript = ` - console.log(JSON.stringify({ - decision: 'block', - reason: 'Security policy triggered', - hookSpecificOutput: { - hookEventName: 'AfterAgent', - clearContext: true - } - })); + 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 + } + })); + } `; const afterAgentScriptPath = rig.createScript( 'after_agent_clear.cjs', @@ -198,8 +206,10 @@ describe('Hooks Agent Flow', () => { rig.setup('should process clearContext in AfterAgent hook output', { settings: { - hooks: { + hooksConfig: { enabled: true, + }, + hooks: { BeforeModel: [ { hooks: [ diff --git a/integration-tests/hooks-system.after-agent.responses b/integration-tests/hooks-system.after-agent.responses index 1475070c3d..526c59362d 100644 --- a/integration-tests/hooks-system.after-agent.responses +++ b/integration-tests/hooks-system.after-agent.responses @@ -1,2 +1,3 @@ {"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}]}]} diff --git a/integration-tests/policy-headless-readonly.responses b/integration-tests/policy-headless-readonly.responses new file mode 100644 index 0000000000..35ba546bae --- /dev/null +++ b/integration-tests/policy-headless-readonly.responses @@ -0,0 +1,2 @@ +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I will read the content of the file to identify its"}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":7969,"candidatesTokenCount":11,"totalTokenCount":8061,"promptTokensDetails":[{"modality":"TEXT","tokenCount":7969}],"thoughtsTokenCount":81}},{"candidates":[{"content":{"parts":[{"text":" language.\n"}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":7969,"candidatesTokenCount":14,"totalTokenCount":8064,"promptTokensDetails":[{"modality":"TEXT","tokenCount":7969}],"thoughtsTokenCount":81}},{"candidates":[{"content":{"parts":[{"functionCall":{"name":"read_file","args":{"file_path":"test.txt"}},"thoughtSignature":"EvkCCvYCAb4+9vt8mJ/o45uuuAJtfjaZ3YzkJzqXHZBttRE+Om0ahcr1S5RDFp50KpgHtJtbAH1pwEXampOnDV3WKiWwA+e3Jnyk4CNQegz7ZMKsl55Nem2XDViP8BZKnJVqGmSFuMoKJLFmbVIxKejtWcblfn3httbGsrUUNbHwdPjPHo1qY043lF63g0kWx4v68gPSsJpNhxLrSugKKjiyRFN+J0rOIBHI2S9MdZoHEKhJxvGMtXiJquxmhPmKcNEsn+hMdXAZB39hmrRrGRHDQPVYVPhfJthVc73ufzbn+5KGJpaMQyKY5hqrc2ea8MHz+z6BSx+tFz4NZBff1tJQOiUp09/QndxQRZHSQZr1ALGy0O1Qw4JqsX94x81IxtXqYkSRo3zgm2vl/xPMC5lKlnK5xoKJmoWaHkUNeXs/sopu3/Waf1a5Csoh9ImnKQsW0rJ6GRyDQvky1FwR6Aa98bgfNdcXOPHml/BtghaqRMXTiG6vaPJ8UFs="}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":7969,"candidatesTokenCount":64,"totalTokenCount":8114,"promptTokensDetails":[{"modality":"TEXT","tokenCount":7969}],"thoughtsTokenCount":81}},{"candidates":[{"content":{"parts":[{"text":""}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":7969,"candidatesTokenCount":64,"totalTokenCount":8114,"cachedContentTokenCount":6082,"promptTokensDetails":[{"modality":"TEXT","tokenCount":7969}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":6082}],"thoughtsTokenCount":81}}]} +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"The language of the file is Latin."}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":8054,"candidatesTokenCount":8,"totalTokenCount":8078,"promptTokensDetails":[{"modality":"TEXT","tokenCount":8054}],"thoughtsTokenCount":16}},{"candidates":[{"content":{"parts":[{"text":"","thoughtSignature":"EnIKcAG+Pvb7vnRBJVz3khx1oArQQqTNvXOXkliNQS7NvYw94dq5m+wGKRmSj3egO3GVp7pacnAtLn9NT1ABKBGpa7MpRhiAe3bbPZfkqOuveeyC19LKQ9fzasCywiYqg5k5qSxfjs5okk+O0NLOvTjN/tg="}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":8135,"candidatesTokenCount":8,"totalTokenCount":8159,"promptTokensDetails":[{"modality":"TEXT","tokenCount":8135}],"thoughtsTokenCount":16}}]} diff --git a/integration-tests/policy-headless-shell-allowed.responses b/integration-tests/policy-headless-shell-allowed.responses new file mode 100644 index 0000000000..7c98e60db0 --- /dev/null +++ b/integration-tests/policy-headless-shell-allowed.responses @@ -0,0 +1,2 @@ +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"I will run the requested"}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":7949,"candidatesTokenCount":5,"totalTokenCount":8092,"promptTokensDetails":[{"modality":"TEXT","tokenCount":7949}],"thoughtsTokenCount":138}},{"candidates":[{"content":{"parts":[{"text":" shell command to verify the policy configuration.\n"}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":7949,"candidatesTokenCount":14,"totalTokenCount":8101,"promptTokensDetails":[{"modality":"TEXT","tokenCount":7949}],"thoughtsTokenCount":138}},{"candidates":[{"content":{"parts":[{"functionCall":{"name":"run_shell_command","args":{"command":"echo POLICY_TEST_ECHO_COMMAND","description":"Echo the test string to verify policy settings."}},"thoughtSignature":"EpwFCpkFAb4+9vulXgVj96CAm2eMFbDEGHz9B37GwI8N1KOvu9AHwdYWiita7yS4RKAdeBui22B5320XBaxOtZGnMo2E9pG0Pcus2WsBiecRaHUTxTmhx1BvURevrs+5m4UJeLRGMfP94+ncha4DeIQod3PKBnK8xeIJTyZBFB7+hmHbHvem2VwZh/v14e4fXlpEkkdntJbzrA1nUdctIGdEmdm0sL8PaFnMqWLUnkZvGdfq7ctFt9EYk2HW2SrHVhk3HdsyWhoxNz2MU0sRWzAgiSQY/heSSAbU7Jdgg0RjwB9o3SkCIHxqnVpkH8PQsARwnah5I5s7pW6EHr3D4f1/UVl0n26hyI2xBqF/n4aZKhtX55U4h/DIhxooZa2znstt6BS8vRcdzflFrX7OV86WQxHE4JHjQecP2ciBRimm8pL3Od3pXnRcx32L8JbrWm6dPyWlo5h5uCRy0qXye2+3SuHs5wtxOjD9NETR4TwzqFe+m0zThpxsR1ZKQeKlO7lN/s3pWih/TjbZQEQs9xr72UnlE8ZtJ4bOKj8GNbemvsrbYAO98NzJwvdil0FhblaXmReP1uYjucmLC0jCJHShqNz2KzAkDTvKs4tmio13IuCRjTZ3E5owqCUn7djDqOSDwrg235RIVJkiDIaPlHemOR15lbVQD1VOzytzT8TZLEzTV750oyHq/IhLMQHYixO8jJ2GkVvUp7bxz9oQ4UeTqT5lTF4s40H2Rlkb6trF4hKXoFhzILy1aOJTC9W3fCoop7VJLIMNulgHLWxiq65Uas6sIep87yiD4xLfbGfMm6HS4JTRhPlfxeckn/SzUfu1afg1nAvW3vBlR/YNREf0N28/PnRC08VYqA3mqCRiyPqPWsf3a0jyio0dD9A="}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":7949,"candidatesTokenCount":54,"totalTokenCount":8141,"promptTokensDetails":[{"modality":"TEXT","tokenCount":7949}],"thoughtsTokenCount":138}},{"candidates":[{"content":{"parts":[{"text":""}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":7949,"candidatesTokenCount":54,"totalTokenCount":8141,"cachedContentTokenCount":6082,"promptTokensDetails":[{"modality":"TEXT","tokenCount":7949}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":6082}],"thoughtsTokenCount":138}}]} +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"POLICY_TEST_"}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":8042,"candidatesTokenCount":4,"totalTokenCount":8046,"promptTokensDetails":[{"modality":"TEXT","tokenCount":8042}]}},{"candidates":[{"content":{"parts":[{"text":"ECHO_COMMAND"}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":8042,"candidatesTokenCount":8,"totalTokenCount":8050,"promptTokensDetails":[{"modality":"TEXT","tokenCount":8042}]}},{"candidates":[{"content":{"parts":[{"text":""}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":8180,"candidatesTokenCount":8,"totalTokenCount":8188,"promptTokensDetails":[{"modality":"TEXT","tokenCount":8180}]}}]} diff --git a/integration-tests/policy-headless-shell-denied.responses b/integration-tests/policy-headless-shell-denied.responses new file mode 100644 index 0000000000..4278543b7e --- /dev/null +++ b/integration-tests/policy-headless-shell-denied.responses @@ -0,0 +1,2 @@ +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"**Assessing Command Execution**\n\nOkay, I'm currently assessing the feasibility of executing `echo POLICY_TEST_ECHO_COMMAND` using the `run_shell_command` function. Restrictions are being evaluated; the prompt is specifically geared towards a successful command output: \"POLICY_TEST_ECHO_COMMAND\".\n\n\n","thought":true}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":7949,"totalTokenCount":7949,"promptTokensDetails":[{"modality":"TEXT","tokenCount":7949}]}},{"candidates":[{"content":{"parts":[{"text":"I will execute the requested echo"}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":7949,"candidatesTokenCount":6,"totalTokenCount":8161,"promptTokensDetails":[{"modality":"TEXT","tokenCount":7949}],"thoughtsTokenCount":206}},{"candidates":[{"content":{"parts":[{"text":" command to verify the policy."}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":7949,"candidatesTokenCount":12,"totalTokenCount":8167,"promptTokensDetails":[{"modality":"TEXT","tokenCount":7949}],"thoughtsTokenCount":206}},{"candidates":[{"content":{"parts":[{"functionCall":{"name":"run_shell_command","args":{"description":"Execute the echo command as requested.","command":"echo POLICY_TEST_ECHO_COMMAND"}},"thoughtSignature":"EvkGCvYGAb4+9vucYbmJ8DrNCca9c0C8o4qKQ6V2WnzmT4mbCw8V7s0+2I/PoxrgnsxZJIIRM8y5E4bW7Jbs46GjbJ2cefY9Q3iC45eiGS5Gqvq0eAG04N3GZRwizyDOp+wJlBsaPu1cNB1t6CnMk/ZHDAHEIQUpYfYWmPudbHOQMspGMu3bX23YSI1+Q5vPVdOtM16J3EFbk3dCp+RnPa/8tVC+5AqFlLveuDbJXtrLN9wAyf4SjnPhn9BPfD0bgas3+gF03qRJvWoNcnnJiYxL3DNQtjsAYJ7IWRzciYYZSTm99blD730bn3NzvSObhlHDtb3hFpApYvG396+3prsgJg0Yjef54B4KxHfZaQbE2ndSP5zGrwLtVD5y7XJAYskvhiUqwPFHNVykqroEMzPn8wWQSGvonNR6ezcMIsUV5xwnxZDaPhvrDdIwF4NR1F5DeriJRu27+fwtCApeYkx9mPx4LqnyxOuVsILjzdSPHE6Bqf690VJSXpo67lCN4F3DRRYIuCD4UOlf8V3dvUO6BKjvChDDWnIq7KPoByDQT9VhVlZvS3/nYlkeDuhi0rk2jpByN1NdgD2YSvOlpJcka8JqKQ+lnO/7Swunij2ISUfpL2hkx6TEHjebPU2dBQkub5nSl9J1EhZn4sUGG5r6Zdv1lYcpIcO4ZYeMqZZ4uNvTvSpGdT4Jj1+qS88taKgYq7uN1RgQSTsT5wcpmlubIpgIycNwAIRFvN+DjkQjiUC6hSqdeOx3dc7LWgC/O/+PRog7kuFrD2nzih+oIP0YxXrLA9CMVPlzeAgPUi9b75HAJQ92GRHxfQ163tjZY+4bWmJtcU4NBqGH0x/jLEU9xCojTeh+mZoUDGsb3N+bVcGJftRIet7IBYveD29Z+XHtKhf7s/YIkFW8lgsG8Q0EtNchCxqIQxf9UjYEO52RhCx7i7zScB1knovt2HAotACKqDdPqg18PmpDv8Frw6Y66XeCCJzBCmNcSUTETq3K05gwkU8nyANQtjbJT0wF4LS9h5vPE+Vc7/dGH6pi1TgxWB/n4q1IXfNqilo/h2Pyw01VPsHKthNtKKq1/nSW/WuEU0rimqu7wHplMqU2nwRDCTNE9pPO59RtTHMfUxxd8yEgKBj9L8MiQGM5isIYl/lJtvucee4HD9iLpbYADlrQAlUCd0rg/z+5sQ=="}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":7949,"candidatesTokenCount":50,"totalTokenCount":8205,"promptTokensDetails":[{"modality":"TEXT","tokenCount":7949}],"thoughtsTokenCount":206}},{"candidates":[{"content":{"parts":[{"text":""}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":7949,"candidatesTokenCount":50,"totalTokenCount":8205,"cachedContentTokenCount":6082,"promptTokensDetails":[{"modality":"TEXT","tokenCount":7949}],"cacheTokensDetails":[{"modality":"TEXT","tokenCount":6082}],"thoughtsTokenCount":206}}]} +{"method":"generateContentStream","response":[{"candidates":[{"content":{"parts":[{"text":"AR NAR"}],"role":"model"},"index":0}],"usageMetadata":{"promptTokenCount":8020,"candidatesTokenCount":2,"totalTokenCount":8049,"promptTokensDetails":[{"modality":"TEXT","tokenCount":8020}],"thoughtsTokenCount":27}},{"candidates":[{"content":{"parts":[{"text":"","thoughtSignature":"Er8BCrwBAb4+9vv6KGeMf6yopmPBE/az7Kjdp+Pe5a/R6wgXcyCZzGNwkwKFW3i3ro0j26bRrVeHD1zRfWFTIGdOSZKV6OMPWLqFC/RU6CNJ88B1xY7hbCVwA7EchYPzgd3YZRVNwmFu52j86/9qXf/zaqTFN+WQ0mUESJXh2O2YX8E7imAvxhmRdobVkxvEt4ZX3dW5skDhXHMDZOxbLpX0nkK7cWWS7iEc+qBFP0yinlA/eiG2ZdKpuTiDl76a9ik="}],"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":8226,"candidatesTokenCount":2,"totalTokenCount":8255,"promptTokensDetails":[{"modality":"TEXT","tokenCount":8226}],"thoughtsTokenCount":27}}]} diff --git a/integration-tests/policy-headless.test.ts b/integration-tests/policy-headless.test.ts new file mode 100644 index 0000000000..b6cc14f61c --- /dev/null +++ b/integration-tests/policy-headless.test.ts @@ -0,0 +1,205 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { join } from 'node:path'; +import { TestRig } from './test-helper.js'; + +interface PromptCommand { + prompt: (testFile: string) => string; + tool: string; + command: string; + expectedSuccessResult: string; + expectedFailureResult: string; +} + +const ECHO_PROMPT: PromptCommand = { + command: 'echo', + prompt: () => + `Use the \`echo POLICY_TEST_ECHO_COMMAND\` shell command. On success, ` + + `your final response must ONLY be "POLICY_TEST_ECHO_COMMAND". If the ` + + `command fails output AR NAR and stop.`, + tool: 'run_shell_command', + expectedSuccessResult: 'POLICY_TEST_ECHO_COMMAND', + expectedFailureResult: 'AR NAR', +}; + +const READ_FILE_PROMPT: PromptCommand = { + prompt: (testFile: string) => + `Read the file ${testFile} and tell me what language it is, if the ` + + `read_file tool fails output AR NAR and stop.`, + tool: 'read_file', + command: '', + expectedSuccessResult: 'Latin', + expectedFailureResult: 'AR NAR', +}; + +async function waitForToolCallLog( + rig: TestRig, + tool: string, + command: string, + timeout: number = 15000, +) { + const foundToolCall = await rig.waitForToolCall(tool, timeout, (args) => + args.toLowerCase().includes(command.toLowerCase()), + ); + + expect(foundToolCall).toBe(true); + + const toolLogs = rig + .readToolLogs() + .filter((toolLog) => toolLog.toolRequest.name === tool); + const log = toolLogs.find( + (toolLog) => + !command || + toolLog.toolRequest.args.toLowerCase().includes(command.toLowerCase()), + ); + + // The policy engine should have logged the tool call + expect(log).toBeTruthy(); + return log; +} + +async function verifyToolExecution( + rig: TestRig, + promptCommand: PromptCommand, + result: string, + expectAllowed: boolean, + expectedDenialString?: string, +) { + const log = await waitForToolCallLog( + rig, + promptCommand.tool, + promptCommand.command, + ); + + 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(promptCommand.expectedFailureResult); + } +} + +interface TestCase { + name: string; + responsesFile: string; + promptCommand: PromptCommand; + policyContent?: string; + expectAllowed: boolean; + expectedDenialString?: string; +} + +describe('Policy Engine Headless Mode', () => { + let rig: TestRig; + let testFile: string; + + beforeEach(() => { + rig = new TestRig(); + }); + + afterEach(async () => { + if (rig) { + await rig.cleanup(); + } + }); + + const runTestCase = async (tc: TestCase) => { + const fakeResponsesPath = join(import.meta.dirname, tc.responsesFile); + rig.setup(tc.name, { fakeResponsesPath }); + + testFile = rig.createFile('test.txt', 'Lorem\nIpsum\nDolor\n'); + const args = ['-p', tc.promptCommand.prompt(testFile)]; + + if (tc.policyContent) { + const policyPath = rig.createFile('test-policy.toml', tc.policyContent); + args.push('--policy', policyPath); + } + + const result = await rig.run({ + args, + approvalMode: 'default', + }); + + await verifyToolExecution( + rig, + tc.promptCommand, + result, + tc.expectAllowed, + tc.expectedDenialString, + ); + }; + + const testCases = [ + { + name: 'should deny ASK_USER tools by default in 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', + responsesFile: 'policy-headless-shell-allowed.responses', + promptCommand: ECHO_PROMPT, + policyContent: ` + [[rule]] + toolName = "run_shell_command" + decision = "allow" + priority = 100 + `, + expectAllowed: true, + }, + { + name: 'should allow read-only tools by default in headless mode', + responsesFile: 'policy-headless-readonly.responses', + promptCommand: READ_FILE_PROMPT, + expectAllowed: true, + }, + { + name: 'should allow specific shell commands in policy file', + responsesFile: 'policy-headless-shell-allowed.responses', + promptCommand: ECHO_PROMPT, + policyContent: ` + [[rule]] + toolName = "run_shell_command" + commandPrefix = "${ECHO_PROMPT.command}" + decision = "allow" + priority = 100 + `, + expectAllowed: true, + }, + { + name: 'should deny other shell commands in policy file', + responsesFile: 'policy-headless-shell-denied.responses', + promptCommand: ECHO_PROMPT, + policyContent: ` + [[rule]] + toolName = "run_shell_command" + commandPrefix = "node" + decision = "allow" + priority = 100 + `, + expectAllowed: false, + expectedDenialString: 'Tool execution denied by policy', + }, + ]; + + it.each(testCases)( + '$name', + async (tc) => { + await runTestCase(tc); + }, + // Large timeout for regeneration + process.env['REGENERATE_MODEL_GOLDENS'] === 'true' ? 120000 : undefined, + ); +}); diff --git a/package-lock.json b/package-lock.json index 8f7ed6be5c..85448711c7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@google/gemini-cli", - "version": "0.33.0-nightly.20260228.1ca5c05d0", + "version": "0.34.0-nightly.20260304.28af4e127", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@google/gemini-cli", - "version": "0.33.0-nightly.20260228.1ca5c05d0", + "version": "0.34.0-nightly.20260304.28af4e127", "workspaces": [ "packages/*" ], @@ -5464,13 +5464,6 @@ "node": ">=8" } }, - "node_modules/array-flatten": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", - "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", - "license": "MIT", - "peer": true - }, "node_modules/array-includes": { "version": "3.1.9", "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.9.tgz", @@ -6305,16 +6298,36 @@ "node": ">= 12" } }, - "node_modules/clipboardy": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/clipboardy/-/clipboardy-5.0.0.tgz", - "integrity": "sha512-MQfKHaD09eP80Pev4qBxZLbxJK/ONnqfSYAPlCmPh+7BDboYtO/3BmB6HGzxDIT0SlTRc2tzS8lQqfcdLtZ0Kg==", + "node_modules/clipboard-image": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/clipboard-image/-/clipboard-image-0.1.0.tgz", + "integrity": "sha512-SWk7FgaXLNFld19peQ/rTe0n97lwR1WbkqxV6JKCAOh7U52AKV/PeMFCyt/8IhBdqyDA8rdyewQMKZqvWT5Akg==", "license": "MIT", "dependencies": { - "execa": "^9.6.0", + "run-jxa": "^3.0.0" + }, + "bin": { + "clipboard-image": "cli.js" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/clipboardy": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/clipboardy/-/clipboardy-5.2.1.tgz", + "integrity": "sha512-RWp4E/ivQAzgF4QSWA9sjeW+Bjo+U2SvebkDhNIfO7y65eGdXPUxMTdIKYsn+bxM3ItPHGm3e68Bv3fgQ3mARw==", + "license": "MIT", + "dependencies": { + "clipboard-image": "^0.1.0", + "execa": "^9.6.1", "is-wayland": "^0.1.0", "is-wsl": "^3.1.0", - "is64bit": "^2.0.0" + "is64bit": "^2.0.0", + "powershell-utils": "^0.2.0" }, "engines": { "node": ">=20" @@ -6570,7 +6583,6 @@ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", "license": "MIT", - "peer": true, "dependencies": { "safe-buffer": "5.2.1" }, @@ -6740,6 +6752,33 @@ "node": ">= 8" } }, + "node_modules/crypto-random-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-4.0.0.tgz", + "integrity": "sha512-x8dy3RnvYdlUcPOjkEHqozhiwzKNSq7GcPuXFbnyMOCHxX8V3OgIg/pYuabl2sbUPfIJaeAQB7PMOK8DFIdoRA==", + "license": "MIT", + "dependencies": { + "type-fest": "^1.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/crypto-random-string/node_modules/type-fest": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-1.4.0.tgz", + "integrity": "sha512-yGSza74xk0UG8k+pLh5oeoYirvIiWo5t0/o3zHHAO2tRDiZcxWP7fywNlXhqb6/r6sWvwi+RsyQMWhVLe4BVuA==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/css-select": { "version": "5.2.2", "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.2.2.tgz", @@ -8430,9 +8469,9 @@ } }, "node_modules/execa": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-9.6.0.tgz", - "integrity": "sha512-jpWzZ1ZhwUmeWRhS7Qv3mhpOhLfwI+uAX4e5fOcXqwMR7EcJ0pj2kV1CVzHVMX/LphnKWD3LObjZCoJ71lKpHw==", + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-9.6.1.tgz", + "integrity": "sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA==", "license": "MIT", "dependencies": { "@sindresorhus/merge-streams": "^4.0.0", @@ -8550,36 +8589,15 @@ "express": ">= 4.11" } }, - "node_modules/express/node_modules/cookie": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", - "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.6" - } - }, "node_modules/express/node_modules/debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "license": "MIT", - "peer": true, "dependencies": { "ms": "2.0.0" } }, - "node_modules/express/node_modules/statuses": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", - "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.8" - } - }, "node_modules/extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", @@ -8839,7 +8857,6 @@ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "license": "MIT", - "peer": true, "dependencies": { "ms": "2.0.0" } @@ -8848,18 +8865,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", - "license": "MIT", - "peer": true - }, - "node_modules/finalhandler/node_modules/statuses": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", - "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.8" - } + "license": "MIT" }, "node_modules/find-up": { "version": "5.0.0", @@ -11735,6 +11741,21 @@ "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", "license": "ISC" }, + "node_modules/macos-version": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/macos-version/-/macos-version-6.0.0.tgz", + "integrity": "sha512-O2S8voA+pMfCHhBn/TIYDXzJ1qNHpPDU32oFxglKnVdJABiYYITt45oLkV9yhwA3E2FDwn3tQqUFrTsr1p3sBQ==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -11870,6 +11891,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "license": "MIT" + }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", @@ -13420,6 +13447,18 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/powershell-utils": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/powershell-utils/-/powershell-utils-0.2.0.tgz", + "integrity": "sha512-ZlsFlG7MtSFCoc5xreOvBAozCJ6Pf06opgJjh9ONEv418xpZSAzNjstD36C6+JwOnfSqOW/9uDkqKjezTdxZhw==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -14302,6 +14341,107 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/run-jxa": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/run-jxa/-/run-jxa-3.0.0.tgz", + "integrity": "sha512-4f2CrY7H+sXkKXJn/cE6qRA3z+NMVO7zvlZ/nUV0e62yWftpiLAfw5eV9ZdomzWd2TXWwEIiGjAT57+lWIzzvA==", + "license": "MIT", + "dependencies": { + "execa": "^5.1.1", + "macos-version": "^6.0.0", + "subsume": "^4.0.0", + "type-fest": "^2.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/run-jxa/node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/run-jxa/node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/run-jxa/node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "license": "Apache-2.0", + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/run-jxa/node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "license": "MIT", + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/run-jxa/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/run-jxa/node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/run-jxa/node_modules/type-fest": { + "version": "2.19.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-2.19.0.tgz", + "integrity": "sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", @@ -15238,6 +15378,34 @@ "integrity": "sha512-PdHt7hHUJKxvTCgbKX9C1V/ftOcjJQgz8BZwNfV5c4B6dcGqlpelTbJ999jBGZ2jYiPAwcX5dP6oBwVlBlUbxw==", "license": "MIT" }, + "node_modules/subsume": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/subsume/-/subsume-4.0.0.tgz", + "integrity": "sha512-BWnYJElmHbYZ/zKevy+TG+SsyoFCmRPDHJbR1MzLxkPOv1Jp/4hGhVUtP98s+wZBsBsHwCXvPTP0x287/WMjGg==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^5.0.0", + "unique-string": "^3.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/subsume/node_modules/escape-string-regexp": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", + "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/superagent": { "version": "10.2.3", "resolved": "https://registry.npmjs.org/superagent/-/superagent-10.2.3.tgz", @@ -16220,6 +16388,21 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/unique-string": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-3.0.0.tgz", + "integrity": "sha512-VGXBUVwxKMBUznyffQweQABPRRW1vHZAbadFZud4pLFAqRGvv/96vafgjWFqzourzr8YonlQiPgH0YCJfawoGQ==", + "license": "MIT", + "dependencies": { + "crypto-random-string": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/universal-user-agent": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-7.0.3.tgz", @@ -16286,16 +16469,6 @@ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", "license": "MIT" }, - "node_modules/utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 0.4.0" - } - }, "node_modules/uuid": { "version": "9.0.1", "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", @@ -17130,7 +17303,7 @@ }, "packages/a2a-server": { "name": "@google/gemini-cli-a2a-server", - "version": "0.33.0-nightly.20260228.1ca5c05d0", + "version": "0.34.0-nightly.20260304.28af4e127", "dependencies": { "@a2a-js/sdk": "^0.3.8", "@google-cloud/storage": "^7.16.0", @@ -17188,7 +17361,7 @@ }, "packages/cli": { "name": "@google/gemini-cli", - "version": "0.33.0-nightly.20260228.1ca5c05d0", + "version": "0.34.0-nightly.20260304.28af4e127", "license": "Apache-2.0", "dependencies": { "@agentclientprotocol/sdk": "^0.12.0", @@ -17200,7 +17373,7 @@ "ansi-regex": "^6.2.2", "chalk": "^4.1.2", "cli-spinners": "^2.9.2", - "clipboardy": "^5.0.0", + "clipboardy": "~5.2.0", "color-convert": "^2.0.1", "command-exists": "^1.2.9", "comment-json": "^4.2.5", @@ -17271,7 +17444,7 @@ }, "packages/core": { "name": "@google/gemini-cli-core", - "version": "0.33.0-nightly.20260228.1ca5c05d0", + "version": "0.34.0-nightly.20260304.28af4e127", "license": "Apache-2.0", "dependencies": { "@a2a-js/sdk": "^0.3.8", @@ -17536,7 +17709,7 @@ }, "packages/devtools": { "name": "@google/gemini-cli-devtools", - "version": "0.33.0-nightly.20260228.1ca5c05d0", + "version": "0.34.0-nightly.20260304.28af4e127", "license": "Apache-2.0", "dependencies": { "ws": "^8.16.0" @@ -17551,7 +17724,7 @@ }, "packages/sdk": { "name": "@google/gemini-cli-sdk", - "version": "0.33.0-nightly.20260228.1ca5c05d0", + "version": "0.34.0-nightly.20260304.28af4e127", "license": "Apache-2.0", "dependencies": { "@google/gemini-cli-core": "file:../core", @@ -17568,7 +17741,7 @@ }, "packages/test-utils": { "name": "@google/gemini-cli-test-utils", - "version": "0.33.0-nightly.20260228.1ca5c05d0", + "version": "0.34.0-nightly.20260304.28af4e127", "license": "Apache-2.0", "dependencies": { "@google/gemini-cli-core": "file:../core", @@ -17585,7 +17758,7 @@ }, "packages/vscode-ide-companion": { "name": "gemini-cli-vscode-ide-companion", - "version": "0.33.0-nightly.20260228.1ca5c05d0", + "version": "0.34.0-nightly.20260304.28af4e127", "license": "LICENSE", "dependencies": { "@modelcontextprotocol/sdk": "^1.23.0", diff --git a/package.json b/package.json index b1053f5b8a..8d931c1462 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@google/gemini-cli", - "version": "0.33.0-nightly.20260228.1ca5c05d0", + "version": "0.34.0-nightly.20260304.28af4e127", "engines": { "node": ">=20.0.0" }, @@ -14,7 +14,7 @@ "url": "git+https://github.com/google-gemini/gemini-cli.git" }, "config": { - "sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.33.0-nightly.20260228.1ca5c05d0" + "sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.34.0-nightly.20260304.28af4e127" }, "scripts": { "start": "cross-env NODE_ENV=development node scripts/start.js", diff --git a/packages/a2a-server/package.json b/packages/a2a-server/package.json index 0428a84311..b70ea8986a 100644 --- a/packages/a2a-server/package.json +++ b/packages/a2a-server/package.json @@ -1,6 +1,6 @@ { "name": "@google/gemini-cli-a2a-server", - "version": "0.33.0-nightly.20260228.1ca5c05d0", + "version": "0.34.0-nightly.20260304.28af4e127", "description": "Gemini CLI A2A Server", "repository": { "type": "git", diff --git a/packages/a2a-server/src/agent/task.ts b/packages/a2a-server/src/agent/task.ts index c969e601c3..ef15a907e6 100644 --- a/packages/a2a-server/src/agent/task.ts +++ b/packages/a2a-server/src/agent/task.ts @@ -28,6 +28,9 @@ import { type Config, type UserTierId, type ToolLiveOutput, + type AnsiLine, + type AnsiOutput, + type AnsiToken, isSubagentProgress, EDIT_TOOL_NAMES, processRestorableToolCalls, @@ -344,10 +347,15 @@ export class Task { outputAsText = outputChunk; } else if (isSubagentProgress(outputChunk)) { outputAsText = JSON.stringify(outputChunk); - } else { - outputAsText = outputChunk - .map((line) => line.map((token) => token.text).join('')) + } else if (Array.isArray(outputChunk)) { + const ansiOutput: AnsiOutput = outputChunk; + outputAsText = ansiOutput + .map((line: AnsiLine) => + line.map((token: AnsiToken) => token.text).join(''), + ) .join('\n'); + } else { + outputAsText = String(outputChunk); } logger.info( @@ -824,7 +832,9 @@ 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; diff --git a/packages/a2a-server/src/config/config.test.ts b/packages/a2a-server/src/config/config.test.ts index c676e46289..ee63df36f7 100644 --- a/packages/a2a-server/src/config/config.test.ts +++ b/packages/a2a-server/src/config/config.test.ts @@ -16,6 +16,9 @@ import { ExperimentFlags, fetchAdminControlsOnce, type FetchAdminControlsResponse, + AuthType, + isHeadlessMode, + FatalAuthenticationError, } from '@google/gemini-cli-core'; // Mock dependencies @@ -50,6 +53,7 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => { startupProfiler: { flush: vi.fn(), }, + isHeadlessMode: vi.fn().mockReturnValue(false), FileDiscoveryService: vi.fn(), getCodeAssistServer: vi.fn(), fetchAdminControlsOnce: vi.fn(), @@ -62,6 +66,7 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => { vi.mock('../utils/logger.js', () => ({ logger: { info: vi.fn(), + warn: vi.fn(), error: vi.fn(), }, })); @@ -73,12 +78,11 @@ describe('loadConfig', () => { beforeEach(() => { vi.clearAllMocks(); - process.env['GEMINI_API_KEY'] = 'test-key'; + vi.stubEnv('GEMINI_API_KEY', 'test-key'); }); afterEach(() => { - delete process.env['CUSTOM_IGNORE_FILE_PATHS']; - delete process.env['GEMINI_API_KEY']; + vi.unstubAllEnvs(); }); describe('admin settings overrides', () => { @@ -199,7 +203,7 @@ describe('loadConfig', () => { it('should set customIgnoreFilePaths when CUSTOM_IGNORE_FILE_PATHS env var is present', async () => { const testPath = '/tmp/ignore'; - process.env['CUSTOM_IGNORE_FILE_PATHS'] = testPath; + vi.stubEnv('CUSTOM_IGNORE_FILE_PATHS', testPath); const config = await loadConfig(mockSettings, mockExtensionLoader, taskId); // eslint-disable-next-line @typescript-eslint/no-explicit-any expect((config as any).fileFiltering.customIgnoreFilePaths).toEqual([ @@ -224,7 +228,7 @@ describe('loadConfig', () => { it('should merge customIgnoreFilePaths from settings and env var', async () => { const envPath = '/env/ignore'; const settingsPath = '/settings/ignore'; - process.env['CUSTOM_IGNORE_FILE_PATHS'] = envPath; + vi.stubEnv('CUSTOM_IGNORE_FILE_PATHS', envPath); const settings: Settings = { fileFiltering: { customIgnoreFilePaths: [settingsPath], @@ -240,7 +244,7 @@ describe('loadConfig', () => { it('should split CUSTOM_IGNORE_FILE_PATHS using system delimiter', async () => { const paths = ['/path/one', '/path/two']; - process.env['CUSTOM_IGNORE_FILE_PATHS'] = paths.join(path.delimiter); + vi.stubEnv('CUSTOM_IGNORE_FILE_PATHS', paths.join(path.delimiter)); const config = await loadConfig(mockSettings, mockExtensionLoader, taskId); // eslint-disable-next-line @typescript-eslint/no-explicit-any expect((config as any).fileFiltering.customIgnoreFilePaths).toEqual(paths); @@ -254,7 +258,7 @@ describe('loadConfig', () => { it('should initialize FileDiscoveryService with correct options', async () => { const testPath = '/tmp/ignore'; - process.env['CUSTOM_IGNORE_FILE_PATHS'] = testPath; + vi.stubEnv('CUSTOM_IGNORE_FILE_PATHS', testPath); const settings: Settings = { fileFiltering: { respectGitIgnore: false, @@ -311,5 +315,219 @@ describe('loadConfig', () => { }), ); }); + + describe('interactivity', () => { + it('should set interactive true when not headless', async () => { + vi.mocked(isHeadlessMode).mockReturnValue(false); + await loadConfig(mockSettings, mockExtensionLoader, taskId); + expect(Config).toHaveBeenCalledWith( + expect.objectContaining({ + interactive: true, + enableInteractiveShell: true, + }), + ); + }); + + it('should set interactive false when headless', async () => { + vi.mocked(isHeadlessMode).mockReturnValue(true); + await loadConfig(mockSettings, mockExtensionLoader, taskId); + expect(Config).toHaveBeenCalledWith( + expect.objectContaining({ + interactive: false, + enableInteractiveShell: false, + }), + ); + }); + }); + + describe('authentication fallback', () => { + beforeEach(() => { + vi.stubEnv('USE_CCPA', 'true'); + vi.stubEnv('GEMINI_API_KEY', ''); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it('should fall back to COMPUTE_ADC in Cloud Shell if LOGIN_WITH_GOOGLE fails', async () => { + vi.stubEnv('CLOUD_SHELL', 'true'); + vi.mocked(isHeadlessMode).mockReturnValue(false); + const refreshAuthMock = vi.fn().mockImplementation((authType) => { + if (authType === AuthType.LOGIN_WITH_GOOGLE) { + throw new FatalAuthenticationError('Non-interactive session'); + } + return Promise.resolve(); + }); + + // Update the mock implementation for this test + vi.mocked(Config).mockImplementation( + (params: unknown) => + ({ + ...(params as object), + initialize: vi.fn(), + waitForMcpInit: vi.fn(), + refreshAuth: refreshAuthMock, + getExperiments: vi.fn().mockReturnValue({ flags: {} }), + getRemoteAdminSettings: vi.fn(), + setRemoteAdminSettings: vi.fn(), + }) as unknown as Config, + ); + + await loadConfig(mockSettings, mockExtensionLoader, taskId); + + expect(refreshAuthMock).toHaveBeenCalledWith( + AuthType.LOGIN_WITH_GOOGLE, + ); + expect(refreshAuthMock).toHaveBeenCalledWith(AuthType.COMPUTE_ADC); + }); + + it('should not fall back to COMPUTE_ADC if not in cloud environment', async () => { + vi.mocked(isHeadlessMode).mockReturnValue(false); + const refreshAuthMock = vi.fn().mockImplementation((authType) => { + if (authType === AuthType.LOGIN_WITH_GOOGLE) { + throw new FatalAuthenticationError('Non-interactive session'); + } + return Promise.resolve(); + }); + + vi.mocked(Config).mockImplementation( + (params: unknown) => + ({ + ...(params as object), + initialize: vi.fn(), + waitForMcpInit: vi.fn(), + refreshAuth: refreshAuthMock, + getExperiments: vi.fn().mockReturnValue({ flags: {} }), + getRemoteAdminSettings: vi.fn(), + setRemoteAdminSettings: vi.fn(), + }) as unknown as Config, + ); + + await expect( + loadConfig(mockSettings, mockExtensionLoader, taskId), + ).rejects.toThrow('Non-interactive session'); + + expect(refreshAuthMock).toHaveBeenCalledWith( + AuthType.LOGIN_WITH_GOOGLE, + ); + expect(refreshAuthMock).not.toHaveBeenCalledWith(AuthType.COMPUTE_ADC); + }); + + it('should skip LOGIN_WITH_GOOGLE and use COMPUTE_ADC directly in headless Cloud Shell', async () => { + vi.stubEnv('CLOUD_SHELL', 'true'); + vi.mocked(isHeadlessMode).mockReturnValue(true); + + const refreshAuthMock = vi.fn().mockResolvedValue(undefined); + + vi.mocked(Config).mockImplementation( + (params: unknown) => + ({ + ...(params as object), + initialize: vi.fn(), + waitForMcpInit: vi.fn(), + refreshAuth: refreshAuthMock, + getExperiments: vi.fn().mockReturnValue({ flags: {} }), + getRemoteAdminSettings: vi.fn(), + setRemoteAdminSettings: vi.fn(), + }) as unknown as Config, + ); + + await loadConfig(mockSettings, mockExtensionLoader, taskId); + + expect(refreshAuthMock).not.toHaveBeenCalledWith( + AuthType.LOGIN_WITH_GOOGLE, + ); + expect(refreshAuthMock).toHaveBeenCalledWith(AuthType.COMPUTE_ADC); + }); + + it('should skip LOGIN_WITH_GOOGLE and use COMPUTE_ADC directly if GEMINI_CLI_USE_COMPUTE_ADC is true', async () => { + vi.stubEnv('GEMINI_CLI_USE_COMPUTE_ADC', 'true'); + vi.mocked(isHeadlessMode).mockReturnValue(false); // Even if not headless + + const refreshAuthMock = vi.fn().mockResolvedValue(undefined); + + vi.mocked(Config).mockImplementation( + (params: unknown) => + ({ + ...(params as object), + initialize: vi.fn(), + waitForMcpInit: vi.fn(), + refreshAuth: refreshAuthMock, + getExperiments: vi.fn().mockReturnValue({ flags: {} }), + getRemoteAdminSettings: vi.fn(), + setRemoteAdminSettings: vi.fn(), + }) as unknown as Config, + ); + + await loadConfig(mockSettings, mockExtensionLoader, taskId); + + expect(refreshAuthMock).not.toHaveBeenCalledWith( + AuthType.LOGIN_WITH_GOOGLE, + ); + expect(refreshAuthMock).toHaveBeenCalledWith(AuthType.COMPUTE_ADC); + }); + + it('should throw FatalAuthenticationError in headless mode if no ADC fallback available', async () => { + vi.mocked(isHeadlessMode).mockReturnValue(true); + + const refreshAuthMock = vi.fn().mockResolvedValue(undefined); + + vi.mocked(Config).mockImplementation( + (params: unknown) => + ({ + ...(params as object), + initialize: vi.fn(), + waitForMcpInit: vi.fn(), + refreshAuth: refreshAuthMock, + getExperiments: vi.fn().mockReturnValue({ flags: {} }), + getRemoteAdminSettings: vi.fn(), + setRemoteAdminSettings: vi.fn(), + }) as unknown as Config, + ); + + await expect( + loadConfig(mockSettings, mockExtensionLoader, taskId), + ).rejects.toThrow( + 'Interactive terminal required for LOGIN_WITH_GOOGLE. Run in an interactive terminal or set GEMINI_CLI_USE_COMPUTE_ADC=true to use Application Default Credentials.', + ); + + expect(refreshAuthMock).not.toHaveBeenCalled(); + }); + + it('should include both original and fallback error when COMPUTE_ADC fallback fails', async () => { + vi.stubEnv('CLOUD_SHELL', 'true'); + vi.mocked(isHeadlessMode).mockReturnValue(false); + + const refreshAuthMock = vi.fn().mockImplementation((authType) => { + if (authType === AuthType.LOGIN_WITH_GOOGLE) { + throw new FatalAuthenticationError('OAuth failed'); + } + if (authType === AuthType.COMPUTE_ADC) { + throw new Error('ADC failed'); + } + return Promise.resolve(); + }); + + vi.mocked(Config).mockImplementation( + (params: unknown) => + ({ + ...(params as object), + initialize: vi.fn(), + waitForMcpInit: vi.fn(), + refreshAuth: refreshAuthMock, + getExperiments: vi.fn().mockReturnValue({ flags: {} }), + getRemoteAdminSettings: vi.fn(), + setRemoteAdminSettings: vi.fn(), + }) as unknown as Config, + ); + + await expect( + loadConfig(mockSettings, mockExtensionLoader, taskId), + ).rejects.toThrow( + 'OAuth failed. Fallback to COMPUTE_ADC also failed: ADC failed', + ); + }); + }); }); }); diff --git a/packages/a2a-server/src/config/config.ts b/packages/a2a-server/src/config/config.ts index f3100bce4d..5b6757701d 100644 --- a/packages/a2a-server/src/config/config.ts +++ b/packages/a2a-server/src/config/config.ts @@ -23,6 +23,9 @@ import { fetchAdminControlsOnce, getCodeAssistServer, ExperimentFlags, + isHeadlessMode, + FatalAuthenticationError, + isCloudShell, type TelemetryTarget, type ConfigParameters, type ExtensionLoader, @@ -103,8 +106,8 @@ export async function loadConfig( trustedFolder: true, extensionLoader, checkpointing, - interactive: true, - enableInteractiveShell: true, + interactive: !isHeadlessMode(), + enableInteractiveShell: !isHeadlessMode(), ptyInfo: 'auto', }; @@ -117,7 +120,6 @@ export async function loadConfig( await loadServerHierarchicalMemory( workspaceDir, [workspaceDir], - false, fileService, extensionLoader, folderTrust, @@ -255,7 +257,61 @@ async function refreshAuthentication( `[${logPrefix}] USE_CCPA env var is true but unable to resolve GOOGLE_APPLICATION_CREDENTIALS file path ${adcFilePath}. Error ${e}`, ); } - await config.refreshAuth(AuthType.LOGIN_WITH_GOOGLE); + + const useComputeAdc = process.env['GEMINI_CLI_USE_COMPUTE_ADC'] === 'true'; + const isHeadless = isHeadlessMode(); + const shouldSkipOauth = isHeadless || useComputeAdc; + + if (shouldSkipOauth) { + if (isCloudShell() || useComputeAdc) { + logger.info( + `[${logPrefix}] Skipping LOGIN_WITH_GOOGLE due to ${isHeadless ? 'headless mode' : 'GEMINI_CLI_USE_COMPUTE_ADC'}. Attempting COMPUTE_ADC.`, + ); + try { + await config.refreshAuth(AuthType.COMPUTE_ADC); + logger.info(`[${logPrefix}] COMPUTE_ADC successful.`); + } catch (adcError) { + const adcMessage = + adcError instanceof Error ? adcError.message : String(adcError); + throw new FatalAuthenticationError( + `COMPUTE_ADC failed: ${adcMessage}. (Skipped LOGIN_WITH_GOOGLE due to ${isHeadless ? 'headless mode' : 'GEMINI_CLI_USE_COMPUTE_ADC'})`, + ); + } + } else { + throw new FatalAuthenticationError( + `Interactive terminal required for LOGIN_WITH_GOOGLE. Run in an interactive terminal or set GEMINI_CLI_USE_COMPUTE_ADC=true to use Application Default Credentials.`, + ); + } + } else { + try { + await config.refreshAuth(AuthType.LOGIN_WITH_GOOGLE); + } catch (e) { + if ( + e instanceof FatalAuthenticationError && + (isCloudShell() || useComputeAdc) + ) { + logger.warn( + `[${logPrefix}] LOGIN_WITH_GOOGLE failed. Attempting COMPUTE_ADC fallback.`, + ); + try { + await config.refreshAuth(AuthType.COMPUTE_ADC); + logger.info(`[${logPrefix}] COMPUTE_ADC fallback successful.`); + } catch (adcError) { + logger.error( + `[${logPrefix}] COMPUTE_ADC fallback failed: ${adcError}`, + ); + const originalMessage = e instanceof Error ? e.message : String(e); + const adcMessage = + adcError instanceof Error ? adcError.message : String(adcError); + throw new FatalAuthenticationError( + `${originalMessage}. Fallback to COMPUTE_ADC also failed: ${adcMessage}`, + ); + } + } else { + throw e; + } + } + } logger.info( `[${logPrefix}] GOOGLE_CLOUD_PROJECT: ${process.env['GOOGLE_CLOUD_PROJECT']}`, ); diff --git a/packages/cli/package.json b/packages/cli/package.json index f4fd2f7bd1..cc561eeb8c 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@google/gemini-cli", - "version": "0.33.0-nightly.20260228.1ca5c05d0", + "version": "0.34.0-nightly.20260304.28af4e127", "description": "Gemini CLI", "license": "Apache-2.0", "repository": { @@ -26,7 +26,7 @@ "dist" ], "config": { - "sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.33.0-nightly.20260228.1ca5c05d0" + "sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.34.0-nightly.20260304.28af4e127" }, "dependencies": { "@agentclientprotocol/sdk": "^0.12.0", @@ -38,7 +38,7 @@ "ansi-regex": "^6.2.2", "chalk": "^4.1.2", "cli-spinners": "^2.9.2", - "clipboardy": "^5.0.0", + "clipboardy": "~5.2.0", "color-convert": "^2.0.1", "command-exists": "^1.2.9", "comment-json": "^4.2.5", diff --git a/packages/cli/src/zed-integration/zedIntegration.test.ts b/packages/cli/src/acp/acpClient.test.ts similarity index 78% rename from packages/cli/src/zed-integration/zedIntegration.test.ts rename to packages/cli/src/acp/acpClient.test.ts index e8e5355dc0..0922e3a510 100644 --- a/packages/cli/src/zed-integration/zedIntegration.test.ts +++ b/packages/cli/src/acp/acpClient.test.ts @@ -14,7 +14,8 @@ import { type Mock, type Mocked, } from 'vitest'; -import { GeminiAgent, Session } from './zedIntegration.js'; +import { GeminiAgent, Session } from './acpClient.js'; +import type { CommandHandler } from './commandHandler.js'; import * as acp from '@agentclientprotocol/sdk'; import { AuthType, @@ -26,6 +27,7 @@ import { type Config, type MessageBus, LlmRole, + type GitService, } from '@google/gemini-cli-core'; import { SettingScope, @@ -62,7 +64,33 @@ vi.mock('node:path', async (importOriginal) => { }; }); -// Mock ReadManyFilesTool +vi.mock('../ui/commands/memoryCommand.js', () => ({ + memoryCommand: { + name: 'memory', + action: vi.fn(), + }, +})); + +vi.mock('../ui/commands/extensionsCommand.js', () => ({ + extensionsCommand: vi.fn().mockReturnValue({ + name: 'extensions', + action: vi.fn(), + }), +})); + +vi.mock('../ui/commands/restoreCommand.js', () => ({ + restoreCommand: vi.fn().mockReturnValue({ + name: 'restore', + action: vi.fn(), + }), +})); + +vi.mock('../ui/commands/initCommand.js', () => ({ + initCommand: { + name: 'init', + action: vi.fn(), + }, +})); vi.mock( '@google/gemini-cli-core', async ( @@ -145,6 +173,9 @@ describe('GeminiAgent', () => { }), getApprovalMode: vi.fn().mockReturnValue('default'), isPlanEnabled: vi.fn().mockReturnValue(false), + getGemini31LaunchedSync: vi.fn().mockReturnValue(false), + getHasAccessToPreviewModel: vi.fn().mockReturnValue(false), + getCheckpointingEnabled: vi.fn().mockReturnValue(false), } as unknown as Mocked>>; mockSettings = { merged: { @@ -177,7 +208,16 @@ describe('GeminiAgent', () => { }); expect(response.protocolVersion).toBe(acp.PROTOCOL_VERSION); - expect(response.authMethods).toHaveLength(3); + expect(response.authMethods).toHaveLength(4); + const gatewayAuth = response.authMethods?.find( + (m) => m.id === AuthType.GATEWAY, + ); + expect(gatewayAuth?._meta).toEqual({ + gateway: { + protocol: 'google', + restartRequired: 'false', + }, + }); const geminiAuth = response.authMethods?.find( (m) => m.id === AuthType.USE_GEMINI, ); @@ -197,6 +237,8 @@ describe('GeminiAgent', () => { expect(mockConfig.refreshAuth).toHaveBeenCalledWith( AuthType.LOGIN_WITH_GOOGLE, undefined, + undefined, + undefined, ); expect(mockSettings.setValue).toHaveBeenCalledWith( SettingScope.User, @@ -216,6 +258,8 @@ describe('GeminiAgent', () => { expect(mockConfig.refreshAuth).toHaveBeenCalledWith( AuthType.USE_GEMINI, 'test-api-key', + undefined, + undefined, ); expect(mockSettings.setValue).toHaveBeenCalledWith( SettingScope.User, @@ -224,7 +268,47 @@ describe('GeminiAgent', () => { ); }); + it('should authenticate correctly with gateway method', async () => { + await agent.authenticate({ + methodId: AuthType.GATEWAY, + _meta: { + gateway: { + baseUrl: 'https://example.com', + headers: { Authorization: 'Bearer token' }, + }, + }, + } as unknown as acp.AuthenticateRequest); + + expect(mockConfig.refreshAuth).toHaveBeenCalledWith( + AuthType.GATEWAY, + undefined, + 'https://example.com', + { Authorization: 'Bearer token' }, + ); + expect(mockSettings.setValue).toHaveBeenCalledWith( + SettingScope.User, + 'security.auth.selectedType', + AuthType.GATEWAY, + ); + }); + + it('should throw acp.RequestError when gateway payload is malformed', async () => { + await expect( + agent.authenticate({ + methodId: AuthType.GATEWAY, + _meta: { + gateway: { + // Invalid baseUrl + baseUrl: 123, + headers: { Authorization: 'Bearer token' }, + }, + }, + } as unknown as acp.AuthenticateRequest), + ).rejects.toThrow(/Malformed gateway payload/); + }); + it('should create a new session', async () => { + vi.useFakeTimers(); mockConfig.getContentGeneratorConfig = vi.fn().mockReturnValue({ apiKey: 'test-key', }); @@ -237,6 +321,17 @@ describe('GeminiAgent', () => { expect(loadCliConfig).toHaveBeenCalled(); expect(mockConfig.initialize).toHaveBeenCalled(); expect(mockConfig.getGeminiClient).toHaveBeenCalled(); + + // Verify deferred call + await vi.runAllTimersAsync(); + expect(mockConnection.sessionUpdate).toHaveBeenCalledWith( + expect.objectContaining({ + update: expect.objectContaining({ + sessionUpdate: 'available_commands_update', + }), + }), + ); + vi.useRealTimers(); }); it('should return modes without plan mode when plan is disabled', async () => { @@ -263,6 +358,38 @@ describe('GeminiAgent', () => { ], currentModeId: 'default', }); + expect(response.models).toEqual({ + availableModels: expect.arrayContaining([ + expect.objectContaining({ + modelId: 'auto-gemini-2.5', + name: 'Auto (Gemini 2.5)', + }), + ]), + currentModelId: 'gemini-pro', + }); + }); + + it('should include preview models when user has access', async () => { + mockConfig.getHasAccessToPreviewModel = vi.fn().mockReturnValue(true); + mockConfig.getGemini31LaunchedSync = vi.fn().mockReturnValue(true); + + const response = await agent.newSession({ + cwd: '/tmp', + mcpServers: [], + }); + + expect(response.models?.availableModels).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + modelId: 'auto-gemini-3', + name: expect.stringContaining('Auto'), + }), + expect.objectContaining({ + modelId: 'gemini-3.1-pro-preview', + name: 'gemini-3.1-pro-preview', + }), + ]), + ); }); it('should return modes with plan mode when plan is enabled', async () => { @@ -290,6 +417,15 @@ describe('GeminiAgent', () => { ], currentModeId: 'plan', }); + expect(response.models).toEqual({ + availableModels: expect.arrayContaining([ + expect.objectContaining({ + modelId: 'auto-gemini-2.5', + name: 'Auto (Gemini 2.5)', + }), + ]), + currentModelId: 'gemini-pro', + }); }); it('should fail session creation if Gemini API key is missing', async () => { @@ -439,6 +575,32 @@ describe('GeminiAgent', () => { }), ).rejects.toThrow('Session not found: unknown'); }); + + it('should delegate setModel to session (unstable)', async () => { + await agent.newSession({ cwd: '/tmp', mcpServers: [] }); + const session = ( + agent as unknown as { sessions: Map } + ).sessions.get('test-session-id'); + if (!session) throw new Error('Session not found'); + session.setModel = vi.fn().mockReturnValue({}); + + const result = await agent.unstable_setSessionModel({ + sessionId: 'test-session-id', + modelId: 'gemini-2.0-pro-exp', + }); + + expect(session.setModel).toHaveBeenCalledWith('gemini-2.0-pro-exp'); + expect(result).toEqual({}); + }); + + it('should throw error when setting model on non-existent session (unstable)', async () => { + await expect( + agent.unstable_setSessionModel({ + sessionId: 'unknown', + modelId: 'gemini-2.0-pro-exp', + }), + ).rejects.toThrow('Session not found: unknown'); + }); }); describe('Session', () => { @@ -477,6 +639,7 @@ describe('Session', () => { getModel: vi.fn().mockReturnValue('gemini-pro'), getActiveModel: vi.fn().mockReturnValue('gemini-pro'), getToolRegistry: vi.fn().mockReturnValue(mockToolRegistry), + getMcpServers: vi.fn(), getFileService: vi.fn().mockReturnValue({ shouldIgnoreFile: vi.fn().mockReturnValue(false), }), @@ -486,7 +649,10 @@ describe('Session', () => { getDebugMode: vi.fn().mockReturnValue(false), getMessageBus: vi.fn().mockReturnValue(mockMessageBus), setApprovalMode: vi.fn(), + setModel: vi.fn(), isPlanEnabled: vi.fn().mockReturnValue(false), + getCheckpointingEnabled: vi.fn().mockReturnValue(false), + getGitService: vi.fn().mockResolvedValue({} as GitService), waitForMcpInit: vi.fn(), } as unknown as Mocked; mockConnection = { @@ -495,13 +661,38 @@ describe('Session', () => { sendNotification: vi.fn(), } as unknown as Mocked; - session = new Session('session-1', mockChat, mockConfig, mockConnection); + session = new Session('session-1', mockChat, mockConfig, mockConnection, { + system: { settings: {} }, + systemDefaults: { settings: {} }, + user: { settings: {} }, + workspace: { settings: {} }, + merged: { settings: {} }, + errors: [], + } as unknown as LoadedSettings); }); afterEach(() => { vi.clearAllMocks(); }); + it('should send available commands', async () => { + await session.sendAvailableCommands(); + + expect(mockConnection.sessionUpdate).toHaveBeenCalledWith( + expect.objectContaining({ + update: expect.objectContaining({ + sessionUpdate: 'available_commands_update', + availableCommands: expect.arrayContaining([ + expect.objectContaining({ name: 'memory' }), + expect.objectContaining({ name: 'extensions' }), + expect.objectContaining({ name: 'restore' }), + expect.objectContaining({ name: 'init' }), + ]), + }), + }), + ); + }); + it('should await MCP initialization before processing a prompt', async () => { const stream = createMockStream([ { @@ -551,6 +742,113 @@ describe('Session', () => { expect(result).toEqual({ stopReason: 'end_turn' }); }); + it('should handle /memory command', async () => { + const handleCommandSpy = vi + .spyOn( + (session as unknown as { commandHandler: CommandHandler }) + .commandHandler, + 'handleCommand', + ) + .mockResolvedValue(true); + + const result = await session.prompt({ + sessionId: 'session-1', + prompt: [{ type: 'text', text: '/memory view' }], + }); + + expect(result).toEqual({ stopReason: 'end_turn' }); + expect(handleCommandSpy).toHaveBeenCalledWith( + '/memory view', + expect.any(Object), + ); + expect(mockChat.sendMessageStream).not.toHaveBeenCalled(); + }); + + it('should handle /extensions command', async () => { + const handleCommandSpy = vi + .spyOn( + (session as unknown as { commandHandler: CommandHandler }) + .commandHandler, + 'handleCommand', + ) + .mockResolvedValue(true); + + const result = await session.prompt({ + sessionId: 'session-1', + prompt: [{ type: 'text', text: '/extensions list' }], + }); + + expect(result).toEqual({ stopReason: 'end_turn' }); + expect(handleCommandSpy).toHaveBeenCalledWith( + '/extensions list', + expect.any(Object), + ); + expect(mockChat.sendMessageStream).not.toHaveBeenCalled(); + }); + + it('should handle /extensions explore command', async () => { + const handleCommandSpy = vi + .spyOn( + (session as unknown as { commandHandler: CommandHandler }) + .commandHandler, + 'handleCommand', + ) + .mockResolvedValue(true); + + const result = await session.prompt({ + sessionId: 'session-1', + prompt: [{ type: 'text', text: '/extensions explore' }], + }); + + expect(result).toEqual({ stopReason: 'end_turn' }); + expect(handleCommandSpy).toHaveBeenCalledWith( + '/extensions explore', + expect.any(Object), + ); + expect(mockChat.sendMessageStream).not.toHaveBeenCalled(); + }); + + it('should handle /restore command', async () => { + const handleCommandSpy = vi + .spyOn( + (session as unknown as { commandHandler: CommandHandler }) + .commandHandler, + 'handleCommand', + ) + .mockResolvedValue(true); + + const result = await session.prompt({ + sessionId: 'session-1', + prompt: [{ type: 'text', text: '/restore' }], + }); + + expect(result).toEqual({ stopReason: 'end_turn' }); + expect(handleCommandSpy).toHaveBeenCalledWith( + '/restore', + expect.any(Object), + ); + expect(mockChat.sendMessageStream).not.toHaveBeenCalled(); + }); + + it('should handle /init command', async () => { + const handleCommandSpy = vi + .spyOn( + (session as unknown as { commandHandler: CommandHandler }) + .commandHandler, + 'handleCommand', + ) + .mockResolvedValue(true); + + const result = await session.prompt({ + sessionId: 'session-1', + prompt: [{ type: 'text', text: '/init' }], + }); + + expect(result).toEqual({ stopReason: 'end_turn' }); + expect(handleCommandSpy).toHaveBeenCalledWith('/init', expect.any(Object)); + expect(mockChat.sendMessageStream).not.toHaveBeenCalled(); + }); + it('should handle tool calls', async () => { const stream1 = createMockStream([ { @@ -1207,4 +1505,30 @@ describe('Session', () => { 'Invalid or unavailable mode: invalid-mode', ); }); + + it('should set model on config', () => { + session.setModel('gemini-2.0-flash-exp'); + expect(mockConfig.setModel).toHaveBeenCalledWith('gemini-2.0-flash-exp'); + }); + + it('should handle unquoted commands from autocomplete (with empty leading parts)', async () => { + // Mock handleCommand to verify it gets called + const handleCommandSpy = vi + .spyOn( + (session as unknown as { commandHandler: CommandHandler }) + .commandHandler, + 'handleCommand', + ) + .mockResolvedValue(true); + + await session.prompt({ + sessionId: 'session-1', + prompt: [ + { type: 'text', text: '' }, + { type: 'text', text: '/memory' }, + ], + }); + + expect(handleCommandSpy).toHaveBeenCalledWith('/memory', expect.anything()); + }); }); diff --git a/packages/cli/src/zed-integration/zedIntegration.ts b/packages/cli/src/acp/acpClient.ts similarity index 83% rename from packages/cli/src/zed-integration/zedIntegration.ts rename to packages/cli/src/acp/acpClient.ts index 98c9efdc75..2a8a524ff8 100644 --- a/packages/cli/src/zed-integration/zedIntegration.ts +++ b/packages/cli/src/acp/acpClient.ts @@ -4,15 +4,13 @@ * SPDX-License-Identifier: Apache-2.0 */ -import type { - Config, - GeminiChat, - ToolResult, - ToolCallConfirmationDetails, - FilterFilesOptions, - ConversationRecord, -} from '@google/gemini-cli-core'; import { + type Config, + type GeminiChat, + type ToolResult, + type ToolCallConfirmationDetails, + type FilterFilesOptions, + type ConversationRecord, CoreToolCallStatus, AuthType, logToolCall, @@ -39,6 +37,16 @@ import { ApprovalMode, getVersion, convertSessionToClientHistory, + DEFAULT_GEMINI_MODEL, + DEFAULT_GEMINI_FLASH_MODEL, + DEFAULT_GEMINI_FLASH_LITE_MODEL, + PREVIEW_GEMINI_MODEL, + PREVIEW_GEMINI_3_1_MODEL, + PREVIEW_GEMINI_3_1_CUSTOM_TOOLS_MODEL, + PREVIEW_GEMINI_FLASH_MODEL, + DEFAULT_GEMINI_MODEL_AUTO, + PREVIEW_GEMINI_MODEL_AUTO, + getDisplayString, } from '@google/gemini-cli-core'; import * as acp from '@agentclientprotocol/sdk'; import { AcpFileSystemService } from './fileSystemService.js'; @@ -61,11 +69,14 @@ import { loadCliConfig } from '../config/config.js'; import { runExitCleanup } from '../utils/cleanup.js'; import { SessionSelector } from '../utils/sessionUtils.js'; -export async function runZedIntegration( +import { CommandHandler } from './commandHandler.js'; +export async function runAcpClient( config: Config, settings: LoadedSettings, argv: CliArgs, ) { + // ... (skip unchanged lines) ... + const { stdout: workingStdout } = createWorkingStdio(); const stdout = Writable.toWeb(workingStdout) as WritableStream; // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion @@ -87,6 +98,8 @@ export class GeminiAgent { private sessions: Map = new Map(); private clientCapabilities: acp.ClientCapabilities | undefined; private apiKey: string | undefined; + private baseUrl: string | undefined; + private customHeaders: Record | undefined; constructor( private config: Config, @@ -120,6 +133,17 @@ export class GeminiAgent { name: 'Vertex AI', description: 'Use an API key with Vertex AI GenAI API', }, + { + id: AuthType.GATEWAY, + name: 'AI API Gateway', + description: 'Use a custom AI API Gateway', + _meta: { + gateway: { + protocol: 'google', + restartRequired: 'false', + }, + }, + }, ]; await this.config.initialize(); @@ -168,7 +192,38 @@ export class GeminiAgent { if (apiKey) { this.apiKey = apiKey; } - await this.config.refreshAuth(method, apiKey ?? this.apiKey); + + // Extract gateway details if present + const gatewaySchema = z.object({ + baseUrl: z.string().optional(), + headers: z.record(z.string()).optional(), + }); + + let baseUrl: string | undefined; + let headers: Record | undefined; + + if (meta?.['gateway']) { + const result = gatewaySchema.safeParse(meta['gateway']); + if (result.success) { + baseUrl = result.data.baseUrl; + headers = result.data.headers; + } else { + throw new acp.RequestError( + -32602, + `Malformed gateway payload: ${result.error.message}`, + ); + } + } + + this.baseUrl = baseUrl; + this.customHeaders = headers; + + await this.config.refreshAuth( + method, + apiKey ?? this.apiKey, + baseUrl, + headers, + ); } catch (e) { throw new acp.RequestError(-32000, getAcpErrorMessage(e)); } @@ -198,7 +253,12 @@ export class GeminiAgent { let isAuthenticated = false; let authErrorMessage = ''; try { - await config.refreshAuth(authType, this.apiKey); + await config.refreshAuth( + authType, + this.apiKey, + this.baseUrl, + this.customHeaders, + ); isAuthenticated = true; // Extra validation for Gemini API key @@ -240,16 +300,37 @@ export class GeminiAgent { const geminiClient = config.getGeminiClient(); const chat = await geminiClient.startChat(); - const session = new Session(sessionId, chat, config, this.connection); + const session = new Session( + sessionId, + chat, + config, + this.connection, + this.settings, + ); this.sessions.set(sessionId, session); - return { + setTimeout(() => { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + session.sendAvailableCommands(); + }, 0); + + const { availableModels, currentModelId } = buildAvailableModels( + config, + loadedSettings, + ); + + const response = { sessionId, modes: { availableModes: buildAvailableModes(config.isPlanEnabled()), currentModeId: config.getApprovalMode(), }, + models: { + availableModels, + currentModelId, + }, }; + return response; } async loadSession({ @@ -291,6 +372,7 @@ export class GeminiAgent { geminiClient.getChat(), config, this.connection, + this.settings, ); this.sessions.set(sessionId, session); @@ -298,12 +380,27 @@ export class GeminiAgent { // eslint-disable-next-line @typescript-eslint/no-floating-promises session.streamHistory(sessionData.messages); - return { + setTimeout(() => { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + session.sendAvailableCommands(); + }, 0); + + const { availableModels, currentModelId } = buildAvailableModels( + config, + this.settings, + ); + + const response = { modes: { availableModes: buildAvailableModes(config.isPlanEnabled()), currentModeId: config.getApprovalMode(), }, + models: { + availableModels, + currentModelId, + }, }; + return response; } private async initializeSessionConfig( @@ -323,7 +420,12 @@ export class GeminiAgent { // This satisfies the security requirement to verify the user before executing // potentially unsafe server definitions. try { - await config.refreshAuth(selectedAuthType, this.apiKey); + await config.refreshAuth( + selectedAuthType, + this.apiKey, + this.baseUrl, + this.customHeaders, + ); } catch (e) { debugLogger.error(`Authentication failed: ${e}`); throw acp.RequestError.authRequired(); @@ -414,16 +516,28 @@ export class GeminiAgent { } return session.setMode(params.modeId); } + + async unstable_setSessionModel( + params: acp.SetSessionModelRequest, + ): Promise { + const session = this.sessions.get(params.sessionId); + if (!session) { + throw new Error(`Session not found: ${params.sessionId}`); + } + return session.setModel(params.modelId); + } } export class Session { private pendingPrompt: AbortController | null = null; + private commandHandler = new CommandHandler(); constructor( private readonly id: string, private readonly chat: GeminiChat, private readonly config: Config, private readonly connection: acp.AgentSideConnection, + private readonly settings: LoadedSettings, ) {} async cancelPendingPrompt(): Promise { @@ -446,6 +560,27 @@ export class Session { return {}; } + private getAvailableCommands() { + return this.commandHandler.getAvailableCommands(); + } + + async sendAvailableCommands(): Promise { + const availableCommands = this.getAvailableCommands().map((command) => ({ + name: command.name, + description: command.description, + })); + + await this.sendUpdate({ + sessionUpdate: 'available_commands_update', + availableCommands, + }); + } + + setModel(modelId: acp.ModelId): acp.SetSessionModelResponse { + this.config.setModel(modelId); + return {}; + } + async streamHistory(messages: ConversationRecord['messages']): Promise { for (const msg of messages) { const contentString = partListUnionToString(msg.content); @@ -528,6 +663,41 @@ export class Session { const parts = await this.#resolvePrompt(params.prompt, pendingSend.signal); + // Command interception + let commandText = ''; + + for (const part of parts) { + if (typeof part === 'object' && part !== null) { + if ('text' in part) { + // It is a text part + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-type-assertion + const text = (part as any).text; + if (typeof text === 'string') { + commandText += text; + } + } else { + // Non-text part (image, embedded resource) + // Stop looking for command + break; + } + } + } + + commandText = commandText.trim(); + + if ( + commandText && + (commandText.startsWith('/') || commandText.startsWith('$')) + ) { + // If we found a command, pass it to handleCommand + // Note: handleCommand currently expects `commandText` to be the command string + // It uses `parts` argument but effectively ignores it in current implementation + const handled = await this.handleCommand(commandText, parts); + if (handled) { + return { stopReason: 'end_turn' }; + } + } + let nextMessage: Content | null = { role: 'user', parts }; while (nextMessage !== null) { @@ -627,9 +797,28 @@ export class Session { return { stopReason: 'end_turn' }; } - private async sendUpdate( - update: acp.SessionNotification['update'], - ): Promise { + private async handleCommand( + commandText: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + parts: Part[], + ): Promise { + const gitService = await this.config.getGitService(); + const commandContext = { + config: this.config, + settings: this.settings, + git: gitService, + sendMessage: async (text: string) => { + await this.sendUpdate({ + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text }, + }); + }, + }; + + return this.commandHandler.handleCommand(commandText, commandContext); + } + + private async sendUpdate(update: acp.SessionUpdate): Promise { const params: acp.SessionNotification = { sessionId: this.id, update, @@ -1377,3 +1566,94 @@ function buildAvailableModes(isPlanEnabled: boolean): acp.SessionMode[] { return modes; } + +function buildAvailableModels( + config: Config, + settings: LoadedSettings, +): { + availableModels: Array<{ + modelId: string; + name: string; + description?: string; + }>; + currentModelId: string; +} { + const preferredModel = config.getModel() || DEFAULT_GEMINI_MODEL_AUTO; + const shouldShowPreviewModels = config.getHasAccessToPreviewModel(); + const useGemini31 = config.getGemini31LaunchedSync?.() ?? false; + const selectedAuthType = settings.merged.security.auth.selectedType; + const useCustomToolModel = + useGemini31 && selectedAuthType === AuthType.USE_GEMINI; + + const mainOptions = [ + { + value: DEFAULT_GEMINI_MODEL_AUTO, + title: getDisplayString(DEFAULT_GEMINI_MODEL_AUTO), + description: + 'Let Gemini CLI decide the best model for the task: gemini-2.5-pro, gemini-2.5-flash', + }, + ]; + + if (shouldShowPreviewModels) { + mainOptions.unshift({ + value: PREVIEW_GEMINI_MODEL_AUTO, + title: getDisplayString(PREVIEW_GEMINI_MODEL_AUTO), + description: useGemini31 + ? 'Let Gemini CLI decide the best model for the task: gemini-3.1-pro, gemini-3-flash' + : 'Let Gemini CLI decide the best model for the task: gemini-3-pro, gemini-3-flash', + }); + } + + const manualOptions = [ + { + value: DEFAULT_GEMINI_MODEL, + title: getDisplayString(DEFAULT_GEMINI_MODEL), + }, + { + value: DEFAULT_GEMINI_FLASH_MODEL, + title: getDisplayString(DEFAULT_GEMINI_FLASH_MODEL), + }, + { + value: DEFAULT_GEMINI_FLASH_LITE_MODEL, + title: getDisplayString(DEFAULT_GEMINI_FLASH_LITE_MODEL), + }, + ]; + + if (shouldShowPreviewModels) { + const previewProModel = useGemini31 + ? PREVIEW_GEMINI_3_1_MODEL + : PREVIEW_GEMINI_MODEL; + + const previewProValue = useCustomToolModel + ? PREVIEW_GEMINI_3_1_CUSTOM_TOOLS_MODEL + : previewProModel; + + manualOptions.unshift( + { + value: previewProValue, + title: getDisplayString(previewProModel), + }, + { + value: PREVIEW_GEMINI_FLASH_MODEL, + title: getDisplayString(PREVIEW_GEMINI_FLASH_MODEL), + }, + ); + } + + const scaleOptions = ( + options: Array<{ value: string; title: string; description?: string }>, + ) => + options.map((o) => ({ + modelId: o.value, + name: o.title, + description: o.description, + })); + + return { + availableModels: [ + ...scaleOptions(mainOptions), + ...scaleOptions(manualOptions), + ], + currentModelId: preferredModel, + }; +} diff --git a/packages/cli/src/zed-integration/acpErrors.test.ts b/packages/cli/src/acp/acpErrors.test.ts similarity index 100% rename from packages/cli/src/zed-integration/acpErrors.test.ts rename to packages/cli/src/acp/acpErrors.test.ts diff --git a/packages/cli/src/zed-integration/acpErrors.ts b/packages/cli/src/acp/acpErrors.ts similarity index 100% rename from packages/cli/src/zed-integration/acpErrors.ts rename to packages/cli/src/acp/acpErrors.ts diff --git a/packages/cli/src/zed-integration/acpResume.test.ts b/packages/cli/src/acp/acpResume.test.ts similarity index 95% rename from packages/cli/src/zed-integration/acpResume.test.ts rename to packages/cli/src/acp/acpResume.test.ts index 54c04a0ff3..37354af5c9 100644 --- a/packages/cli/src/zed-integration/acpResume.test.ts +++ b/packages/cli/src/acp/acpResume.test.ts @@ -13,7 +13,7 @@ import { type Mocked, type Mock, } from 'vitest'; -import { GeminiAgent } from './zedIntegration.js'; +import { GeminiAgent } from './acpClient.js'; import * as acp from '@agentclientprotocol/sdk'; import { ApprovalMode, @@ -93,6 +93,10 @@ describe('GeminiAgent Session Resume', () => { }, getApprovalMode: vi.fn().mockReturnValue('default'), isPlanEnabled: vi.fn().mockReturnValue(false), + getModel: vi.fn().mockReturnValue('gemini-pro'), + getHasAccessToPreviewModel: vi.fn().mockReturnValue(false), + getGemini31LaunchedSync: vi.fn().mockReturnValue(false), + getCheckpointingEnabled: vi.fn().mockReturnValue(false), } as unknown as Mocked; mockSettings = { merged: { @@ -203,6 +207,10 @@ describe('GeminiAgent Session Resume', () => { ], currentModeId: ApprovalMode.DEFAULT, }, + models: { + availableModels: expect.any(Array) as unknown, + currentModelId: 'gemini-pro', + }, }); // Verify resumeChat received the correct arguments diff --git a/packages/cli/src/acp/commandHandler.test.ts b/packages/cli/src/acp/commandHandler.test.ts new file mode 100644 index 0000000000..8e04f014f3 --- /dev/null +++ b/packages/cli/src/acp/commandHandler.test.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { CommandHandler } from './commandHandler.js'; +import { describe, it, expect } from 'vitest'; + +describe('CommandHandler', () => { + it('parses commands correctly', () => { + const handler = new CommandHandler(); + // @ts-expect-error - testing private method + const parse = (query: string) => handler.parseSlashCommand(query); + + const memShow = parse('/memory show'); + expect(memShow.commandToExecute?.name).toBe('memory show'); + expect(memShow.args).toBe(''); + + const memAdd = parse('/memory add hello world'); + expect(memAdd.commandToExecute?.name).toBe('memory add'); + expect(memAdd.args).toBe('hello world'); + + const extList = parse('/extensions list'); + expect(extList.commandToExecute?.name).toBe('extensions list'); + + const init = parse('/init'); + expect(init.commandToExecute?.name).toBe('init'); + }); +}); diff --git a/packages/cli/src/acp/commandHandler.ts b/packages/cli/src/acp/commandHandler.ts new file mode 100644 index 0000000000..836cdf7736 --- /dev/null +++ b/packages/cli/src/acp/commandHandler.ts @@ -0,0 +1,134 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import type { Command, CommandContext } from './commands/types.js'; +import { CommandRegistry } from './commands/commandRegistry.js'; +import { MemoryCommand } from './commands/memory.js'; +import { ExtensionsCommand } from './commands/extensions.js'; +import { InitCommand } from './commands/init.js'; +import { RestoreCommand } from './commands/restore.js'; + +export class CommandHandler { + private registry: CommandRegistry; + + constructor() { + this.registry = CommandHandler.createRegistry(); + } + + private static createRegistry(): CommandRegistry { + const registry = new CommandRegistry(); + registry.register(new MemoryCommand()); + registry.register(new ExtensionsCommand()); + registry.register(new InitCommand()); + registry.register(new RestoreCommand()); + return registry; + } + + getAvailableCommands(): Array<{ name: string; description: string }> { + return this.registry.getAllCommands().map((cmd) => ({ + name: cmd.name, + description: cmd.description, + })); + } + + /** + * Parses and executes a command string if it matches a registered command. + * Returns true if a command was handled, false otherwise. + */ + async handleCommand( + commandText: string, + context: CommandContext, + ): Promise { + const { commandToExecute, args } = this.parseSlashCommand(commandText); + + if (commandToExecute) { + await this.runCommand(commandToExecute, args, context); + return true; + } + + return false; + } + + private async runCommand( + commandToExecute: Command, + args: string, + context: CommandContext, + ): Promise { + try { + const result = await commandToExecute.execute( + context, + args ? args.split(/\s+/) : [], + ); + + let messageContent = ''; + if (typeof result.data === 'string') { + messageContent = result.data; + } else if ( + typeof result.data === 'object' && + result.data !== null && + 'content' in result.data + ) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion, @typescript-eslint/no-explicit-any + messageContent = (result.data as Record)[ + 'content' + ] as string; + } else { + messageContent = JSON.stringify(result.data, null, 2); + } + + await context.sendMessage(messageContent); + } catch (error) { + const errorMessage = + error instanceof Error ? error.message : String(error); + await context.sendMessage(`Error: ${errorMessage}`); + } + } + + /** + * Parses a raw slash command string into its matching headless command and arguments. + * Mirrors `packages/cli/src/utils/commands.ts` logic. + */ + private parseSlashCommand(query: string): { + commandToExecute: Command | undefined; + args: string; + } { + const trimmed = query.trim(); + const parts = trimmed.substring(1).trim().split(/\s+/); + const commandPath = parts.filter((p) => p); + + let currentCommands = this.registry.getAllCommands(); + let commandToExecute: Command | undefined; + let pathIndex = 0; + + for (const part of commandPath) { + const foundCommand = currentCommands.find((cmd) => { + const expectedName = commandPath.slice(0, pathIndex + 1).join(' '); + return ( + cmd.name === part || + cmd.name === expectedName || + cmd.aliases?.includes(part) || + cmd.aliases?.includes(expectedName) + ); + }); + + if (foundCommand) { + commandToExecute = foundCommand; + pathIndex++; + if (foundCommand.subCommands) { + currentCommands = foundCommand.subCommands; + } else { + break; + } + } else { + break; + } + } + + const args = parts.slice(pathIndex).join(' '); + + return { commandToExecute, args }; + } +} diff --git a/packages/cli/src/acp/commands/commandRegistry.ts b/packages/cli/src/acp/commands/commandRegistry.ts new file mode 100644 index 0000000000..b689d5d602 --- /dev/null +++ b/packages/cli/src/acp/commands/commandRegistry.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { debugLogger } from '@google/gemini-cli-core'; +import type { Command } from './types.js'; + +export class CommandRegistry { + private readonly commands = new Map(); + + register(command: Command) { + if (this.commands.has(command.name)) { + debugLogger.warn(`Command ${command.name} already registered. Skipping.`); + return; + } + + this.commands.set(command.name, command); + + for (const subCommand of command.subCommands ?? []) { + this.register(subCommand); + } + } + + get(commandName: string): Command | undefined { + return this.commands.get(commandName); + } + + getAllCommands(): Command[] { + return [...this.commands.values()]; + } +} diff --git a/packages/cli/src/acp/commands/extensions.ts b/packages/cli/src/acp/commands/extensions.ts new file mode 100644 index 0000000000..d2946e64a6 --- /dev/null +++ b/packages/cli/src/acp/commands/extensions.ts @@ -0,0 +1,445 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { listExtensions } from '@google/gemini-cli-core'; +import { SettingScope } from '../../config/settings.js'; +import { + ExtensionManager, + inferInstallMetadata, +} from '../../config/extension-manager.js'; +import { getErrorMessage } from '../../utils/errors.js'; +import { McpServerEnablementManager } from '../../config/mcp/mcpServerEnablement.js'; +import { stat } from 'node:fs/promises'; +import type { + Command, + CommandContext, + CommandExecutionResponse, +} from './types.js'; +import type { Config } from '@google/gemini-cli-core'; + +export class ExtensionsCommand implements Command { + readonly name = 'extensions'; + readonly description = 'Manage extensions.'; + readonly subCommands = [ + new ListExtensionsCommand(), + new ExploreExtensionsCommand(), + new EnableExtensionCommand(), + new DisableExtensionCommand(), + new InstallExtensionCommand(), + new LinkExtensionCommand(), + new UninstallExtensionCommand(), + new RestartExtensionCommand(), + new UpdateExtensionCommand(), + ]; + + async execute( + context: CommandContext, + _: string[], + ): Promise { + return new ListExtensionsCommand().execute(context, _); + } +} + +export class ListExtensionsCommand implements Command { + readonly name = 'extensions list'; + readonly description = 'Lists all installed extensions.'; + + async execute( + context: CommandContext, + _: string[], + ): Promise { + const extensions = listExtensions(context.config); + const data = extensions.length ? extensions : 'No extensions installed.'; + + return { name: this.name, data }; + } +} + +export class ExploreExtensionsCommand implements Command { + readonly name = 'extensions explore'; + readonly description = 'Explore available extensions.'; + + async execute( + _context: CommandContext, + _: string[], + ): Promise { + const extensionsUrl = 'https://geminicli.com/extensions/'; + return { + name: this.name, + data: `View or install available extensions at ${extensionsUrl}`, + }; + } +} + +function getEnableDisableContext( + config: Config, + args: string[], + invocationName: string, +) { + const extensionManager = config.getExtensionLoader(); + if (!(extensionManager instanceof ExtensionManager)) { + return { + error: `Cannot ${invocationName} extensions in this environment.`, + }; + } + + if (args.length === 0) { + return { + error: `Usage: /extensions ${invocationName} [--scope=]`, + }; + } + + let scope = SettingScope.User; + if (args.includes('--scope=workspace') || args.includes('workspace')) { + scope = SettingScope.Workspace; + } else if (args.includes('--scope=session') || args.includes('session')) { + scope = SettingScope.Session; + } + + const name = args.filter( + (a) => + !a.startsWith('--scope') && !['user', 'workspace', 'session'].includes(a), + )[0]; + + let names: string[] = []; + if (name === '--all') { + let extensions = extensionManager.getExtensions(); + if (invocationName === 'enable') { + extensions = extensions.filter((ext) => !ext.isActive); + } + if (invocationName === 'disable') { + extensions = extensions.filter((ext) => ext.isActive); + } + names = extensions.map((ext) => ext.name); + } else if (name) { + names = [name]; + } else { + return { error: 'No extension name provided.' }; + } + + return { extensionManager, names, scope }; +} + +export class EnableExtensionCommand implements Command { + readonly name = 'extensions enable'; + readonly description = 'Enable an extension.'; + + async execute( + context: CommandContext, + args: string[], + ): Promise { + const enableContext = getEnableDisableContext( + context.config, + args, + 'enable', + ); + if ('error' in enableContext) { + return { name: this.name, data: enableContext.error }; + } + + const { names, scope, extensionManager } = enableContext; + const output: string[] = []; + + for (const name of names) { + try { + await extensionManager.enableExtension(name, scope); + output.push(`Extension "${name}" enabled for scope "${scope}".`); + + const extension = extensionManager + .getExtensions() + .find((e) => e.name === name); + + if (extension?.mcpServers) { + const mcpEnablementManager = McpServerEnablementManager.getInstance(); + const mcpClientManager = context.config.getMcpClientManager(); + const enabledServers = await mcpEnablementManager.autoEnableServers( + Object.keys(extension.mcpServers), + ); + + if (mcpClientManager && enabledServers.length > 0) { + const restartPromises = enabledServers.map((serverName) => + mcpClientManager.restartServer(serverName).catch((error) => { + output.push( + `Failed to restart MCP server '${serverName}': ${getErrorMessage(error)}`, + ); + }), + ); + await Promise.all(restartPromises); + output.push(`Re-enabled MCP servers: ${enabledServers.join(', ')}`); + } + } + } catch (e) { + output.push(`Failed to enable "${name}": ${getErrorMessage(e)}`); + } + } + + return { name: this.name, data: output.join('\n') || 'No action taken.' }; + } +} + +export class DisableExtensionCommand implements Command { + readonly name = 'extensions disable'; + readonly description = 'Disable an extension.'; + + async execute( + context: CommandContext, + args: string[], + ): Promise { + const enableContext = getEnableDisableContext( + context.config, + args, + 'disable', + ); + if ('error' in enableContext) { + return { name: this.name, data: enableContext.error }; + } + + const { names, scope, extensionManager } = enableContext; + const output: string[] = []; + + for (const name of names) { + try { + await extensionManager.disableExtension(name, scope); + output.push(`Extension "${name}" disabled for scope "${scope}".`); + } catch (e) { + output.push(`Failed to disable "${name}": ${getErrorMessage(e)}`); + } + } + + return { name: this.name, data: output.join('\n') || 'No action taken.' }; + } +} + +export class InstallExtensionCommand implements Command { + readonly name = 'extensions install'; + readonly description = 'Install an extension from a git repo or local path.'; + + async execute( + context: CommandContext, + args: string[], + ): Promise { + const extensionLoader = context.config.getExtensionLoader(); + if (!(extensionLoader instanceof ExtensionManager)) { + return { + name: this.name, + data: 'Cannot install extensions in this environment.', + }; + } + + const source = args.join(' ').trim(); + if (!source) { + return { name: this.name, data: `Usage: /extensions install ` }; + } + + if (/[;&|`'"]/.test(source)) { + return { + name: this.name, + data: `Invalid source: contains disallowed characters.`, + }; + } + + try { + const installMetadata = await inferInstallMetadata(source); + const extension = + await extensionLoader.installOrUpdateExtension(installMetadata); + return { + name: this.name, + data: `Extension "${extension.name}" installed successfully.`, + }; + } catch (error) { + return { + name: this.name, + data: `Failed to install extension from "${source}": ${getErrorMessage(error)}`, + }; + } + } +} + +export class LinkExtensionCommand implements Command { + readonly name = 'extensions link'; + readonly description = 'Link an extension from a local path.'; + + async execute( + context: CommandContext, + args: string[], + ): Promise { + const extensionLoader = context.config.getExtensionLoader(); + if (!(extensionLoader instanceof ExtensionManager)) { + return { + name: this.name, + data: 'Cannot link extensions in this environment.', + }; + } + + const sourceFilepath = args.join(' ').trim(); + if (!sourceFilepath) { + return { name: this.name, data: `Usage: /extensions link ` }; + } + + try { + await stat(sourceFilepath); + } catch (_error) { + return { name: this.name, data: `Invalid source: ${sourceFilepath}` }; + } + + try { + const extension = await extensionLoader.installOrUpdateExtension({ + source: sourceFilepath, + type: 'link', + }); + return { + name: this.name, + data: `Extension "${extension.name}" linked successfully.`, + }; + } catch (error) { + return { + name: this.name, + data: `Failed to link extension: ${getErrorMessage(error)}`, + }; + } + } +} + +export class UninstallExtensionCommand implements Command { + readonly name = 'extensions uninstall'; + readonly description = 'Uninstall an extension.'; + + async execute( + context: CommandContext, + args: string[], + ): Promise { + const extensionLoader = context.config.getExtensionLoader(); + if (!(extensionLoader instanceof ExtensionManager)) { + return { + name: this.name, + data: 'Cannot uninstall extensions in this environment.', + }; + } + + const all = args.includes('--all'); + const names = args.filter((a) => !a.startsWith('--')).map((a) => a.trim()); + + if (!all && names.length === 0) { + return { + name: this.name, + data: `Usage: /extensions uninstall |--all`, + }; + } + + let namesToUninstall: string[] = []; + if (all) { + namesToUninstall = extensionLoader.getExtensions().map((ext) => ext.name); + } else { + namesToUninstall = names; + } + + if (namesToUninstall.length === 0) { + return { + name: this.name, + data: all ? 'No extensions installed.' : 'No extension name provided.', + }; + } + + 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') }; + } +} + +export class RestartExtensionCommand implements Command { + readonly name = 'extensions restart'; + readonly description = 'Restart an extension.'; + + async execute( + context: CommandContext, + args: string[], + ): Promise { + const extensionLoader = context.config.getExtensionLoader(); + if (!(extensionLoader instanceof ExtensionManager)) { + return { name: this.name, data: 'Cannot restart extensions.' }; + } + + const all = args.includes('--all'); + const names = all ? null : args.filter((a) => !!a); + + if (!all && names?.length === 0) { + return { + name: this.name, + data: 'Usage: /extensions restart |--all', + }; + } + + let extensionsToRestart = extensionLoader + .getExtensions() + .filter((e) => e.isActive); + if (names) { + extensionsToRestart = extensionsToRestart.filter((e) => + names.includes(e.name), + ); + } + + if (extensionsToRestart.length === 0) { + return { + name: this.name, + data: 'No active extensions matched the request.', + }; + } + + const output: string[] = []; + for (const extension of extensionsToRestart) { + try { + await extensionLoader.restartExtension(extension); + output.push(`Restarted "${extension.name}".`); + } catch (e) { + output.push( + `Failed to restart "${extension.name}": ${getErrorMessage(e)}`, + ); + } + } + + return { name: this.name, data: output.join('\n') }; + } +} + +export class UpdateExtensionCommand implements Command { + readonly name = 'extensions update'; + readonly description = 'Update an extension.'; + + async execute( + context: CommandContext, + args: string[], + ): Promise { + const extensionLoader = context.config.getExtensionLoader(); + if (!(extensionLoader instanceof ExtensionManager)) { + return { name: this.name, data: 'Cannot update extensions.' }; + } + + const all = args.includes('--all'); + const names = all ? null : args.filter((a) => !!a); + + if (!all && names?.length === 0) { + return { + name: this.name, + data: 'Usage: /extensions update |--all', + }; + } + + return { + name: this.name, + data: 'Headless extension updating requires internal UI dispatches. Please use `gemini extensions update` directly in the terminal.', + }; + } +} diff --git a/packages/cli/src/acp/commands/init.ts b/packages/cli/src/acp/commands/init.ts new file mode 100644 index 0000000000..5c4197f84c --- /dev/null +++ b/packages/cli/src/acp/commands/init.ts @@ -0,0 +1,62 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { performInit } from '@google/gemini-cli-core'; +import type { + Command, + CommandContext, + CommandExecutionResponse, +} from './types.js'; + +export class InitCommand implements Command { + name = 'init'; + description = 'Analyzes the project and creates a tailored GEMINI.md file'; + requiresWorkspace = true; + + async execute( + context: CommandContext, + _args: string[] = [], + ): Promise { + const targetDir = context.config.getTargetDir(); + if (!targetDir) { + throw new Error('Command requires a workspace.'); + } + + const geminiMdPath = path.join(targetDir, 'GEMINI.md'); + const result = performInit(fs.existsSync(geminiMdPath)); + + switch (result.type) { + case 'message': + return { + name: this.name, + data: result, + }; + case 'submit_prompt': + fs.writeFileSync(geminiMdPath, '', 'utf8'); + + if (typeof result.content !== 'string') { + throw new Error('Init command content must be a string.'); + } + + // Inform the user since we can't trigger the UI-based interactive agent loop here directly. + // We output the prompt text they can use to re-trigger the generation manually, + // or just seed the GEMINI.md file as we've done above. + return { + name: this.name, + data: { + type: 'message', + messageType: 'info', + content: `A template GEMINI.md has been created at ${geminiMdPath}.\n\nTo populate it with project context, you can run the following prompt in a new chat:\n\n${result.content}`, + }, + }; + + default: + throw new Error('Unknown result type from performInit'); + } + } +} diff --git a/packages/cli/src/acp/commands/memory.ts b/packages/cli/src/acp/commands/memory.ts new file mode 100644 index 0000000000..9460af7ad1 --- /dev/null +++ b/packages/cli/src/acp/commands/memory.ts @@ -0,0 +1,121 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { + addMemory, + listMemoryFiles, + refreshMemory, + showMemory, +} from '@google/gemini-cli-core'; +import type { + Command, + CommandContext, + CommandExecutionResponse, +} from './types.js'; + +const DEFAULT_SANITIZATION_CONFIG = { + allowedEnvironmentVariables: [], + blockedEnvironmentVariables: [], + enableEnvironmentVariableRedaction: false, +}; + +export class MemoryCommand implements Command { + readonly name = 'memory'; + readonly description = 'Manage memory.'; + readonly subCommands = [ + new ShowMemoryCommand(), + new RefreshMemoryCommand(), + new ListMemoryCommand(), + new AddMemoryCommand(), + ]; + readonly requiresWorkspace = true; + + async execute( + context: CommandContext, + _: string[], + ): Promise { + return new ShowMemoryCommand().execute(context, _); + } +} + +export class ShowMemoryCommand implements Command { + readonly name = 'memory show'; + readonly description = 'Shows the current memory contents.'; + + async execute( + context: CommandContext, + _: string[], + ): Promise { + const result = showMemory(context.config); + return { name: this.name, data: result.content }; + } +} + +export class RefreshMemoryCommand implements Command { + readonly name = 'memory refresh'; + readonly aliases = ['memory reload']; + readonly description = 'Refreshes the memory from the source.'; + + async execute( + context: CommandContext, + _: string[], + ): Promise { + const result = await refreshMemory(context.config); + return { name: this.name, data: result.content }; + } +} + +export class ListMemoryCommand implements Command { + readonly name = 'memory list'; + readonly description = 'Lists the paths of the GEMINI.md files in use.'; + + async execute( + context: CommandContext, + _: string[], + ): Promise { + const result = listMemoryFiles(context.config); + return { name: this.name, data: result.content }; + } +} + +export class AddMemoryCommand implements Command { + readonly name = 'memory add'; + readonly description = 'Add content to the memory.'; + + async execute( + context: CommandContext, + args: string[], + ): Promise { + const textToAdd = args.join(' ').trim(); + const result = addMemory(textToAdd); + if (result.type === 'message') { + return { name: this.name, data: result.content }; + } + + const toolRegistry = context.config.getToolRegistry(); + const tool = toolRegistry.getTool(result.toolName); + if (tool) { + const abortController = new AbortController(); + const signal = abortController.signal; + + await context.sendMessage(`Saving memory via ${result.toolName}...`); + + await tool.buildAndExecute(result.toolArgs, signal, undefined, { + sanitizationConfig: DEFAULT_SANITIZATION_CONFIG, + }); + await refreshMemory(context.config); + return { + name: this.name, + data: `Added memory: "${textToAdd}"`, + }; + } else { + return { + name: this.name, + data: `Error: Tool ${result.toolName} not found.`, + }; + } + } +} diff --git a/packages/cli/src/acp/commands/restore.ts b/packages/cli/src/acp/commands/restore.ts new file mode 100644 index 0000000000..ec9166ed84 --- /dev/null +++ b/packages/cli/src/acp/commands/restore.ts @@ -0,0 +1,178 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { + getCheckpointInfoList, + getToolCallDataSchema, + isNodeError, + performRestore, +} from '@google/gemini-cli-core'; +import * as fs from 'node:fs/promises'; +import * as path from 'node:path'; +import type { + Command, + CommandContext, + CommandExecutionResponse, +} from './types.js'; + +export class RestoreCommand implements Command { + readonly name = 'restore'; + readonly description = + 'Restore to a previous checkpoint, or list available checkpoints to restore. This will reset the conversation and file history to the state it was in when the checkpoint was created'; + readonly requiresWorkspace = true; + readonly subCommands = [new ListCheckpointsCommand()]; + + async execute( + context: CommandContext, + args: string[], + ): Promise { + const { config, git: gitService } = context; + const argsStr = args.join(' '); + + try { + if (!argsStr) { + return await new ListCheckpointsCommand().execute(context); + } + + if (!config.getCheckpointingEnabled()) { + return { + name: this.name, + data: 'Checkpointing is not enabled. Please enable it in your settings (`general.checkpointing.enabled: true`) to use /restore.', + }; + } + + const selectedFile = argsStr.endsWith('.json') + ? argsStr + : `${argsStr}.json`; + + const checkpointDir = config.storage.getProjectTempCheckpointsDir(); + const filePath = path.join(checkpointDir, selectedFile); + + let data: string; + try { + data = await fs.readFile(filePath, 'utf-8'); + } catch (error) { + if (isNodeError(error) && error.code === 'ENOENT') { + return { + name: this.name, + data: `File not found: ${selectedFile}`, + }; + } + throw error; + } + + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const toolCallData = JSON.parse(data); + const ToolCallDataSchema = getToolCallDataSchema(); + const parseResult = ToolCallDataSchema.safeParse(toolCallData); + + if (!parseResult.success) { + return { + name: this.name, + data: 'Checkpoint file is invalid or corrupted.', + }; + } + + const restoreResultGenerator = performRestore( + parseResult.data, + gitService, + ); + + const restoreResult = []; + for await (const result of restoreResultGenerator) { + restoreResult.push(result); + } + + // Format the result nicely since Zed just dumps data + const formattedResult = restoreResult + .map((r) => { + if (r.type === 'message') { + return `[${r.messageType.toUpperCase()}] ${r.content}`; + } else if (r.type === 'load_history') { + return `Loaded history with ${r.clientHistory.length} messages.`; + } + return `Restored: ${JSON.stringify(r)}`; + }) + .join('\n'); + + return { + name: this.name, + data: formattedResult, + }; + } catch (error) { + return { + name: this.name, + data: `An unexpected error occurred during restore: ${error}`, + }; + } + } +} + +export class ListCheckpointsCommand implements Command { + readonly name = 'restore list'; + readonly description = 'Lists all available checkpoints.'; + + async execute(context: CommandContext): Promise { + const { config } = context; + + try { + if (!config.getCheckpointingEnabled()) { + return { + name: this.name, + data: 'Checkpointing is not enabled. Please enable it in your settings (`general.checkpointing.enabled: true`) to use /restore.', + }; + } + + const checkpointDir = config.storage.getProjectTempCheckpointsDir(); + try { + await fs.mkdir(checkpointDir, { recursive: true }); + } catch (_e) { + // Ignore + } + + const files = await fs.readdir(checkpointDir); + const jsonFiles = files.filter((file) => file.endsWith('.json')); + + if (jsonFiles.length === 0) { + return { name: this.name, data: 'No checkpoints found.' }; + } + + const checkpointFiles = new Map(); + for (const file of jsonFiles) { + const filePath = path.join(checkpointDir, file); + const data = await fs.readFile(filePath, 'utf-8'); + checkpointFiles.set(file, data); + } + + const checkpointInfoList = getCheckpointInfoList(checkpointFiles); + + const formatted = checkpointInfoList + .map((info) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const i = info as Record; + const fileName = String(i['fileName'] || 'Unknown'); + const toolName = String(i['toolName'] || 'Unknown'); + const status = String(i['status'] || 'Unknown'); + const timestamp = new Date( + Number(i['timestamp']) || 0, + ).toLocaleString(); + + return `- **${fileName}**: ${toolName} (Status: ${status}) [${timestamp}]`; + }) + .join('\n'); + + return { + name: this.name, + data: `Available Checkpoints:\n${formatted}`, + }; + } catch (_error) { + return { + name: this.name, + data: 'An unexpected error occurred while listing checkpoints.', + }; + } + } +} diff --git a/packages/cli/src/acp/commands/types.ts b/packages/cli/src/acp/commands/types.ts new file mode 100644 index 0000000000..099f0c923f --- /dev/null +++ b/packages/cli/src/acp/commands/types.ts @@ -0,0 +1,40 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import type { Config, GitService } from '@google/gemini-cli-core'; +import type { LoadedSettings } from '../../config/settings.js'; + +export interface CommandContext { + config: Config; + settings: LoadedSettings; + git?: GitService; + sendMessage: (text: string) => Promise; +} + +export interface CommandArgument { + readonly name: string; + readonly description: string; + readonly isRequired?: boolean; +} + +export interface Command { + readonly name: string; + readonly aliases?: string[]; + readonly description: string; + readonly arguments?: CommandArgument[]; + readonly subCommands?: Command[]; + readonly requiresWorkspace?: boolean; + + execute( + context: CommandContext, + args: string[], + ): Promise; +} + +export interface CommandExecutionResponse { + readonly name: string; + readonly data: unknown; +} diff --git a/packages/cli/src/zed-integration/fileSystemService.test.ts b/packages/cli/src/acp/fileSystemService.test.ts similarity index 100% rename from packages/cli/src/zed-integration/fileSystemService.test.ts rename to packages/cli/src/acp/fileSystemService.test.ts diff --git a/packages/cli/src/zed-integration/fileSystemService.ts b/packages/cli/src/acp/fileSystemService.ts similarity index 100% rename from packages/cli/src/zed-integration/fileSystemService.ts rename to packages/cli/src/acp/fileSystemService.ts diff --git a/packages/cli/src/commands/extensions/install.ts b/packages/cli/src/commands/extensions/install.ts index 5255dfeb83..1886444b88 100644 --- a/packages/cli/src/commands/extensions/install.ts +++ b/packages/cli/src/commands/extensions/install.ts @@ -5,6 +5,7 @@ */ import type { CommandModule } from 'yargs'; +import * as path from 'node:path'; import chalk from 'chalk'; import { debugLogger, @@ -51,12 +52,13 @@ export async function handleInstall(args: InstallArgs) { const settings = loadSettings(workspaceDir).merged; if (installMetadata.type === 'local' || installMetadata.type === 'link') { - const resolvedPath = getRealPath(source); - installMetadata.source = resolvedPath; - const trustResult = isWorkspaceTrusted(settings, resolvedPath); + const absolutePath = path.resolve(source); + const realPath = getRealPath(absolutePath); + installMetadata.source = absolutePath; + const trustResult = isWorkspaceTrusted(settings, absolutePath); if (trustResult.isTrusted !== true) { const discoveryResults = - await FolderTrustDiscoveryService.discover(resolvedPath); + await FolderTrustDiscoveryService.discover(realPath); const hasDiscovery = discoveryResults.commands.length > 0 || @@ -69,7 +71,7 @@ export async function handleInstall(args: InstallArgs) { '', chalk.bold('Do you trust the files in this folder?'), '', - `The extension source at "${resolvedPath}" is not trusted.`, + `The extension source at "${absolutePath}" is not trusted.`, '', 'Trusting a folder allows Gemini CLI to load its local configurations,', 'including custom commands, hooks, MCP servers, agent skills, and', @@ -127,10 +129,10 @@ export async function handleInstall(args: InstallArgs) { ); if (confirmed) { const trustedFolders = loadTrustedFolders(); - await trustedFolders.setValue(resolvedPath, TrustLevel.TRUST_FOLDER); + await trustedFolders.setValue(realPath, TrustLevel.TRUST_FOLDER); } else { throw new Error( - `Installation aborted: Folder "${resolvedPath}" is not trusted.`, + `Installation aborted: Folder "${absolutePath}" is not trusted.`, ); } } diff --git a/packages/cli/src/commands/extensions/uninstall.test.ts b/packages/cli/src/commands/extensions/uninstall.test.ts index 8ae9f6d376..65aed446c5 100644 --- a/packages/cli/src/commands/extensions/uninstall.test.ts +++ b/packages/cli/src/commands/extensions/uninstall.test.ts @@ -28,6 +28,7 @@ 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) => { @@ -38,6 +39,7 @@ vi.mock('../../config/extension-manager.js', async (importOriginal) => { ExtensionManager: vi.fn().mockImplementation(() => ({ uninstallExtension: mockUninstallExtension, loadExtensions: mockLoadExtensions, + getExtensions: mockGetExtensions, setRequestConsent: vi.fn(), setRequestSetting: vi.fn(), })), @@ -93,6 +95,7 @@ describe('extensions uninstall command', () => { afterEach(() => { mockLoadExtensions.mockClear(); mockUninstallExtension.mockClear(); + mockGetExtensions.mockClear(); vi.clearAllMocks(); }); @@ -145,6 +148,41 @@ 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'); @@ -236,13 +274,14 @@ describe('extensions uninstall command', () => { const command = uninstallCommand; it('should have correct command and describe', () => { - expect(command.command).toBe('uninstall '); + 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; } @@ -250,11 +289,12 @@ describe('extensions uninstall command', () => { beforeEach(() => { yargsMock = { positional: vi.fn().mockReturnThis(), + option: vi.fn().mockReturnThis(), check: vi.fn().mockReturnThis(), }; }); - it('should configure positional argument', () => { + it('should configure arguments and options', () => { (command.builder as (yargs: Argv) => Argv)( yargsMock as unknown as Argv, ); @@ -264,18 +304,31 @@ 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', () => { + it('check function should throw for missing names and no --all flag', () => { (command.builder as (yargs: Argv) => Argv)( yargsMock as unknown as Argv, ); const checkCallback = yargsMock.check.mock.calls[0][0]; - expect(() => checkCallback({ names: [] })).toThrow( - 'Please include at least one extension name to uninstall as a positional argument.', + expect(() => checkCallback({ names: [], all: false })).toThrow( + 'Please include at least one extension name to uninstall as a positional argument, or use the --all flag.', ); }); + + 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 () => { @@ -283,10 +336,17 @@ describe('extensions uninstall command', () => { mockUninstallExtension.mockResolvedValue(undefined); const mockCwd = vi.spyOn(process, 'cwd').mockReturnValue('/test/dir'); interface TestArgv { - names: string[]; - [key: string]: unknown; + names?: string[]; + all?: boolean; + _: string[]; + $0: string; } - const argv: TestArgv = { names: ['my-extension'], _: [], $0: '' }; + const argv: TestArgv = { + names: ['my-extension'], + all: false, + _: [], + $0: '', + }; await (command.handler as unknown as (args: TestArgv) => Promise)( argv, ); diff --git a/packages/cli/src/commands/extensions/uninstall.ts b/packages/cli/src/commands/extensions/uninstall.ts index a67a4d3abe..b78b9510df 100644 --- a/packages/cli/src/commands/extensions/uninstall.ts +++ b/packages/cli/src/commands/extensions/uninstall.ts @@ -14,7 +14,8 @@ import { promptForSetting } from '../../config/extensions/extensionSettings.js'; import { exitCli } from '../utils.js'; interface UninstallArgs { - names: string[]; // can be extension names or source URLs. + names?: string[]; // can be extension names or source URLs. + all?: boolean; } export async function handleUninstall(args: UninstallArgs) { @@ -28,8 +29,24 @@ 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 [...new Set(args.names)]) { + for (const name of namesToUninstall) { try { await extensionManager.uninstallExtension(name, false); debugLogger.log(`Extension "${name}" successfully uninstalled.`); @@ -51,7 +68,7 @@ export async function handleUninstall(args: UninstallArgs) { } export const uninstallCommand: CommandModule = { - command: 'uninstall ', + command: 'uninstall [names..]', describe: 'Uninstalls one or more extensions.', builder: (yargs) => yargs @@ -61,10 +78,15 @@ export const uninstallCommand: CommandModule = { type: 'string', array: true, }) + .option('all', { + type: 'boolean', + describe: 'Uninstall all installed extensions.', + default: false, + }) .check((argv) => { - if (!argv.names || argv.names.length === 0) { + if (!argv.all && (!argv.names || argv.names.length === 0)) { throw new Error( - 'Please include at least one extension name to uninstall as a positional argument.', + 'Please include at least one extension name to uninstall as a positional argument, or use the --all flag.', ); } return true; @@ -72,7 +94,9 @@ export const uninstallCommand: CommandModule = { handler: async (argv) => { await handleUninstall({ // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion - names: argv['names'] as string[], + names: argv['names'] as string[] | undefined, + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + all: argv['all'] as boolean, }); await exitCli(); }, diff --git a/packages/cli/src/commands/hooks/migrate.ts b/packages/cli/src/commands/hooks/migrate.ts index 47cc8660d7..36bb2cf9aa 100644 --- a/packages/cli/src/commands/hooks/migrate.ts +++ b/packages/cli/src/commands/hooks/migrate.ts @@ -79,6 +79,7 @@ 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, @@ -93,6 +94,7 @@ 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']; } @@ -140,6 +142,7 @@ function migrateClaudeHooks(claudeConfig: unknown): Record { // Transform matcher if ( 'matcher' in definition && + // eslint-disable-next-line no-restricted-syntax typeof definition['matcher'] === 'string' ) { migratedDef['matcher'] = transformMatcher(definition['matcher']); diff --git a/packages/cli/src/config/config.test.ts b/packages/cli/src/config/config.test.ts index b22b7412cc..a66d5e6589 100644 --- a/packages/cli/src/config/config.test.ts +++ b/packages/cli/src/config/config.test.ts @@ -116,14 +116,16 @@ 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, @@ -847,7 +849,6 @@ describe('Hierarchical Memory Loading (config.ts) - Placeholder Suite', () => { expect(ServerConfig.loadServerHierarchicalMemory).toHaveBeenCalledWith( expect.any(String), [], - false, expect.any(Object), expect.any(ExtensionManager), true, @@ -876,7 +877,6 @@ 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,7 +904,6 @@ describe('Hierarchical Memory Loading (config.ts) - Placeholder Suite', () => { expect(ServerConfig.loadServerHierarchicalMemory).toHaveBeenCalledWith( expect.any(String), [], - false, expect.any(Object), expect.any(ExtensionManager), true, @@ -953,12 +952,6 @@ describe('mergeMcpServers', () => { }); describe('mergeExcludeTools', () => { - const defaultExcludes = new Set([ - SHELL_TOOL_NAME, - EDIT_TOOL_NAME, - WRITE_FILE_TOOL_NAME, - WEB_FETCH_TOOL_NAME, - ]); const originalIsTTY = process.stdin.isTTY; beforeEach(() => { @@ -1080,9 +1073,7 @@ describe('mergeExcludeTools', () => { process.argv = ['node', 'script.js', '-p', 'test']; const argv = await parseArguments(createTestMergedSettings()); const config = await loadCliConfig(settings, 'test-session', argv); - expect(config.getExcludeTools()).toEqual( - new Set([...defaultExcludes, ASK_USER_TOOL_NAME]), - ); + expect(config.getExcludeTools()).toEqual(new Set([ASK_USER_TOOL_NAME])); }); it('should handle settings with excludeTools but no extensions', async () => { @@ -1163,9 +1154,9 @@ describe('Approval mode tool exclusion logic', () => { const config = await loadCliConfig(settings, 'test-session', argv); const excludedTools = config.getExcludeTools(); - expect(excludedTools).toContain(SHELL_TOOL_NAME); - expect(excludedTools).toContain(EDIT_TOOL_NAME); - expect(excludedTools).toContain(WRITE_FILE_TOOL_NAME); + expect(excludedTools).not.toContain(SHELL_TOOL_NAME); + expect(excludedTools).not.toContain(EDIT_TOOL_NAME); + expect(excludedTools).not.toContain(WRITE_FILE_TOOL_NAME); expect(excludedTools).toContain(ASK_USER_TOOL_NAME); }); @@ -1184,9 +1175,9 @@ describe('Approval mode tool exclusion logic', () => { const config = await loadCliConfig(settings, 'test-session', argv); const excludedTools = config.getExcludeTools(); - expect(excludedTools).toContain(SHELL_TOOL_NAME); - expect(excludedTools).toContain(EDIT_TOOL_NAME); - expect(excludedTools).toContain(WRITE_FILE_TOOL_NAME); + expect(excludedTools).not.toContain(SHELL_TOOL_NAME); + expect(excludedTools).not.toContain(EDIT_TOOL_NAME); + expect(excludedTools).not.toContain(WRITE_FILE_TOOL_NAME); expect(excludedTools).toContain(ASK_USER_TOOL_NAME); }); @@ -1205,7 +1196,7 @@ describe('Approval mode tool exclusion logic', () => { const config = await loadCliConfig(settings, 'test-session', argv); const excludedTools = config.getExcludeTools(); - expect(excludedTools).toContain(SHELL_TOOL_NAME); + expect(excludedTools).not.toContain(SHELL_TOOL_NAME); expect(excludedTools).not.toContain(EDIT_TOOL_NAME); expect(excludedTools).not.toContain(WRITE_FILE_TOOL_NAME); expect(excludedTools).toContain(ASK_USER_TOOL_NAME); @@ -1251,9 +1242,9 @@ describe('Approval mode tool exclusion logic', () => { const config = await loadCliConfig(settings, 'test-session', argv); const excludedTools = config.getExcludeTools(); - expect(excludedTools).toContain(SHELL_TOOL_NAME); - expect(excludedTools).toContain(EDIT_TOOL_NAME); - expect(excludedTools).toContain(WRITE_FILE_TOOL_NAME); + expect(excludedTools).not.toContain(SHELL_TOOL_NAME); + expect(excludedTools).not.toContain(EDIT_TOOL_NAME); + expect(excludedTools).not.toContain(WRITE_FILE_TOOL_NAME); expect(excludedTools).toContain(ASK_USER_TOOL_NAME); }); @@ -1315,9 +1306,10 @@ describe('Approval mode tool exclusion logic', () => { const excludedTools = config.getExcludeTools(); expect(excludedTools).toContain('custom_tool'); // From settings - expect(excludedTools).toContain(SHELL_TOOL_NAME); // From approval mode + expect(excludedTools).not.toContain(SHELL_TOOL_NAME); // No longer from approval mode expect(excludedTools).not.toContain(EDIT_TOOL_NAME); // Should be allowed in auto_edit expect(excludedTools).not.toContain(WRITE_FILE_TOOL_NAME); // Should be allowed in auto_edit + expect(excludedTools).toContain(ASK_USER_TOOL_NAME); }); it('should throw an error if YOLO mode is attempted when disableYoloMode is true', async () => { @@ -2164,9 +2156,9 @@ describe('loadCliConfig tool exclusions', () => { 'test-session', argv, ); - expect(config.getExcludeTools()).toContain('run_shell_command'); - expect(config.getExcludeTools()).toContain('replace'); - expect(config.getExcludeTools()).toContain('write_file'); + expect(config.getExcludeTools()).not.toContain('run_shell_command'); + expect(config.getExcludeTools()).not.toContain('replace'); + expect(config.getExcludeTools()).not.toContain('write_file'); expect(config.getExcludeTools()).toContain('ask_user'); }); @@ -2204,7 +2196,7 @@ describe('loadCliConfig tool exclusions', () => { expect(config.getExcludeTools()).not.toContain(SHELL_TOOL_NAME); }); - it('should exclude web-fetch in non-interactive mode when not allowed', async () => { + it('should not exclude web-fetch in non-interactive mode at config level', async () => { process.stdin.isTTY = false; process.argv = ['node', 'script.js', '-p', 'test']; const argv = await parseArguments(createTestMergedSettings()); @@ -2213,7 +2205,7 @@ describe('loadCliConfig tool exclusions', () => { 'test-session', argv, ); - expect(config.getExcludeTools()).toContain(WEB_FETCH_TOOL_NAME); + expect(config.getExcludeTools()).not.toContain(WEB_FETCH_TOOL_NAME); }); it('should not exclude web-fetch in non-interactive mode when allowed', async () => { @@ -3326,11 +3318,11 @@ describe('Policy Engine Integration in loadCliConfig', () => { await loadCliConfig(settings, 'test-session', argv); - // In non-interactive mode, ShellTool, etc. are excluded + // In non-interactive mode, only ask_user is excluded by default expect(ServerConfig.createPolicyEngineConfig).toHaveBeenCalledWith( expect.objectContaining({ tools: expect.objectContaining({ - exclude: expect.arrayContaining([SHELL_TOOL_NAME]), + exclude: expect.arrayContaining([ASK_USER_TOOL_NAME]), }), }), expect.anything(), diff --git a/packages/cli/src/config/config.ts b/packages/cli/src/config/config.ts index b478d67478..a8c85975e9 100755 --- a/packages/cli/src/config/config.ts +++ b/packages/cli/src/config/config.ts @@ -19,16 +19,11 @@ import { DEFAULT_FILE_FILTERING_OPTIONS, DEFAULT_MEMORY_FILE_FILTERING_OPTIONS, FileDiscoveryService, - WRITE_FILE_TOOL_NAME, - SHELL_TOOL_NAMES, - SHELL_TOOL_NAME, resolveTelemetrySettings, FatalConfigError, getPty, - EDIT_TOOL_NAME, debugLogger, loadServerHierarchicalMemory, - WEB_FETCH_TOOL_NAME, ASK_USER_TOOL_NAME, getVersion, PREVIEW_GEMINI_MODEL_AUTO, @@ -81,7 +76,8 @@ export interface CliArgs { policy: string[] | undefined; allowedMcpServerNames: string[] | undefined; allowedTools: string[] | undefined; - experimentalAcp: boolean | undefined; + acp?: boolean; + experimentalAcp?: boolean; extensions: string[] | undefined; listExtensions: boolean | undefined; resume: string | typeof RESUME_LATEST | undefined; @@ -177,10 +173,15 @@ export async function parseArguments( .filter(Boolean), ), }) - .option('experimental-acp', { + .option('acp', { type: 'boolean', description: 'Starts the agent in ACP mode', }) + .option('experimental-acp', { + type: 'boolean', + description: + 'Starts the agent in ACP mode (deprecated, use --acp instead)', + }) .option('allowed-mcp-server-names', { type: 'array', string: true, @@ -395,36 +396,6 @@ export async function parseArguments( return result as unknown as CliArgs; } -/** - * Creates a filter function to determine if a tool should be excluded. - * - * In non-interactive mode, we want to disable tools that require user - * interaction to prevent the CLI from hanging. This function creates a predicate - * that returns `true` if a tool should be excluded. - * - * A tool is excluded if it's not in the `allowedToolsSet`. The shell tool - * has a special case: it's not excluded if any of its subcommands - * are in the `allowedTools` list. - * - * @param allowedTools A list of explicitly allowed tool names. - * @param allowedToolsSet A set of explicitly allowed tool names for quick lookups. - * @returns A function that takes a tool name and returns `true` if it should be excluded. - */ -function createToolExclusionFilter( - allowedTools: string[], - allowedToolsSet: Set, -) { - return (tool: string): boolean => { - if (tool === SHELL_TOOL_NAME) { - // If any of the allowed tools is ShellTool (even with subcommands), don't exclude it. - return !allowedTools.some((allowed) => - SHELL_TOOL_NAMES.some((shellName) => allowed.startsWith(shellName)), - ); - } - return !allowedToolsSet.has(tool); - }; -} - export function isDebugMode(argv: CliArgs): boolean { return ( argv.debug || @@ -528,7 +499,6 @@ export async function loadCliConfig( settings.context?.loadMemoryFromIncludeDirectories || false ? includeDirectories : [], - debugMode, fileService, extensionManager, trustedFolder, @@ -632,54 +602,20 @@ export async function loadCliConfig( // -i/--prompt-interactive forces interactive mode with an initial prompt const interactive = !!argv.promptInteractive || + !!argv.acp || !!argv.experimentalAcp || (!isHeadlessMode({ prompt: argv.prompt, query: argv.query }) && !argv.isCommand); const allowedTools = argv.allowedTools || settings.tools?.allowed || []; - const allowedToolsSet = new Set(allowedTools); // In non-interactive mode, exclude tools that require a prompt. const extraExcludes: string[] = []; if (!interactive) { - // ask_user requires user interaction and must be excluded in all - // non-interactive modes, regardless of the approval mode. + // The Policy Engine natively handles headless safety by translating ASK_USER + // decisions to DENY. However, we explicitly block ask_user here to guarantee + // it can never be allowed via a high-priority policy rule when no human is present. extraExcludes.push(ASK_USER_TOOL_NAME); - - const defaultExcludes = [ - SHELL_TOOL_NAME, - EDIT_TOOL_NAME, - WRITE_FILE_TOOL_NAME, - WEB_FETCH_TOOL_NAME, - ]; - const autoEditExcludes = [SHELL_TOOL_NAME]; - - const toolExclusionFilter = createToolExclusionFilter( - allowedTools, - allowedToolsSet, - ); - - switch (approvalMode) { - case ApprovalMode.PLAN: - // In plan non-interactive mode, all tools that require approval are excluded. - // TODO(#16625): Replace this default exclusion logic with specific rules for plan mode. - extraExcludes.push(...defaultExcludes.filter(toolExclusionFilter)); - break; - case ApprovalMode.DEFAULT: - // In default non-interactive mode, all tools that require approval are excluded. - extraExcludes.push(...defaultExcludes.filter(toolExclusionFilter)); - break; - case ApprovalMode.AUTO_EDIT: - // In auto-edit non-interactive mode, only tools that still require a prompt are excluded. - extraExcludes.push(...autoEditExcludes.filter(toolExclusionFilter)); - break; - case ApprovalMode.YOLO: - // No extra excludes for YOLO mode. - break; - default: - // This should never happen due to validation earlier, but satisfies the linter - break; - } } const excludeTools = mergeExcludeTools(settings, extraExcludes); @@ -758,6 +694,7 @@ export async function loadCliConfig( } return new Config({ + acpMode: !!argv.acp || !!argv.experimentalAcp, sessionId, clientVersion: await getVersion(), embeddingModel: DEFAULT_GEMINI_EMBEDDING_MODEL, @@ -821,7 +758,7 @@ export async function loadCliConfig( bugCommand: settings.advanced?.bugCommand, model: resolvedModel, maxSessionTurns: settings.model?.maxSessionTurns, - experimentalZedIntegration: argv.experimentalAcp || false, + listExtensions: argv.listExtensions || false, listSessions: argv.listSessions || false, deleteSession: argv.deleteSession, @@ -830,6 +767,7 @@ export async function loadCliConfig( enableExtensionReloading: settings.experimental?.extensionReloading, enableAgents: settings.experimental?.enableAgents, plan: settings.experimental?.plan, + tracker: settings.experimental?.taskTracker, directWebFetch: settings.experimental?.directWebFetch, planSettings: settings.general?.plan?.directory ? settings.general.plan @@ -867,6 +805,7 @@ 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, diff --git a/packages/cli/src/config/extension-manager.test.ts b/packages/cli/src/config/extension-manager.test.ts index 4ab52e24b5..a5fb822cdb 100644 --- a/packages/cli/src/config/extension-manager.test.ts +++ b/packages/cli/src/config/extension-manager.test.ts @@ -12,6 +12,13 @@ import { ExtensionManager } from './extension-manager.js'; import { createTestMergedSettings } from './settings.js'; import { createExtension } from '../test-utils/createExtension.js'; import { EXTENSIONS_DIRECTORY_NAME } from './extensions/variables.js'; +import { + TrustLevel, + loadTrustedFolders, + isWorkspaceTrusted, +} from './trustedFolders.js'; +import { getRealPath } from '@google/gemini-cli-core'; +import type { MergedSettings } from './settings.js'; const mockHomedir = vi.hoisted(() => vi.fn(() => '/tmp/mock-home')); @@ -185,4 +192,157 @@ describe('ExtensionManager', () => { fs.rmSync(externalDir, { recursive: true, force: true }); }); }); + + describe('symlink handling', () => { + let extensionDir: string; + let symlinkDir: string; + + beforeEach(() => { + extensionDir = path.join(tempHomeDir, 'extension'); + symlinkDir = path.join(tempHomeDir, 'symlink-ext'); + + fs.mkdirSync(extensionDir, { recursive: true }); + + fs.writeFileSync( + path.join(extensionDir, 'gemini-extension.json'), + JSON.stringify({ name: 'test-ext', version: '1.0.0' }), + ); + + fs.symlinkSync(extensionDir, symlinkDir, 'dir'); + }); + + it('preserves symlinks in installMetadata.source when linking', async () => { + const manager = new ExtensionManager({ + workspaceDir: tempWorkspaceDir, + settings: { + security: { + folderTrust: { enabled: false }, // Disable trust for simplicity in this test + }, + experimental: { extensionConfig: false }, + admin: { extensions: { enabled: true }, mcp: { enabled: true } }, + hooksConfig: { enabled: true }, + } as unknown as MergedSettings, + requestConsent: () => Promise.resolve(true), + requestSetting: null, + }); + + // Trust the workspace to allow installation + const trustedFolders = loadTrustedFolders(); + await trustedFolders.setValue(tempWorkspaceDir, TrustLevel.TRUST_FOLDER); + + const installMetadata = { + source: symlinkDir, + type: 'link' as const, + }; + + await manager.loadExtensions(); + const extension = await manager.installOrUpdateExtension(installMetadata); + + // Desired behavior: it preserves symlinks (if they were absolute or relative as provided) + expect(extension.installMetadata?.source).toBe(symlinkDir); + }); + + it('works with the new install command logic (preserves symlink but trusts real path)', async () => { + // This simulates the logic in packages/cli/src/commands/extensions/install.ts + const absolutePath = path.resolve(symlinkDir); + const realPath = getRealPath(absolutePath); + + const settings = { + security: { + folderTrust: { enabled: true }, + }, + experimental: { extensionConfig: false }, + admin: { extensions: { enabled: true }, mcp: { enabled: true } }, + hooksConfig: { enabled: true }, + } as unknown as MergedSettings; + + // Trust the REAL path + const trustedFolders = loadTrustedFolders(); + await trustedFolders.setValue(realPath, TrustLevel.TRUST_FOLDER); + + // Check trust of the symlink path + const trustResult = isWorkspaceTrusted(settings, absolutePath); + expect(trustResult.isTrusted).toBe(true); + + const manager = new ExtensionManager({ + workspaceDir: tempWorkspaceDir, + settings, + requestConsent: () => Promise.resolve(true), + requestSetting: null, + }); + + const installMetadata = { + source: absolutePath, + type: 'link' as const, + }; + + await manager.loadExtensions(); + const extension = await manager.installOrUpdateExtension(installMetadata); + + expect(extension.installMetadata?.source).toBe(absolutePath); + expect(extension.installMetadata?.source).not.toBe(realPath); + }); + + it('enforces allowedExtensions using the real path', async () => { + const absolutePath = path.resolve(symlinkDir); + const realPath = getRealPath(absolutePath); + + const settings = { + security: { + folderTrust: { enabled: false }, + // Only allow the real path, not the symlink path + allowedExtensions: [realPath.replace(/\\/g, '\\\\')], + }, + experimental: { extensionConfig: false }, + admin: { extensions: { enabled: true }, mcp: { enabled: true } }, + hooksConfig: { enabled: true }, + } as unknown as MergedSettings; + + const manager = new ExtensionManager({ + workspaceDir: tempWorkspaceDir, + settings, + requestConsent: () => Promise.resolve(true), + requestSetting: null, + }); + + const installMetadata = { + source: absolutePath, + type: 'link' as const, + }; + + await manager.loadExtensions(); + // This should pass because realPath is allowed + const extension = await manager.installOrUpdateExtension(installMetadata); + expect(extension.name).toBe('test-ext'); + + // Now try with a settings that only allows the symlink path string + const settingsOnlySymlink = { + security: { + folderTrust: { enabled: false }, + // Only allow the symlink path string explicitly + allowedExtensions: [absolutePath.replace(/\\/g, '\\\\')], + }, + experimental: { extensionConfig: false }, + admin: { extensions: { enabled: true }, mcp: { enabled: true } }, + hooksConfig: { enabled: true }, + } as unknown as MergedSettings; + + const manager2 = new ExtensionManager({ + workspaceDir: tempWorkspaceDir, + settings: settingsOnlySymlink, + requestConsent: () => Promise.resolve(true), + requestSetting: null, + }); + + // This should FAIL because it checks the real path against the pattern + // (Unless symlinkDir === extensionDir, which shouldn't happen in this test setup) + if (absolutePath !== realPath) { + await expect( + manager2.installOrUpdateExtension(installMetadata), + ).rejects.toThrow( + /is not allowed by the "allowedExtensions" security setting/, + ); + } + }); + }); }); diff --git a/packages/cli/src/config/extension-manager.ts b/packages/cli/src/config/extension-manager.ts index a9fce44635..678350ba49 100644 --- a/packages/cli/src/config/extension-manager.ts +++ b/packages/cli/src/config/extension-manager.ts @@ -161,7 +161,9 @@ export class ExtensionManager extends ExtensionLoader { const extensionAllowed = this.settings.security?.allowedExtensions.some( (pattern) => { try { - return new RegExp(pattern).test(installMetadata.source); + return new RegExp(pattern).test( + getRealPath(installMetadata.source), + ); } catch (e) { throw new Error( `Invalid regex pattern in allowedExtensions setting: "${pattern}. Error: ${getErrorMessage(e)}`, @@ -210,11 +212,9 @@ export class ExtensionManager extends ExtensionLoader { await fs.promises.mkdir(extensionsDir, { recursive: true }); if (installMetadata.type === 'local' || installMetadata.type === 'link') { - installMetadata.source = getRealPath( - path.isAbsolute(installMetadata.source) - ? installMetadata.source - : path.resolve(this.workspaceDir, installMetadata.source), - ); + installMetadata.source = path.isAbsolute(installMetadata.source) + ? installMetadata.source + : path.resolve(this.workspaceDir, installMetadata.source); } let tempDir: string | undefined; @@ -262,7 +262,7 @@ Would you like to attempt to install via "git clone" instead?`, installMetadata.type === 'local' || installMetadata.type === 'link' ) { - localSourcePath = installMetadata.source; + localSourcePath = getRealPath(installMetadata.source); } else { throw new Error(`Unsupported install type: ${installMetadata.type}`); } @@ -638,7 +638,9 @@ Would you like to attempt to install via "git clone" instead?`, const extensionAllowed = this.settings.security?.allowedExtensions.some( (pattern) => { try { - return new RegExp(pattern).test(installMetadata?.source); + return new RegExp(pattern).test( + getRealPath(installMetadata?.source ?? ''), + ); } catch (e) { throw new Error( `Invalid regex pattern in allowedExtensions setting: "${pattern}. Error: ${getErrorMessage(e)}`, diff --git a/packages/cli/src/config/extensions/__snapshots__/consent-consent-maybeRequestConsentOrFail-consent-string-generation-should-request-consent-if-skills-change.snap.svg b/packages/cli/src/config/extensions/__snapshots__/consent-consent-maybeRequestConsentOrFail-consent-string-generation-should-request-consent-if-skills-change.snap.svg index 6f5879df4c..fbaaa599d4 100644 --- a/packages/cli/src/config/extensions/__snapshots__/consent-consent-maybeRequestConsentOrFail-consent-string-generation-should-request-consent-if-skills-change.snap.svg +++ b/packages/cli/src/config/extensions/__snapshots__/consent-consent-maybeRequestConsentOrFail-consent-string-generation-should-request-consent-if-skills-change.snap.svg @@ -10,11 +10,15 @@ * server2 (remote): https://remote.com This extension will append info to your gemini.md context using my-context.md This extension will exclude the following core tools: tool1,tool2 - Agent Skills: + Agent Skills: This extension will install the following agent skills: - * skill1: desc1 + * + skill1 + : desc1 (Source: /mock/temp/dir/skill1/SKILL.md) (2 items in directory) - * skill2: desc2 + * + skill2 + : desc2 (Source: /mock/temp/dir/skill2/SKILL.md) (1 items in directory) The extension you are about to install may have been created by a third-party developer and sourced from a public repository. Google does not vet, endorse, or guarantee the functionality or security diff --git a/packages/cli/src/config/extensions/__snapshots__/consent-consent-maybeRequestConsentOrFail-consent-string-generation-should-show-a-warning-if-the-skill-directory-cannot-be-read.snap.svg b/packages/cli/src/config/extensions/__snapshots__/consent-consent-maybeRequestConsentOrFail-consent-string-generation-should-show-a-warning-if-the-skill-directory-cannot-be-read.snap.svg index 3fff32664a..b57af41589 100644 --- a/packages/cli/src/config/extensions/__snapshots__/consent-consent-maybeRequestConsentOrFail-consent-string-generation-should-show-a-warning-if-the-skill-directory-cannot-be-read.snap.svg +++ b/packages/cli/src/config/extensions/__snapshots__/consent-consent-maybeRequestConsentOrFail-consent-string-generation-should-show-a-warning-if-the-skill-directory-cannot-be-read.snap.svg @@ -5,9 +5,11 @@ Installing extension "test-ext". - Agent Skills: + Agent Skills: This extension will install the following agent skills: - * locked-skill: A skill in a locked dir + * + locked-skill + : A skill in a locked dir (Source: /mock/temp/dir/locked/SKILL.md) ⚠️ (Could not count items in directory) The extension you are about to install may have been created by a third-party developer and sourced diff --git a/packages/cli/src/config/extensions/__snapshots__/consent-consent-skillsConsentString-should-generate-a-consent-string-for-skills.snap.svg b/packages/cli/src/config/extensions/__snapshots__/consent-consent-skillsConsentString-should-generate-a-consent-string-for-skills.snap.svg index c52724836e..32b9d8e0a3 100644 --- a/packages/cli/src/config/extensions/__snapshots__/consent-consent-skillsConsentString-should-generate-a-consent-string-for-skills.snap.svg +++ b/packages/cli/src/config/extensions/__snapshots__/consent-consent-skillsConsentString-should-generate-a-consent-string-for-skills.snap.svg @@ -6,7 +6,9 @@ Installing agent skill(s) from "https://example.com/repo.git". The following agent skill(s) will be installing: - * skill1: desc1 + * + skill1 + : desc1 (Source: /mock/temp/dir/skill1/SKILL.md) (1 items in directory) Install Destination: /mock/target/dir Agent skills inject specialized instructions and domain-specific knowledge into the agent's system diff --git a/packages/cli/src/config/footerItems.test.ts b/packages/cli/src/config/footerItems.test.ts new file mode 100644 index 0000000000..420246811b --- /dev/null +++ b/packages/cli/src/config/footerItems.test.ts @@ -0,0 +1,91 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, it, expect } from 'vitest'; +import { deriveItemsFromLegacySettings } from './footerItems.js'; +import { createMockSettings } from '../test-utils/settings.js'; + +describe('deriveItemsFromLegacySettings', () => { + it('returns defaults when no legacy settings are customized', () => { + const settings = createMockSettings({ + ui: { footer: { hideContextPercentage: true } }, + }).merged; + const items = deriveItemsFromLegacySettings(settings); + expect(items).toEqual([ + 'workspace', + 'git-branch', + 'sandbox', + 'model-name', + 'quota', + ]); + }); + + it('removes workspace when hideCWD is true', () => { + const settings = createMockSettings({ + ui: { footer: { hideCWD: true, hideContextPercentage: true } }, + }).merged; + const items = deriveItemsFromLegacySettings(settings); + expect(items).not.toContain('workspace'); + }); + + it('removes sandbox when hideSandboxStatus is true', () => { + const settings = createMockSettings({ + ui: { footer: { hideSandboxStatus: true, hideContextPercentage: true } }, + }).merged; + const items = deriveItemsFromLegacySettings(settings); + expect(items).not.toContain('sandbox'); + }); + + it('removes model-name, context-used, and quota when hideModelInfo is true', () => { + const settings = createMockSettings({ + ui: { footer: { hideModelInfo: true, hideContextPercentage: true } }, + }).merged; + const items = deriveItemsFromLegacySettings(settings); + expect(items).not.toContain('model-name'); + expect(items).not.toContain('context-used'); + expect(items).not.toContain('quota'); + }); + + it('includes context-used when hideContextPercentage is false', () => { + const settings = createMockSettings({ + ui: { footer: { hideContextPercentage: false } }, + }).merged; + const items = deriveItemsFromLegacySettings(settings); + expect(items).toContain('context-used'); + // Should be after model-name + const modelIdx = items.indexOf('model-name'); + const contextIdx = items.indexOf('context-used'); + expect(contextIdx).toBe(modelIdx + 1); + }); + + it('includes memory-usage when showMemoryUsage is true', () => { + const settings = createMockSettings({ + ui: { showMemoryUsage: true, footer: { hideContextPercentage: true } }, + }).merged; + const items = deriveItemsFromLegacySettings(settings); + expect(items).toContain('memory-usage'); + }); + + it('handles combination of settings', () => { + const settings = createMockSettings({ + ui: { + showMemoryUsage: true, + footer: { + hideCWD: true, + hideModelInfo: true, + hideContextPercentage: false, + }, + }, + }).merged; + const items = deriveItemsFromLegacySettings(settings); + expect(items).toEqual([ + 'git-branch', + 'sandbox', + 'context-used', + 'memory-usage', + ]); + }); +}); diff --git a/packages/cli/src/config/footerItems.ts b/packages/cli/src/config/footerItems.ts new file mode 100644 index 0000000000..8410d0b5ec --- /dev/null +++ b/packages/cli/src/config/footerItems.ts @@ -0,0 +1,132 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import type { MergedSettings } from './settings.js'; + +export const ALL_ITEMS = [ + { + id: 'workspace', + header: 'workspace (/directory)', + description: 'Current working directory', + }, + { + id: 'git-branch', + header: 'branch', + description: 'Current git branch name (not shown when unavailable)', + }, + { + id: 'sandbox', + header: 'sandbox', + description: 'Sandbox type and trust indicator', + }, + { + id: 'model-name', + header: '/model', + description: 'Current model identifier', + }, + { + id: 'context-used', + header: 'context', + description: 'Percentage of context window used', + }, + { + id: 'quota', + header: '/stats', + description: 'Remaining usage on daily limit (not shown when unavailable)', + }, + { + id: 'memory-usage', + header: 'memory', + description: 'Memory used by the application', + }, + { + id: 'session-id', + header: 'session', + description: 'Unique identifier for the current session', + }, + { + id: 'code-changes', + header: 'diff', + description: 'Lines added/removed in the session (not shown when zero)', + }, + { + id: 'token-count', + header: 'tokens', + description: 'Total tokens used in the session (not shown when zero)', + }, +] as const; + +export type FooterItemId = (typeof ALL_ITEMS)[number]['id']; + +export const DEFAULT_ORDER = [ + 'workspace', + 'git-branch', + 'sandbox', + 'model-name', + 'context-used', + 'quota', + 'memory-usage', + 'session-id', + 'code-changes', + 'token-count', +]; + +export function deriveItemsFromLegacySettings( + settings: MergedSettings, +): string[] { + const defaults = [ + 'workspace', + 'git-branch', + 'sandbox', + 'model-name', + 'quota', + ]; + const items = [...defaults]; + + const remove = (arr: string[], id: string) => { + const idx = arr.indexOf(id); + if (idx !== -1) arr.splice(idx, 1); + }; + + if (settings.ui.footer.hideCWD) remove(items, 'workspace'); + if (settings.ui.footer.hideSandboxStatus) remove(items, 'sandbox'); + if (settings.ui.footer.hideModelInfo) { + remove(items, 'model-name'); + remove(items, 'context-used'); + remove(items, 'quota'); + } + if ( + !settings.ui.footer.hideContextPercentage && + !items.includes('context-used') + ) { + const modelIdx = items.indexOf('model-name'); + if (modelIdx !== -1) items.splice(modelIdx + 1, 0, 'context-used'); + else items.push('context-used'); + } + if (settings.ui.showMemoryUsage) items.push('memory-usage'); + + return items; +} + +const VALID_IDS: Set = new Set(ALL_ITEMS.map((i) => i.id)); + +/** + * Resolves the ordered list and selected set of footer items from settings. + * Used by FooterConfigDialog to initialize and reset state. + */ +export function resolveFooterState(settings: MergedSettings): { + orderedIds: string[]; + selectedIds: Set; +} { + const source = ( + settings.ui?.footer?.items ?? deriveItemsFromLegacySettings(settings) + ).filter((id: string) => VALID_IDS.has(id)); + const others = DEFAULT_ORDER.filter((id) => !source.includes(id)); + return { + orderedIds: [...source, ...others], + selectedIds: new Set(source), + }; +} diff --git a/packages/cli/src/config/keyBindings.test.ts b/packages/cli/src/config/keyBindings.test.ts index c2abc32d27..e450e68b71 100644 --- a/packages/cli/src/config/keyBindings.test.ts +++ b/packages/cli/src/config/keyBindings.test.ts @@ -58,46 +58,6 @@ describe('keyBindings config', () => { const config: KeyBindingConfig = defaultKeyBindings; expect(config[Command.HOME]).toBeDefined(); }); - - it('should have correct specific bindings', () => { - // Verify navigation ignores shift - const navUp = defaultKeyBindings[Command.NAVIGATION_UP]; - expect(navUp).toContainEqual({ key: 'up', shift: false }); - - const navDown = defaultKeyBindings[Command.NAVIGATION_DOWN]; - expect(navDown).toContainEqual({ key: 'down', shift: false }); - - // Verify dialog navigation - const dialogNavUp = defaultKeyBindings[Command.DIALOG_NAVIGATION_UP]; - expect(dialogNavUp).toContainEqual({ key: 'up', shift: false }); - expect(dialogNavUp).toContainEqual({ key: 'k', shift: false }); - - const dialogNavDown = defaultKeyBindings[Command.DIALOG_NAVIGATION_DOWN]; - expect(dialogNavDown).toContainEqual({ key: 'down', shift: false }); - expect(dialogNavDown).toContainEqual({ key: 'j', shift: false }); - - // Verify physical home/end keys for cursor movement - expect(defaultKeyBindings[Command.HOME]).toContainEqual({ - key: 'home', - ctrl: false, - shift: false, - }); - expect(defaultKeyBindings[Command.END]).toContainEqual({ - key: 'end', - ctrl: false, - shift: false, - }); - - // Verify physical home/end keys for scrolling - expect(defaultKeyBindings[Command.SCROLL_HOME]).toContainEqual({ - key: 'home', - ctrl: true, - }); - expect(defaultKeyBindings[Command.SCROLL_END]).toContainEqual({ - key: 'end', - ctrl: true, - }); - }); }); describe('command metadata', () => { diff --git a/packages/cli/src/config/keyBindings.ts b/packages/cli/src/config/keyBindings.ts index 3122acef1d..e2260d99d8 100644 --- a/packages/cli/src/config/keyBindings.ts +++ b/packages/cli/src/config/keyBindings.ts @@ -134,27 +134,12 @@ export const defaultKeyBindings: KeyBindingConfig = { [Command.EXIT]: [{ key: 'd', ctrl: true }], // Cursor Movement - [Command.HOME]: [ - { key: 'a', ctrl: true }, - { key: 'home', shift: false, ctrl: false }, - ], - [Command.END]: [ - { key: 'e', ctrl: true }, - { key: 'end', shift: false, ctrl: false }, - ], - [Command.MOVE_UP]: [ - { key: 'up', shift: false, alt: false, ctrl: false, cmd: false }, - ], - [Command.MOVE_DOWN]: [ - { key: 'down', shift: false, alt: false, ctrl: false, cmd: false }, - ], - [Command.MOVE_LEFT]: [ - { key: 'left', shift: false, alt: false, ctrl: false, cmd: false }, - ], - [Command.MOVE_RIGHT]: [ - { key: 'right', shift: false, alt: false, ctrl: false, cmd: false }, - { key: 'f', ctrl: true }, - ], + [Command.HOME]: [{ key: 'a', ctrl: true }, { key: 'home' }], + [Command.END]: [{ key: 'e', ctrl: true }, { key: 'end' }], + [Command.MOVE_UP]: [{ key: 'up' }], + [Command.MOVE_DOWN]: [{ key: 'down' }], + [Command.MOVE_LEFT]: [{ key: 'left' }], + [Command.MOVE_RIGHT]: [{ key: 'right' }, { key: 'f', ctrl: true }], [Command.MOVE_WORD_LEFT]: [ { key: 'left', ctrl: true }, { key: 'left', alt: true }, @@ -183,8 +168,8 @@ export const defaultKeyBindings: KeyBindingConfig = { [Command.DELETE_CHAR_LEFT]: [{ key: 'backspace' }, { key: 'h', ctrl: true }], [Command.DELETE_CHAR_RIGHT]: [{ key: 'delete' }, { key: 'd', ctrl: true }], [Command.UNDO]: [ - { key: 'z', cmd: true, shift: false }, - { key: 'z', alt: true, shift: false }, + { key: 'z', cmd: true }, + { key: 'z', alt: true }, ], [Command.REDO]: [ { key: 'z', ctrl: true, shift: true }, @@ -207,56 +192,33 @@ export const defaultKeyBindings: KeyBindingConfig = { [Command.PAGE_DOWN]: [{ key: 'pagedown' }], // History & Search - [Command.HISTORY_UP]: [{ key: 'p', shift: false, ctrl: true }], - [Command.HISTORY_DOWN]: [{ key: 'n', shift: false, ctrl: true }], + [Command.HISTORY_UP]: [{ key: 'p', ctrl: true }], + [Command.HISTORY_DOWN]: [{ key: 'n', ctrl: true }], [Command.REVERSE_SEARCH]: [{ key: 'r', ctrl: true }], - [Command.REWIND]: [{ key: 'double escape' }], - [Command.SUBMIT_REVERSE_SEARCH]: [{ key: 'return', ctrl: false }], - [Command.ACCEPT_SUGGESTION_REVERSE_SEARCH]: [{ key: 'tab', shift: false }], + [Command.REWIND]: [{ key: 'double escape' }], // for documentation only + [Command.SUBMIT_REVERSE_SEARCH]: [{ key: 'return' }], + [Command.ACCEPT_SUGGESTION_REVERSE_SEARCH]: [{ key: 'tab' }], // Navigation - [Command.NAVIGATION_UP]: [{ key: 'up', shift: false }], - [Command.NAVIGATION_DOWN]: [{ key: 'down', shift: false }], + [Command.NAVIGATION_UP]: [{ key: 'up' }], + [Command.NAVIGATION_DOWN]: [{ key: 'down' }], // Navigation shortcuts appropriate for dialogs where we do not need to accept // text input. - [Command.DIALOG_NAVIGATION_UP]: [ - { key: 'up', shift: false }, - { key: 'k', shift: false }, - ], - [Command.DIALOG_NAVIGATION_DOWN]: [ - { key: 'down', shift: false }, - { key: 'j', shift: false }, - ], - [Command.DIALOG_NEXT]: [{ key: 'tab', shift: false }], + [Command.DIALOG_NAVIGATION_UP]: [{ key: 'up' }, { key: 'k' }], + [Command.DIALOG_NAVIGATION_DOWN]: [{ key: 'down' }, { key: 'j' }], + [Command.DIALOG_NEXT]: [{ key: 'tab' }], [Command.DIALOG_PREV]: [{ key: 'tab', shift: true }], // Suggestions & Completions - [Command.ACCEPT_SUGGESTION]: [ - { key: 'tab', shift: false }, - { key: 'return', ctrl: false }, - ], - [Command.COMPLETION_UP]: [ - { key: 'up', shift: false }, - { key: 'p', shift: false, ctrl: true }, - ], - [Command.COMPLETION_DOWN]: [ - { key: 'down', shift: false }, - { key: 'n', shift: false, ctrl: true }, - ], + [Command.ACCEPT_SUGGESTION]: [{ key: 'tab' }, { key: 'return' }], + [Command.COMPLETION_UP]: [{ key: 'up' }, { key: 'p', ctrl: true }], + [Command.COMPLETION_DOWN]: [{ key: 'down' }, { key: 'n', ctrl: true }], [Command.EXPAND_SUGGESTION]: [{ key: 'right' }], [Command.COLLAPSE_SUGGESTION]: [{ key: 'left' }], // Text Input // Must also exclude shift to allow shift+enter for newline - [Command.SUBMIT]: [ - { - key: 'return', - shift: false, - alt: false, - ctrl: false, - cmd: false, - }, - ], + [Command.SUBMIT]: [{ key: 'return' }], [Command.NEWLINE]: [ { key: 'return', ctrl: true }, { key: 'return', cmd: true }, @@ -283,19 +245,17 @@ export const defaultKeyBindings: KeyBindingConfig = { [Command.TOGGLE_BACKGROUND_SHELL_LIST]: [{ key: 'l', ctrl: true }], [Command.KILL_BACKGROUND_SHELL]: [{ key: 'k', ctrl: true }], [Command.UNFOCUS_BACKGROUND_SHELL]: [{ key: 'tab', shift: true }], - [Command.UNFOCUS_BACKGROUND_SHELL_LIST]: [{ key: 'tab', shift: false }], - [Command.SHOW_BACKGROUND_SHELL_UNFOCUS_WARNING]: [ - { key: 'tab', shift: false }, - ], - [Command.SHOW_SHELL_INPUT_UNFOCUS_WARNING]: [{ key: 'tab', shift: false }], + [Command.UNFOCUS_BACKGROUND_SHELL_LIST]: [{ key: 'tab' }], + [Command.SHOW_BACKGROUND_SHELL_UNFOCUS_WARNING]: [{ key: 'tab' }], + [Command.SHOW_SHELL_INPUT_UNFOCUS_WARNING]: [{ key: 'tab' }], [Command.BACKGROUND_SHELL_SELECT]: [{ key: 'return' }], [Command.BACKGROUND_SHELL_ESCAPE]: [{ key: 'escape' }], [Command.SHOW_MORE_LINES]: [{ key: 'o', ctrl: true }], [Command.EXPAND_PASTE]: [{ key: 'o', ctrl: true }], - [Command.FOCUS_SHELL_INPUT]: [{ key: 'tab', shift: false }], + [Command.FOCUS_SHELL_INPUT]: [{ key: 'tab' }], [Command.UNFOCUS_SHELL_INPUT]: [{ key: 'tab', shift: true }], [Command.CLEAR_SCREEN]: [{ key: 'l', ctrl: true }], - [Command.RESTART_APP]: [{ key: 'r' }], + [Command.RESTART_APP]: [{ key: 'r' }, { key: 'r', shift: true }], [Command.SUSPEND_APP]: [{ key: 'z', ctrl: true }], }; diff --git a/packages/cli/src/config/policy-engine.integration.test.ts b/packages/cli/src/config/policy-engine.integration.test.ts index 02515815d0..71d5f49e59 100644 --- a/packages/cli/src/config/policy-engine.integration.test.ts +++ b/packages/cli/src/config/policy-engine.integration.test.ts @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { describe, it, expect, vi } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { ApprovalMode, PolicyDecision, @@ -29,6 +29,10 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => { }); describe('Policy Engine Integration Tests', () => { + beforeEach(() => vi.stubEnv('GEMINI_SYSTEM_MD', '')); + + afterEach(() => vi.unstubAllEnvs()); + describe('Policy configuration produces valid PolicyEngine config', () => { it('should create a working PolicyEngine from basic settings', async () => { const settings: Settings = { @@ -89,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: 'allowed-server__tool1' }, undefined)) + (await engine.check({ name: 'mcp_allowed-server_tool1' }, undefined)) .decision, ).toBe(PolicyDecision.ALLOW); expect( ( await engine.check( - { name: 'allowed-server__another_tool' }, + { name: 'mcp_allowed-server_another_tool' }, undefined, ) ).decision, @@ -103,13 +107,13 @@ describe('Policy Engine Integration Tests', () => { // Tools from trusted server should be allowed expect( - (await engine.check({ name: 'trusted-server__tool1' }, undefined)) + (await engine.check({ name: 'mcp_trusted-server_tool1' }, undefined)) .decision, ).toBe(PolicyDecision.ALLOW); expect( ( await engine.check( - { name: 'trusted-server__special_tool' }, + { name: 'mcp_trusted-server_special_tool' }, undefined, ) ).decision, @@ -117,17 +121,17 @@ describe('Policy Engine Integration Tests', () => { // Tools from blocked server should be denied expect( - (await engine.check({ name: 'blocked-server__tool1' }, undefined)) + (await engine.check({ name: 'mcp_blocked-server_tool1' }, undefined)) .decision, ).toBe(PolicyDecision.DENY); expect( - (await engine.check({ name: 'blocked-server__any_tool' }, undefined)) + (await engine.check({ name: 'mcp_blocked-server_any_tool' }, undefined)) .decision, ).toBe(PolicyDecision.DENY); // Tools from unknown servers should use default expect( - (await engine.check({ name: 'unknown-server__tool' }, undefined)) + (await engine.check({ name: 'mcp_unknown-server_tool' }, undefined)) .decision, ).toBe(PolicyDecision.ASK_USER); }); @@ -147,12 +151,16 @@ describe('Policy Engine Integration Tests', () => { // ANY tool with a server name should be allowed expect( - (await engine.check({ name: 'mcp-server__tool' }, 'mcp-server')) + (await engine.check({ name: 'mcp_mcp-server_tool' }, 'mcp-server')) .decision, ).toBe(PolicyDecision.ALLOW); expect( - (await engine.check({ name: 'another-server__tool' }, 'another-server')) - .decision, + ( + await engine.check( + { name: 'mcp_another-server_tool' }, + 'another-server', + ) + ).decision, ).toBe(PolicyDecision.ALLOW); // Built-in tools should NOT be allowed by the MCP wildcard @@ -167,7 +175,7 @@ describe('Policy Engine Integration Tests', () => { allowed: ['my-server'], }, tools: { - exclude: ['my-server__dangerous-tool'], + exclude: ['mcp_my-server_dangerous-tool'], }, }; @@ -180,20 +188,24 @@ 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: 'my-server__safe-tool' }, undefined)) + (await engine.check({ name: 'mcp_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: 'my-server__dangerous-tool' }, undefined)) - .decision, + ( + await engine.check( + { name: 'mcp_my-server_dangerous-tool' }, + undefined, + ) + ).decision, ).toBe(PolicyDecision.DENY); }); it('should handle complex mixed configurations', async () => { const settings: Settings = { tools: { - allowed: ['custom-tool', 'my-server__special-tool'], + allowed: ['custom-tool', 'mcp_my-server_special-tool'], exclude: ['glob', 'dangerous-tool'], }, mcp: { @@ -238,21 +250,21 @@ describe('Policy Engine Integration Tests', () => { (await engine.check({ name: 'custom-tool' }, undefined)).decision, ).toBe(PolicyDecision.ALLOW); expect( - (await engine.check({ name: 'my-server__special-tool' }, undefined)) + (await engine.check({ name: 'mcp_my-server_special-tool' }, undefined)) .decision, ).toBe(PolicyDecision.ALLOW); // MCP server tools expect( - (await engine.check({ name: 'allowed-server__tool' }, undefined)) + (await engine.check({ name: 'mcp_allowed-server_tool' }, undefined)) .decision, ).toBe(PolicyDecision.ALLOW); expect( - (await engine.check({ name: 'trusted-server__tool' }, undefined)) + (await engine.check({ name: 'mcp_trusted-server_tool' }, undefined)) .decision, ).toBe(PolicyDecision.ALLOW); expect( - (await engine.check({ name: 'blocked-server__tool' }, undefined)) + (await engine.check({ name: 'mcp_blocked-server_tool' }, undefined)) .decision, ).toBe(PolicyDecision.DENY); @@ -479,7 +491,7 @@ describe('Policy Engine Integration Tests', () => { expect(blockedToolRule?.priority).toBe(4.4); // Command line exclude const blockedServerRule = rules.find( - (r) => r.toolName === 'blocked-server__*', + (r) => r.toolName === 'mcp_blocked-server_*', ); expect(blockedServerRule?.priority).toBe(4.9); // MCP server exclude @@ -489,11 +501,13 @@ describe('Policy Engine Integration Tests', () => { expect(specificToolRule?.priority).toBe(4.3); // Command line allow const trustedServerRule = rules.find( - (r) => r.toolName === 'trusted-server__*', + (r) => r.toolName === 'mcp_trusted-server_*', ); expect(trustedServerRule?.priority).toBe(4.2); // MCP trusted server - const mcpServerRule = rules.find((r) => r.toolName === 'mcp-server__*'); + const mcpServerRule = rules.find( + (r) => r.toolName === 'mcp_mcp-server_*', + ); expect(mcpServerRule?.priority).toBe(4.1); // MCP allowed server const readOnlyToolRule = rules.find((r) => r.toolName === 'glob'); @@ -505,18 +519,19 @@ describe('Policy Engine Integration Tests', () => { (await engine.check({ name: 'blocked-tool' }, undefined)).decision, ).toBe(PolicyDecision.DENY); expect( - (await engine.check({ name: 'blocked-server__any' }, undefined)) + (await engine.check({ name: 'mcp_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: 'trusted-server__any' }, undefined)) + (await engine.check({ name: 'mcp_trusted-server_any' }, undefined)) .decision, ).toBe(PolicyDecision.ALLOW); expect( - (await engine.check({ name: 'mcp-server__any' }, undefined)).decision, + (await engine.check({ name: 'mcp_mcp-server_any' }, undefined)) + .decision, ).toBe(PolicyDecision.ALLOW); expect((await engine.check({ name: 'glob' }, undefined)).decision).toBe( PolicyDecision.ALLOW, @@ -545,7 +560,7 @@ describe('Policy Engine Integration Tests', () => { // Exclusion (195) should win over trust (90) expect( - (await engine.check({ name: 'conflicted-server__tool' }, undefined)) + (await engine.check({ name: 'mcp_conflicted-server_tool' }, undefined)) .decision, ).toBe(PolicyDecision.DENY); }); @@ -556,7 +571,7 @@ describe('Policy Engine Integration Tests', () => { excluded: ['my-server'], // Priority 195 - DENY }, tools: { - allowed: ['my-server__special-tool'], // Priority 100 - ALLOW + allowed: ['mcp_my-server_special-tool'], // Priority 100 - ALLOW }, }; @@ -569,11 +584,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: 'my-server__special-tool' }, undefined)) + (await engine.check({ name: 'mcp_my-server_special-tool' }, undefined)) .decision, ).toBe(PolicyDecision.DENY); expect( - (await engine.check({ name: 'my-server__other-tool' }, undefined)) + (await engine.check({ name: 'mcp_my-server_other-tool' }, undefined)) .decision, ).toBe(PolicyDecision.DENY); }); @@ -643,13 +658,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 === 'server2__*'); + const server2Rule = rules.find((r) => r.toolName === 'mcp_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 === 'server1__*'); + const server1Rule = rules.find((r) => r.toolName === 'mcp_server1_*'); expect(server1Rule?.priority).toBe(4.1); // Allowed servers (user tier) const globRule = rules.find((r) => r.toolName === 'glob'); diff --git a/packages/cli/src/config/policy.test.ts b/packages/cli/src/config/policy.test.ts index 9baccd3359..8d368bfb91 100644 --- a/packages/cli/src/config/policy.test.ts +++ b/packages/cli/src/config/policy.test.ts @@ -183,7 +183,6 @@ 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 }); diff --git a/packages/cli/src/config/sandboxConfig.test.ts b/packages/cli/src/config/sandboxConfig.test.ts index 14080dc30b..51c4f7d83c 100644 --- a/packages/cli/src/config/sandboxConfig.test.ts +++ b/packages/cli/src/config/sandboxConfig.test.ts @@ -97,7 +97,7 @@ describe('loadSandboxConfig', () => { it('should throw if GEMINI_SANDBOX is an invalid command', async () => { process.env['GEMINI_SANDBOX'] = 'invalid-command'; await expect(loadSandboxConfig({}, {})).rejects.toThrow( - "Invalid sandbox command 'invalid-command'. Must be one of docker, podman, sandbox-exec", + "Invalid sandbox command 'invalid-command'. Must be one of docker, podman, sandbox-exec, runsc, lxc", ); }); @@ -108,6 +108,22 @@ describe('loadSandboxConfig', () => { "Missing sandbox command 'docker' (from GEMINI_SANDBOX)", ); }); + + it('should use lxc if GEMINI_SANDBOX=lxc and it exists', async () => { + process.env['GEMINI_SANDBOX'] = 'lxc'; + mockedCommandExistsSync.mockReturnValue(true); + const config = await loadSandboxConfig({}, {}); + expect(config).toEqual({ command: 'lxc', image: 'default/image' }); + expect(mockedCommandExistsSync).toHaveBeenCalledWith('lxc'); + }); + + it('should throw if GEMINI_SANDBOX=lxc but lxc command does not exist', async () => { + process.env['GEMINI_SANDBOX'] = 'lxc'; + mockedCommandExistsSync.mockReturnValue(false); + await expect(loadSandboxConfig({}, {})).rejects.toThrow( + "Missing sandbox command 'lxc' (from GEMINI_SANDBOX)", + ); + }); }); describe('with sandbox: true', () => { @@ -178,7 +194,7 @@ describe('loadSandboxConfig', () => { await expect( loadSandboxConfig({}, { sandbox: 'invalid-command' }), ).rejects.toThrow( - "Invalid sandbox command 'invalid-command'. Must be one of docker, podman, sandbox-exec", + "Invalid sandbox command 'invalid-command'. Must be one of docker, podman, sandbox-exec, runsc, lxc", ); }); }); @@ -231,4 +247,92 @@ describe('loadSandboxConfig', () => { }, ); }); + + describe('with sandbox: runsc (gVisor)', () => { + beforeEach(() => { + mockedOsPlatform.mockReturnValue('linux'); + mockedCommandExistsSync.mockReturnValue(true); + }); + + it('should use runsc via CLI argument on Linux', async () => { + const config = await loadSandboxConfig({}, { sandbox: 'runsc' }); + + expect(config).toEqual({ command: 'runsc', image: 'default/image' }); + expect(mockedCommandExistsSync).toHaveBeenCalledWith('runsc'); + expect(mockedCommandExistsSync).toHaveBeenCalledWith('docker'); + }); + + it('should use runsc via GEMINI_SANDBOX environment variable', async () => { + process.env['GEMINI_SANDBOX'] = 'runsc'; + const config = await loadSandboxConfig({}, {}); + + expect(config).toEqual({ command: 'runsc', image: 'default/image' }); + expect(mockedCommandExistsSync).toHaveBeenCalledWith('runsc'); + expect(mockedCommandExistsSync).toHaveBeenCalledWith('docker'); + }); + + it('should use runsc via settings file', async () => { + const config = await loadSandboxConfig( + { tools: { sandbox: 'runsc' } }, + {}, + ); + + expect(config).toEqual({ command: 'runsc', image: 'default/image' }); + expect(mockedCommandExistsSync).toHaveBeenCalledWith('runsc'); + expect(mockedCommandExistsSync).toHaveBeenCalledWith('docker'); + }); + + it('should prioritize GEMINI_SANDBOX over CLI and settings', async () => { + process.env['GEMINI_SANDBOX'] = 'runsc'; + const config = await loadSandboxConfig( + { tools: { sandbox: 'docker' } }, + { sandbox: 'podman' }, + ); + + expect(config).toEqual({ command: 'runsc', image: 'default/image' }); + }); + + it('should reject runsc on macOS (Linux-only)', async () => { + mockedOsPlatform.mockReturnValue('darwin'); + + await expect(loadSandboxConfig({}, { sandbox: 'runsc' })).rejects.toThrow( + 'gVisor (runsc) sandboxing is only supported on Linux', + ); + }); + + it('should reject runsc on Windows (Linux-only)', async () => { + mockedOsPlatform.mockReturnValue('win32'); + + await expect(loadSandboxConfig({}, { sandbox: 'runsc' })).rejects.toThrow( + 'gVisor (runsc) sandboxing is only supported on Linux', + ); + }); + + it('should throw if runsc binary not found', async () => { + mockedCommandExistsSync.mockReturnValue(false); + + await expect(loadSandboxConfig({}, { sandbox: 'runsc' })).rejects.toThrow( + "Missing sandbox command 'runsc' (from GEMINI_SANDBOX)", + ); + }); + + it('should throw if Docker not available (runsc requires Docker)', async () => { + mockedCommandExistsSync.mockImplementation((cmd) => cmd === 'runsc'); + + await expect(loadSandboxConfig({}, { sandbox: 'runsc' })).rejects.toThrow( + "runsc (gVisor) requires Docker. Install Docker, or use sandbox: 'docker'.", + ); + }); + + it('should NOT auto-detect runsc when both runsc and docker available', async () => { + mockedCommandExistsSync.mockImplementation( + (cmd) => cmd === 'runsc' || cmd === 'docker', + ); + + const config = await loadSandboxConfig({}, { sandbox: true }); + + expect(config?.command).toBe('docker'); + expect(config?.command).not.toBe('runsc'); + }); + }); }); diff --git a/packages/cli/src/config/sandboxConfig.ts b/packages/cli/src/config/sandboxConfig.ts index 57430becae..968d3e427a 100644 --- a/packages/cli/src/config/sandboxConfig.ts +++ b/packages/cli/src/config/sandboxConfig.ts @@ -27,6 +27,8 @@ const VALID_SANDBOX_COMMANDS: ReadonlyArray = [ 'docker', 'podman', 'sandbox-exec', + 'runsc', + 'lxc', ]; function isSandboxCommand(value: string): value is SandboxConfig['command'] { @@ -63,17 +65,30 @@ function getSandboxCommand( )}`, ); } - // confirm that specified command exists - if (commandExists.sync(sandbox)) { - return sandbox; + // runsc (gVisor) is only supported on Linux + if (sandbox === 'runsc' && os.platform() !== 'linux') { + throw new FatalSandboxError( + 'gVisor (runsc) sandboxing is only supported on Linux', + ); } - throw new FatalSandboxError( - `Missing sandbox command '${sandbox}' (from GEMINI_SANDBOX)`, - ); + // confirm that specified command exists + if (!commandExists.sync(sandbox)) { + throw new FatalSandboxError( + `Missing sandbox command '${sandbox}' (from GEMINI_SANDBOX)`, + ); + } + // runsc uses Docker with --runtime=runsc; both must be available (prioritize runsc when explicitly chosen) + if (sandbox === 'runsc' && !commandExists.sync('docker')) { + throw new FatalSandboxError( + "runsc (gVisor) requires Docker. Install Docker, or use sandbox: 'docker'.", + ); + } + return sandbox; } // look for seatbelt, docker, or podman, in that order // for container-based sandboxing, require sandbox to be enabled explicitly + // note: runsc is NOT auto-detected, it must be explicitly specified if (os.platform() === 'darwin' && commandExists.sync('sandbox-exec')) { return 'sandbox-exec'; } else if (commandExists.sync('docker') && sandbox === true) { @@ -91,6 +106,9 @@ function getSandboxCommand( } return ''; + // Note: 'lxc' is intentionally not auto-detected because it requires a + // pre-existing, running container managed by the user. Use + // GEMINI_SANDBOX=lxc or sandbox: "lxc" in settings to enable it. } export async function loadSandboxConfig( diff --git a/packages/cli/src/config/settings.test.ts b/packages/cli/src/config/settings.test.ts index 8fd0bd81b0..5589ef11ba 100644 --- a/packages/cli/src/config/settings.test.ts +++ b/packages/cli/src/config/settings.test.ts @@ -2162,7 +2162,7 @@ describe('Settings Loading and Merging', () => { } }); - it('should prioritize new settings over deprecated ones and respect removeDeprecated flag', () => { + it('should remove deprecated settings by default and prioritize new ones', () => { const userSettingsContent = { general: { disableAutoUpdate: true, @@ -2177,27 +2177,11 @@ describe('Settings Loading and Merging', () => { }; const loadedSettings = createMockSettings(userSettingsContent); - const setValueSpy = vi.spyOn(loadedSettings, 'setValue'); - // 1. removeDeprecated = false (default) + // Default is now removeDeprecated = true migrateDeprecatedSettings(loadedSettings); - // Should still have old settings - expect( - loadedSettings.forScope(SettingScope.User).settings.general, - ).toHaveProperty('disableAutoUpdate'); - expect( - ( - loadedSettings.forScope(SettingScope.User).settings.context as { - fileFiltering: { disableFuzzySearch: boolean }; - } - ).fileFiltering, - ).toHaveProperty('disableFuzzySearch'); - - // 2. removeDeprecated = true - migrateDeprecatedSettings(loadedSettings, true); - // Should remove disableAutoUpdate and trust enableAutoUpdate: true expect(setValueSpy).toHaveBeenCalledWith(SettingScope.User, 'general', { enableAutoUpdate: true, @@ -2209,6 +2193,37 @@ describe('Settings Loading and Merging', () => { }); }); + it('should preserve deprecated settings when removeDeprecated is explicitly false', () => { + const userSettingsContent = { + general: { + disableAutoUpdate: true, + enableAutoUpdate: true, + }, + context: { + fileFiltering: { + disableFuzzySearch: false, + enableFuzzySearch: false, + }, + }, + }; + + const loadedSettings = createMockSettings(userSettingsContent); + + migrateDeprecatedSettings(loadedSettings, false); + + // Should still have old settings since removeDeprecated = false + expect( + loadedSettings.forScope(SettingScope.User).settings.general, + ).toHaveProperty('disableAutoUpdate'); + expect( + ( + loadedSettings.forScope(SettingScope.User).settings.context as { + fileFiltering: { disableFuzzySearch: boolean }; + } + ).fileFiltering, + ).toHaveProperty('disableFuzzySearch'); + }); + it('should trigger migration automatically during loadSettings', () => { mockFsExistsSync.mockImplementation( (p: fs.PathLike) => p === USER_SETTINGS_PATH, diff --git a/packages/cli/src/config/settings.ts b/packages/cli/src/config/settings.ts index 4e9faf5767..422dda6115 100644 --- a/packages/cli/src/config/settings.ts +++ b/packages/cli/src/config/settings.ts @@ -20,8 +20,8 @@ import { type AdminControlsSettings, } from '@google/gemini-cli-core'; import stripJsonComments from 'strip-json-comments'; -import { DefaultLight } from '../ui/themes/default-light.js'; -import { DefaultDark } from '../ui/themes/default.js'; +import { DefaultLight } from '../ui/themes/builtin/light/default-light.js'; +import { DefaultDark } from '../ui/themes/builtin/dark/default-dark.js'; import { isWorkspaceTrusted } from './trustedFolders.js'; import { type Settings, @@ -796,14 +796,13 @@ export function loadSettings( /** * Migrates deprecated settings to their new counterparts. * - * TODO: After a couple of weeks (around early Feb 2026), we should start removing - * the deprecated settings from the settings files by default. + * Deprecated settings are removed from settings files by default. * * @returns true if any changes were made and need to be saved. */ export function migrateDeprecatedSettings( loadedSettings: LoadedSettings, - removeDeprecated = false, + removeDeprecated = true, ): boolean { let anyModified = false; const systemWarnings: Map = new Map(); diff --git a/packages/cli/src/config/settingsSchema.test.ts b/packages/cli/src/config/settingsSchema.test.ts index 17a916213f..389cabe3cf 100644 --- a/packages/cli/src/config/settingsSchema.test.ts +++ b/packages/cli/src/config/settingsSchema.test.ts @@ -461,7 +461,7 @@ describe('SettingsSchema', () => { expect(gemmaModelRouter.category).toBe('Experimental'); expect(gemmaModelRouter.default).toEqual({}); expect(gemmaModelRouter.requiresRestart).toBe(true); - expect(gemmaModelRouter.showInDialog).toBe(true); + expect(gemmaModelRouter.showInDialog).toBe(false); 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(true); + expect(enabled.showInDialog).toBe(false); expect(enabled.description).toBe( - 'Enable the Gemma Model Router. Requires a local endpoint serving Gemma via the Gemini API using LiteRT-LM shim.', + 'Enable the Gemma Model Router (experimental). Requires a local endpoint serving Gemma via the Gemini API using LiteRT-LM shim.', ); const classifier = gemmaModelRouter.properties.classifier; diff --git a/packages/cli/src/config/settingsSchema.ts b/packages/cli/src/config/settingsSchema.ts index 660866c0e3..4fa17916c4 100644 --- a/packages/cli/src/config/settingsSchema.ts +++ b/packages/cli/src/config/settingsSchema.ts @@ -565,14 +565,34 @@ const SETTINGS_SCHEMA = { description: 'Settings for the footer.', showInDialog: false, properties: { + items: { + type: 'array', + label: 'Footer Items', + category: 'UI', + requiresRestart: false, + default: undefined as string[] | undefined, + description: + 'List of item IDs to display in the footer. Rendered in order', + showInDialog: false, + items: { type: 'string' }, + }, + showLabels: { + type: 'boolean', + label: 'Show Footer Labels', + category: 'UI', + requiresRestart: false, + default: true, + description: + 'Display a second line above the footer items with descriptive headers (e.g., /model).', + showInDialog: false, + }, hideCWD: { type: 'boolean', label: 'Hide CWD', category: 'UI', requiresRestart: false, default: false, - description: - 'Hide the current working directory path in the footer.', + description: 'Hide the current working directory in the footer.', showInDialog: true, }, hideSandboxStatus: { @@ -1149,7 +1169,7 @@ const SETTINGS_SCHEMA = { requiresRestart: false, default: false, description: oneLine` - Controls how /memory refresh loads GEMINI.md files. + Controls how /memory reload loads GEMINI.md files. When true, include directories are scanned; when false, only the current directory is used. `, showInDialog: true, @@ -1236,7 +1256,8 @@ const SETTINGS_SCHEMA = { ref: 'BooleanOrString', description: oneLine` Sandbox execution environment. - Set to a boolean to enable or disable the sandbox, or provide a string path to a sandbox profile. + Set to a boolean to enable or disable the sandbox, provide a string path to a sandbox profile, + or specify an explicit sandbox command (e.g., "docker", "podman", "lxc"). `, showInDialog: false, }, @@ -1806,6 +1827,15 @@ const SETTINGS_SCHEMA = { description: 'Enable planning features (Plan Mode and tools).', showInDialog: true, }, + taskTracker: { + type: 'boolean', + label: 'Task Tracker', + category: 'Experimental', + requiresRestart: true, + default: false, + description: 'Enable task tracker tools.', + showInDialog: false, + }, modelSteering: { type: 'boolean', label: 'Model Steering', @@ -1833,7 +1863,7 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: {}, description: 'Enable Gemma model router (experimental).', - showInDialog: true, + showInDialog: false, properties: { enabled: { type: 'boolean', @@ -1842,8 +1872,8 @@ const SETTINGS_SCHEMA = { requiresRestart: true, default: false, description: - 'Enable the Gemma Model Router. Requires a local endpoint serving Gemma via the Gemini API using LiteRT-LM shim.', - showInDialog: true, + 'Enable the Gemma Model Router (experimental). Requires a local endpoint serving Gemma via the Gemini API using LiteRT-LM shim.', + showInDialog: false, }, classifier: { type: 'object', diff --git a/packages/cli/src/config/trustedFolders.test.ts b/packages/cli/src/config/trustedFolders.test.ts index 714d703241..cfe0447078 100644 --- a/packages/cli/src/config/trustedFolders.test.ts +++ b/packages/cli/src/config/trustedFolders.test.ts @@ -506,7 +506,7 @@ describe('Trusted Folders', () => { const realDir = path.join(tempDir, 'real'); const symlinkDir = path.join(tempDir, 'symlink'); fs.mkdirSync(realDir); - fs.symlinkSync(realDir, symlinkDir); + fs.symlinkSync(realDir, symlinkDir, 'dir'); // Rule uses realpath const config = { [realDir]: TrustLevel.TRUST_FOLDER }; diff --git a/packages/cli/src/core/auth.test.ts b/packages/cli/src/core/auth.test.ts index f28e826f49..5db9cd5449 100644 --- a/packages/cli/src/core/auth.test.ts +++ b/packages/cli/src/core/auth.test.ts @@ -9,6 +9,7 @@ import { performInitialAuth } from './auth.js'; import { type Config, ValidationRequiredError, + ProjectIdRequiredError, AuthType, } from '@google/gemini-cli-core'; @@ -116,4 +117,22 @@ describe('auth', () => { AuthType.LOGIN_WITH_GOOGLE, ); }); + + it('should return ProjectIdRequiredError message without "Failed to login" prefix', async () => { + const projectIdError = new ProjectIdRequiredError(); + vi.mocked(mockConfig.refreshAuth).mockRejectedValue(projectIdError); + const result = await performInitialAuth( + mockConfig, + AuthType.LOGIN_WITH_GOOGLE, + ); + expect(result).toEqual({ + authError: + 'This account requires setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID env var. See https://goo.gle/gemini-cli-auth-docs#workspace-gca', + accountSuspensionInfo: null, + }); + expect(result.authError).not.toContain('Failed to login'); + expect(mockConfig.refreshAuth).toHaveBeenCalledWith( + AuthType.LOGIN_WITH_GOOGLE, + ); + }); }); diff --git a/packages/cli/src/core/auth.ts b/packages/cli/src/core/auth.ts index f49fdecf76..f0b8015013 100644 --- a/packages/cli/src/core/auth.ts +++ b/packages/cli/src/core/auth.ts @@ -10,6 +10,7 @@ import { getErrorMessage, ValidationRequiredError, isAccountSuspendedError, + ProjectIdRequiredError, } from '@google/gemini-cli-core'; import type { AccountSuspensionInfo } from '../ui/contexts/UIStateContext.js'; @@ -54,6 +55,14 @@ export async function performInitialAuth( }, }; } + if (e instanceof ProjectIdRequiredError) { + // OAuth succeeded but account setup requires project ID + // Show the error message directly without "Failed to login" prefix + return { + authError: getErrorMessage(e), + accountSuspensionInfo: null, + }; + } return { authError: `Failed to login. Message: ${getErrorMessage(e)}`, accountSuspensionInfo: null, diff --git a/packages/cli/src/gemini.test.tsx b/packages/cli/src/gemini.test.tsx index 2784c5694a..90c63651e7 100644 --- a/packages/cli/src/gemini.test.tsx +++ b/packages/cli/src/gemini.test.tsx @@ -747,6 +747,60 @@ 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, + ); + + 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' @@ -959,13 +1013,18 @@ describe('gemini.tsx main function exit codes', () => { resume: 'invalid-session', } as unknown as CliArgs); - vi.mock('./utils/sessionUtils.js', () => ({ - SessionSelector: vi.fn().mockImplementation(() => ({ - resolveSession: vi - .fn() - .mockRejectedValue(new Error('Session not found')), - })), - })); + vi.mock('./utils/sessionUtils.js', async (importOriginal) => { + const original = + await importOriginal(); + return { + ...original, + SessionSelector: vi.fn().mockImplementation(() => ({ + resolveSession: vi + .fn() + .mockRejectedValue(new Error('Session not found')), + })), + }; + }); process.env['GEMINI_API_KEY'] = 'test-key'; try { diff --git a/packages/cli/src/gemini.tsx b/packages/cli/src/gemini.tsx index 88f9f404cd..331ec0c018 100644 --- a/packages/cli/src/gemini.tsx +++ b/packages/cli/src/gemini.tsx @@ -79,12 +79,12 @@ import { type InitializationResult, } from './core/initializer.js'; import { validateAuthMethod } from './config/auth.js'; -import { runZedIntegration } from './zed-integration/zedIntegration.js'; +import { runAcpClient } from './acp/acpClient.js'; 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 { SessionSelector } from './utils/sessionUtils.js'; +import { SessionError, 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'; @@ -672,8 +672,8 @@ export async function main() { await getOauthClient(settings.merged.security.auth.selectedType, config); } - if (config.getExperimentalZedIntegration()) { - return runZedIntegration(config, settings, argv); + if (config.getAcpMode()) { + return runAcpClient(config, settings, argv); } let input = config.getQuestion(); @@ -706,12 +706,24 @@ export async function main() { // Use the existing session ID to continue recording to the same session config.setSessionId(resumedSessionData.conversation.sessionId); } catch (error) { - coreEvents.emitFeedback( - 'error', - `Error resuming session: ${error instanceof Error ? error.message : 'Unknown error'}`, - ); - await runExitCleanup(); - process.exit(ExitCodes.FATAL_INPUT_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); + } } } diff --git a/packages/cli/src/gemini_cleanup.test.tsx b/packages/cli/src/gemini_cleanup.test.tsx index fb37bb94ec..536da027d4 100644 --- a/packages/cli/src/gemini_cleanup.test.tsx +++ b/packages/cli/src/gemini_cleanup.test.tsx @@ -179,7 +179,7 @@ describe('gemini.tsx main function cleanup', () => { vi.restoreAllMocks(); }); - it('should log error when cleanupExpiredSessions fails', async () => { + it.skip('should log error when cleanupExpiredSessions fails', async () => { const { loadCliConfig, parseArguments } = await import( './config/config.js' ); @@ -216,7 +216,7 @@ describe('gemini.tsx main function cleanup', () => { getMcpServers: () => ({}), getMcpClientManager: vi.fn(), getIdeMode: vi.fn(() => false), - getExperimentalZedIntegration: vi.fn(() => true), + getAcpMode: vi.fn(() => true), getScreenReader: vi.fn(() => false), getGeminiMdFileCount: vi.fn(() => 0), getProjectRoot: vi.fn(() => '/'), diff --git a/packages/cli/src/integration-tests/modelSteering.test.tsx b/packages/cli/src/integration-tests/modelSteering.test.tsx index ca1970cebc..27bcde0dc2 100644 --- a/packages/cli/src/integration-tests/modelSteering.test.tsx +++ b/packages/cli/src/integration-tests/modelSteering.test.tsx @@ -65,10 +65,6 @@ describe('Model Steering Integration', () => { // Resolve list_directory (Proceed) await rig.resolveTool('ReadFolder'); - // Wait for the model to process the hint and output the next action - // Based on steering.responses, it should first acknowledge the hint - await rig.waitForOutput('ACK: I will focus on .txt files now.'); - // Then it should proceed with the next action await rig.waitForOutput( /Since you want me to focus on .txt files,[\s\S]*I will read file1.txt/, diff --git a/packages/cli/src/services/BuiltinCommandLoader.test.ts b/packages/cli/src/services/BuiltinCommandLoader.test.ts index 1246ee0532..7b7832bfbe 100644 --- a/packages/cli/src/services/BuiltinCommandLoader.test.ts +++ b/packages/cli/src/services/BuiltinCommandLoader.test.ts @@ -73,7 +73,17 @@ vi.mock('../ui/commands/agentsCommand.js', () => ({ })); vi.mock('../ui/commands/bugCommand.js', () => ({ bugCommand: {} })); vi.mock('../ui/commands/chatCommand.js', () => ({ - chatCommand: { name: 'chat', subCommands: [] }, + chatCommand: { + name: 'chat', + subCommands: [ + { name: 'list' }, + { name: 'save' }, + { name: 'resume' }, + { name: 'delete' }, + { name: 'share' }, + { name: 'checkpoints', hidden: true, subCommands: [{ name: 'list' }] }, + ], + }, debugCommand: { name: 'debug' }, })); vi.mock('../ui/commands/clearCommand.js', () => ({ clearCommand: {} })); @@ -94,7 +104,19 @@ vi.mock('../ui/commands/modelCommand.js', () => ({ })); vi.mock('../ui/commands/privacyCommand.js', () => ({ privacyCommand: {} })); vi.mock('../ui/commands/quitCommand.js', () => ({ quitCommand: {} })); -vi.mock('../ui/commands/resumeCommand.js', () => ({ resumeCommand: {} })); +vi.mock('../ui/commands/resumeCommand.js', () => ({ + resumeCommand: { + name: 'resume', + subCommands: [ + { name: 'list' }, + { name: 'save' }, + { name: 'resume' }, + { name: 'delete' }, + { name: 'share' }, + { name: 'checkpoints', hidden: true, subCommands: [{ name: 'list' }] }, + ], + }, +})); vi.mock('../ui/commands/statsCommand.js', () => ({ statsCommand: {} })); vi.mock('../ui/commands/themeCommand.js', () => ({ themeCommand: {} })); vi.mock('../ui/commands/toolsCommand.js', () => ({ toolsCommand: {} })); @@ -256,7 +278,7 @@ describe('BuiltinCommandLoader', () => { }); describe('chat debug command', () => { - it('should NOT add debug subcommand to chatCommand if not a nightly build', async () => { + it('should NOT add debug subcommand to chat/resume commands if not a nightly build', async () => { vi.mocked(isNightly).mockResolvedValue(false); const loader = new BuiltinCommandLoader(mockConfig); const commands = await loader.loadCommands(new AbortController().signal); @@ -265,9 +287,30 @@ describe('BuiltinCommandLoader', () => { expect(chatCmd?.subCommands).toBeDefined(); const hasDebug = chatCmd!.subCommands!.some((c) => c.name === 'debug'); expect(hasDebug).toBe(false); + + const resumeCmd = commands.find((c) => c.name === 'resume'); + const resumeHasDebug = + resumeCmd?.subCommands?.some((c) => c.name === 'debug') ?? false; + expect(resumeHasDebug).toBe(false); + + const chatCheckpointsCmd = chatCmd?.subCommands?.find( + (c) => c.name === 'checkpoints', + ); + const chatCheckpointHasDebug = + chatCheckpointsCmd?.subCommands?.some((c) => c.name === 'debug') ?? + false; + expect(chatCheckpointHasDebug).toBe(false); + + const resumeCheckpointsCmd = resumeCmd?.subCommands?.find( + (c) => c.name === 'checkpoints', + ); + const resumeCheckpointHasDebug = + resumeCheckpointsCmd?.subCommands?.some((c) => c.name === 'debug') ?? + false; + expect(resumeCheckpointHasDebug).toBe(false); }); - it('should add debug subcommand to chatCommand if it is a nightly build', async () => { + it('should add debug subcommand to chat/resume commands if it is a nightly build', async () => { vi.mocked(isNightly).mockResolvedValue(true); const loader = new BuiltinCommandLoader(mockConfig); const commands = await loader.loadCommands(new AbortController().signal); @@ -276,6 +319,27 @@ describe('BuiltinCommandLoader', () => { expect(chatCmd?.subCommands).toBeDefined(); const hasDebug = chatCmd!.subCommands!.some((c) => c.name === 'debug'); expect(hasDebug).toBe(true); + + const resumeCmd = commands.find((c) => c.name === 'resume'); + const resumeHasDebug = + resumeCmd?.subCommands?.some((c) => c.name === 'debug') ?? false; + expect(resumeHasDebug).toBe(true); + + const chatCheckpointsCmd = chatCmd?.subCommands?.find( + (c) => c.name === 'checkpoints', + ); + const chatCheckpointHasDebug = + chatCheckpointsCmd?.subCommands?.some((c) => c.name === 'debug') ?? + false; + expect(chatCheckpointHasDebug).toBe(true); + + const resumeCheckpointsCmd = resumeCmd?.subCommands?.find( + (c) => c.name === 'checkpoints', + ); + const resumeCheckpointHasDebug = + resumeCheckpointsCmd?.subCommands?.some((c) => c.name === 'debug') ?? + false; + expect(resumeCheckpointHasDebug).toBe(true); }); }); }); diff --git a/packages/cli/src/services/BuiltinCommandLoader.ts b/packages/cli/src/services/BuiltinCommandLoader.ts index 31673e921a..8ee5effc59 100644 --- a/packages/cli/src/services/BuiltinCommandLoader.ts +++ b/packages/cli/src/services/BuiltinCommandLoader.ts @@ -31,6 +31,7 @@ import { docsCommand } from '../ui/commands/docsCommand.js'; import { directoryCommand } from '../ui/commands/directoryCommand.js'; import { editorCommand } from '../ui/commands/editorCommand.js'; import { extensionsCommand } from '../ui/commands/extensionsCommand.js'; +import { footerCommand } from '../ui/commands/footerCommand.js'; import { helpCommand } from '../ui/commands/helpCommand.js'; import { shortcutsCommand } from '../ui/commands/shortcutsCommand.js'; import { rewindCommand } from '../ui/commands/rewindCommand.js'; @@ -77,6 +78,41 @@ export class BuiltinCommandLoader implements ICommandLoader { const handle = startupProfiler.start('load_builtin_commands'); const isNightlyBuild = await isNightly(process.cwd()); + const addDebugToChatResumeSubCommands = ( + subCommands: SlashCommand[] | undefined, + ): SlashCommand[] | undefined => { + if (!subCommands) { + return subCommands; + } + + const withNestedCompatibility = subCommands.map((subCommand) => { + if (subCommand.name !== 'checkpoints') { + return subCommand; + } + + return { + ...subCommand, + subCommands: addDebugToChatResumeSubCommands(subCommand.subCommands), + }; + }); + + if (!isNightlyBuild) { + return withNestedCompatibility; + } + + return withNestedCompatibility.some( + (cmd) => cmd.name === debugCommand.name, + ) + ? withNestedCompatibility + : [ + ...withNestedCompatibility, + { ...debugCommand, suggestionGroup: 'checkpoints' }, + ]; + }; + + const chatResumeSubCommands = addDebugToChatResumeSubCommands( + chatCommand.subCommands, + ); const allDefinitions: Array = [ aboutCommand, @@ -85,9 +121,7 @@ export class BuiltinCommandLoader implements ICommandLoader { bugCommand, { ...chatCommand, - subCommands: isNightlyBuild - ? [...(chatCommand.subCommands || []), debugCommand] - : chatCommand.subCommands, + subCommands: chatResumeSubCommands, }, clearCommand, commandsCommand, @@ -119,6 +153,7 @@ export class BuiltinCommandLoader implements ICommandLoader { ] : [extensionsCommand(this.config?.getEnableExtensionReloading())]), helpCommand, + footerCommand, shortcutsCommand, ...(this.config?.getEnableHooksUI() ? [hooksCommand] : []), rewindCommand, @@ -153,7 +188,10 @@ export class BuiltinCommandLoader implements ICommandLoader { ...(isDevelopment ? [profileCommand] : []), quitCommand, restoreCommand(this.config), - resumeCommand, + { + ...resumeCommand, + subCommands: addDebugToChatResumeSubCommands(resumeCommand.subCommands), + }, statsCommand, themeCommand, toolsCommand, diff --git a/packages/cli/src/services/CommandService.test.ts b/packages/cli/src/services/CommandService.test.ts index ea906a3da6..eae7ec7c40 100644 --- a/packages/cli/src/services/CommandService.test.ts +++ b/packages/cli/src/services/CommandService.test.ts @@ -17,21 +17,9 @@ 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 { - private commandsToLoad: SlashCommand[]; - - constructor(commandsToLoad: SlashCommand[]) { - this.commandsToLoad = commandsToLoad; - } - - loadCommands = vi.fn( - async (): Promise => Promise.resolve(this.commandsToLoad), - ); + constructor(private readonly commands: SlashCommand[]) {} + loadCommands = vi.fn(async () => Promise.resolve(this.commands)); } describe('CommandService', () => { @@ -43,424 +31,74 @@ describe('CommandService', () => { vi.restoreAllMocks(); }); - it('should load commands from a single loader', async () => { - const mockLoader = new MockCommandLoader([mockCommandA, mockCommandB]); - const service = await CommandService.create( - [mockLoader], - new AbortController().signal, - ); + 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, + ); - const commands = service.getCommands(); + expect(service.getCommands()).toHaveLength(2); + expect(service.getCommands()).toEqual( + expect.arrayContaining([cmdA, cmdB]), + ); + }); - expect(mockLoader.loadCommands).toHaveBeenCalledTimes(1); - expect(commands).toHaveLength(2); - expect(commands).toEqual( - expect.arrayContaining([mockCommandA, mockCommandB]), - ); - }); + 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'), + ); - 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, - ); + const service = await CommandService.create( + [ + new MockCommandLoader([cmdA]), + new MockCommandLoader([]), + failingLoader, + ], + new AbortController().signal, + ); - const commands = service.getCommands(); + expect(service.getCommands()).toHaveLength(1); + expect(service.getCommands()[0].name).toBe('a'); + expect(debugLogger.debug).toHaveBeenCalledWith( + 'A command loader failed:', + expect.any(Error), + ); + }); - expect(loader1.loadCommands).toHaveBeenCalledTimes(1); - expect(loader2.loadCommands).toHaveBeenCalledTimes(1); - expect(commands).toHaveLength(2); - expect(commands).toEqual( - expect.arrayContaining([mockCommandA, mockCommandC]), - ); - }); + 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(); + }); - 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', - }), - }, - ], + 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 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', - }; + 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); - const mockLoader = new MockCommandLoader([ - extension1Command, - extension2Command, - ]); + const service = await CommandService.create( + [new MockCommandLoader([builtin, user])], + new AbortController().signal, + ); - 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', - }), - }, - ], + expect(service.getCommands().map((c) => c.name)).toContain('help'); + expect(service.getCommands().map((c) => c.name)).toContain('user.help'); + expect(service.getConflicts()).toHaveLength(1); }); }); - - 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' }), - }), - ]), - ); - }); }); diff --git a/packages/cli/src/services/CommandService.ts b/packages/cli/src/services/CommandService.ts index bd42226a32..61f9457619 100644 --- a/packages/cli/src/services/CommandService.ts +++ b/packages/cli/src/services/CommandService.ts @@ -6,16 +6,8 @@ import { debugLogger, coreEvents } from '@google/gemini-cli-core'; import type { SlashCommand } from '../ui/commands/types.js'; -import type { ICommandLoader } from './types.js'; - -export interface CommandConflict { - name: string; - winner: SlashCommand; - losers: Array<{ - command: SlashCommand; - renamedTo: string; - }>; -} +import type { ICommandLoader, CommandConflict } from './types.js'; +import { SlashCommandResolver } from './SlashCommandResolver.js'; /** * Orchestrates the discovery and loading of all slash commands for the CLI. @@ -24,9 +16,9 @@ export interface CommandConflict { * with an array of `ICommandLoader` instances, each responsible for fetching * commands from a specific source (e.g., built-in code, local files). * - * 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. + * 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. */ export class CommandService { /** @@ -42,96 +34,71 @@ export class CommandService { /** * Asynchronously creates and initializes a new CommandService instance. * - * 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. + * This factory method orchestrates the loading process and delegates + * conflict resolution to the SlashCommandResolver. * - * 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. + * @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. */ static async create( loaders: ICommandLoader[], signal: AbortSignal, ): Promise { + 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 { const results = await Promise.allSettled( loaders.map((loader) => loader.loadCommands(signal)), ); - const allCommands: SlashCommand[] = []; + const commands: SlashCommand[] = []; for (const result of results) { if (result.status === 'fulfilled') { - allCommands.push(...result.value); + commands.push(...result.value); } else { debugLogger.debug('A command loader failed:', result.reason); } } + return commands; + } - const commandMap = new Map(); - const conflictsMap = new Map(); - - 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); + /** + * 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, + })), + ), + ); } /** diff --git a/packages/cli/src/services/FileCommandLoader.ts b/packages/cli/src/services/FileCommandLoader.ts index fb27327ead..229ff0b3bc 100644 --- a/packages/cli/src/services/FileCommandLoader.ts +++ b/packages/cli/src/services/FileCommandLoader.ts @@ -37,6 +37,7 @@ import { sanitizeForDisplay } from '../ui/utils/textUtils.js'; interface CommandDirectory { path: string; + kind: CommandKind; extensionName?: string; extensionId?: string; } @@ -111,6 +112,7 @@ export class FileCommandLoader implements ICommandLoader { this.parseAndAdaptFile( path.join(dirInfo.path, file), dirInfo.path, + dirInfo.kind, dirInfo.extensionName, dirInfo.extensionId, ), @@ -151,10 +153,16 @@ export class FileCommandLoader implements ICommandLoader { const storage = this.config?.storage ?? new Storage(this.projectRoot); // 1. User commands - dirs.push({ path: Storage.getUserCommandsDir() }); + dirs.push({ + path: Storage.getUserCommandsDir(), + kind: CommandKind.USER_FILE, + }); - // 2. Project commands (override user commands) - dirs.push({ path: storage.getProjectCommandsDir() }); + // 2. Project commands + dirs.push({ + path: storage.getProjectCommandsDir(), + kind: CommandKind.WORKSPACE_FILE, + }); // 3. Extension commands (processed last to detect all conflicts) if (this.config) { @@ -165,6 +173,7 @@ 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, })); @@ -179,12 +188,14 @@ 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 { @@ -286,7 +297,7 @@ export class FileCommandLoader implements ICommandLoader { return { name: baseCommandName, description, - kind: CommandKind.FILE, + kind, extensionName, extensionId, action: async ( diff --git a/packages/cli/src/services/McpPromptLoader.ts b/packages/cli/src/services/McpPromptLoader.ts index f61eed9184..9afeffcdc2 100644 --- a/packages/cli/src/services/McpPromptLoader.ts +++ b/packages/cli/src/services/McpPromptLoader.ts @@ -44,6 +44,7 @@ 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: [ { diff --git a/packages/cli/src/services/SlashCommandConflictHandler.test.ts b/packages/cli/src/services/SlashCommandConflictHandler.test.ts new file mode 100644 index 0000000000..a828923fe5 --- /dev/null +++ b/packages/cli/src/services/SlashCommandConflictHandler.test.ts @@ -0,0 +1,175 @@ +/** + * @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(); + 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(); + }); +}); diff --git a/packages/cli/src/services/SlashCommandConflictHandler.ts b/packages/cli/src/services/SlashCommandConflictHandler.ts index 31e110732b..b51617840e 100644 --- a/packages/cli/src/services/SlashCommandConflictHandler.ts +++ b/packages/cli/src/services/SlashCommandConflictHandler.ts @@ -8,10 +8,20 @@ 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(); + private pendingConflicts: SlashCommandConflict[] = []; + private flushTimeout: ReturnType | null = null; constructor() { this.handleConflicts = this.handleConflicts.bind(this); @@ -23,11 +33,18 @@ 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) => { - const key = `${c.name}:${c.loserExtensionName}`; + // 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}`; if (this.notifiedConflicts.has(key)) { return false; } @@ -36,19 +53,119 @@ export class SlashCommandConflictHandler { }); if (newConflicts.length > 0) { - 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'); + this.pendingConflicts.push(...newConflicts); + this.scheduleFlush(); + } + } - coreEvents.emitFeedback( - 'info', - `Command conflicts detected:\n${conflictMessages}`, - ); + 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(); + 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'; } } } diff --git a/packages/cli/src/services/SlashCommandResolver.test.ts b/packages/cli/src/services/SlashCommandResolver.test.ts new file mode 100644 index 0000000000..e703028b3d --- /dev/null +++ b/packages/cli/src/services/SlashCommandResolver.test.ts @@ -0,0 +1,177 @@ +/** + * @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(); + }); + }); +}); diff --git a/packages/cli/src/services/SlashCommandResolver.ts b/packages/cli/src/services/SlashCommandResolver.ts new file mode 100644 index 0000000000..aad4d98fe4 --- /dev/null +++ b/packages/cli/src/services/SlashCommandResolver.ts @@ -0,0 +1,213 @@ +/** + * @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(); + readonly conflictsMap = new Map(); + readonly firstEncounters = new Map(); + + 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 { + 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, + 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, + }); + } +} diff --git a/packages/cli/src/services/types.ts b/packages/cli/src/services/types.ts index 13a87687ee..b583e56e39 100644 --- a/packages/cli/src/services/types.ts +++ b/packages/cli/src/services/types.ts @@ -22,3 +22,12 @@ export interface ICommandLoader { */ loadCommands(signal: AbortSignal): Promise; } + +export interface CommandConflict { + name: string; + losers: Array<{ + command: SlashCommand; + renamedTo: string; + reason: SlashCommand; + }>; +} diff --git a/packages/cli/src/test-utils/fixtures/steering.responses b/packages/cli/src/test-utils/fixtures/steering.responses index 66407f819e..6d843010f1 100644 --- a/packages/cli/src/test-utils/fixtures/steering.responses +++ b/packages/cli/src/test-utils/fixtures/steering.responses @@ -1,4 +1,3 @@ {"method":"generateContentStream","response":[{"candidates":[{"content":{"role":"model","parts":[{"text":"Starting a long task. First, I'll list the files."},{"functionCall":{"name":"list_directory","args":{"dir_path":"."}}}]},"finishReason":"STOP"}]}]} -{"method":"generateContent","response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ACK: I will focus on .txt files now."}]},"finishReason":"STOP"}]}} {"method":"generateContentStream","response":[{"candidates":[{"content":{"role":"model","parts":[{"text":"I see the files. Since you want me to focus on .txt files, I will read file1.txt."},{"functionCall":{"name":"read_file","args":{"file_path":"file1.txt"}}}]},"finishReason":"STOP"}]}]} {"method":"generateContentStream","response":[{"candidates":[{"content":{"role":"model","parts":[{"text":"I have read file1.txt. Task complete."}]},"finishReason":"STOP"}]}]} diff --git a/packages/cli/src/test-utils/mockConfig.ts b/packages/cli/src/test-utils/mockConfig.ts index 8b7c7c520d..c8ab45a35d 100644 --- a/packages/cli/src/test-utils/mockConfig.ts +++ b/packages/cli/src/test-utils/mockConfig.ts @@ -42,7 +42,7 @@ export const createMockConfig = (overrides: Partial = {}): Config => setSessionId: vi.fn(), getSessionId: vi.fn().mockReturnValue('mock-session-id'), getContentGeneratorConfig: vi.fn(() => ({ authType: 'google' })), - getExperimentalZedIntegration: vi.fn(() => false), + getAcpMode: vi.fn(() => false), isBrowserLaunchSuppressed: vi.fn(() => false), setRemoteAdminSettings: vi.fn(), isYoloModeDisabled: vi.fn(() => false), diff --git a/packages/cli/src/test-utils/mockDebugLogger.ts b/packages/cli/src/test-utils/mockDebugLogger.ts index 02eb3b05d9..bc0cde9010 100644 --- a/packages/cli/src/test-utils/mockDebugLogger.ts +++ b/packages/cli/src/test-utils/mockDebugLogger.ts @@ -65,6 +65,7 @@ export function mockCoreDebugLogger>( return { ...actual, coreEvents: { + // eslint-disable-next-line no-restricted-syntax ...(typeof actual['coreEvents'] === 'object' && actual['coreEvents'] !== null ? actual['coreEvents'] diff --git a/packages/cli/src/test-utils/render.tsx b/packages/cli/src/test-utils/render.tsx index 86c46e79e5..39425af171 100644 --- a/packages/cli/src/test-utils/render.tsx +++ b/packages/cli/src/test-utils/render.tsx @@ -17,6 +17,7 @@ import { vi } from 'vitest'; import stripAnsi from 'strip-ansi'; import { act, useState } from 'react'; import os from 'node:os'; +import path from 'node:path'; import { LoadedSettings } from '../config/settings.js'; import { KeypressProvider } from '../ui/contexts/KeypressContext.js'; import { SettingsContext } from '../ui/contexts/SettingsContext.js'; @@ -49,7 +50,7 @@ import { AppContext, type AppState } from '../ui/contexts/AppContext.js'; import { createMockSettings } from './settings.js'; import { SessionStatsProvider } from '../ui/contexts/SessionContext.js'; import { themeManager, DEFAULT_THEME } from '../ui/themes/theme-manager.js'; -import { DefaultLight } from '../ui/themes/default-light.js'; +import { DefaultLight } from '../ui/themes/builtin/light/default-light.js'; import { pickDefaultThemeName } from '../ui/themes/theme.js'; import { generateSvgForTerminal } from './svg.js'; @@ -95,6 +96,7 @@ function isInkRenderMetrics( typeof m === 'object' && m !== null && 'output' in m && + // eslint-disable-next-line no-restricted-syntax typeof m['output'] === 'string' ); } @@ -502,7 +504,22 @@ const configProxy = new Proxy({} as Config, { get(_target, prop) { if (prop === 'getTargetDir') { return () => - '/Users/test/project/foo/bar/and/some/more/directories/to/make/it/long'; + path.join( + path.parse(process.cwd()).root, + 'Users', + 'test', + 'project', + 'foo', + 'bar', + 'and', + 'some', + 'more', + 'directories', + 'to', + 'make', + 'it', + 'long', + ); } if (prop === 'getUseBackgroundColor') { return () => true; diff --git a/packages/cli/src/test-utils/svg.ts b/packages/cli/src/test-utils/svg.ts index 10528ca6b7..92d3f53c2f 100644 --- a/packages/cli/src/test-utils/svg.ts +++ b/packages/cli/src/test-utils/svg.ts @@ -89,6 +89,7 @@ export const generateSvgForTerminal = (terminal: Terminal): string => { break; } } + if (contentRows === 0) contentRows = 1; // Minimum 1 row const width = terminal.cols * charWidth + padding * 2; @@ -113,6 +114,9 @@ export const generateSvgForTerminal = (terminal: Terminal): string => { let currentFgHex: string | null = null; let currentBgHex: string | null = null; + let currentIsBold = false; + let currentIsItalic = false; + let currentIsUnderline = false; let currentBlockStartCol = -1; let currentBlockText = ''; let currentBlockNumCells = 0; @@ -128,12 +132,20 @@ export const generateSvgForTerminal = (terminal: Terminal): string => { svg += ` `; } - if (currentBlockText.trim().length > 0) { + if (currentBlockText.trim().length > 0 || currentIsUnderline) { const fill = currentFgHex || '#ffffff'; // Default text color const textWidth = currentBlockNumCells * charWidth; + + let extraAttrs = ''; + if (currentIsBold) extraAttrs += ' font-weight="bold"'; + if (currentIsItalic) extraAttrs += ' font-style="italic"'; + if (currentIsUnderline) + extraAttrs += ' text-decoration="underline"'; + // Use textLength to ensure the block fits exactly into its designated cells - svg += ` ${escapeXml(currentBlockText)} -`; + const textElement = `${escapeXml(currentBlockText)}`; + + svg += ` ${textElement}\n`; } } } @@ -164,17 +176,27 @@ export const generateSvgForTerminal = (terminal: Terminal): string => { bgHex = tempFgHex || '#ffffff'; } + const isBold = !!cell.isBold(); + const isItalic = !!cell.isItalic(); + const isUnderline = !!cell.isUnderline(); + let chars = cell.getChars(); if (chars === '') chars = ' '.repeat(cellWidth); if ( fgHex !== currentFgHex || bgHex !== currentBgHex || + isBold !== currentIsBold || + isItalic !== currentIsItalic || + isUnderline !== currentIsUnderline || currentBlockStartCol === -1 ) { finalizeBlock(x); currentFgHex = fgHex; currentBgHex = bgHex; + currentIsBold = isBold; + currentIsItalic = isItalic; + currentIsUnderline = isUnderline; currentBlockStartCol = x; currentBlockText = chars; currentBlockNumCells = cellWidth; @@ -185,6 +207,7 @@ export const generateSvgForTerminal = (terminal: Terminal): string => { } finalizeBlock(line.length); } + svg += ` \n`; return svg; }; diff --git a/packages/cli/src/ui/AppContainer.test.tsx b/packages/cli/src/ui/AppContainer.test.tsx index 8505afd3ef..0b6eaa037b 100644 --- a/packages/cli/src/ui/AppContainer.test.tsx +++ b/packages/cli/src/ui/AppContainer.test.tsx @@ -160,6 +160,7 @@ 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'); @@ -218,6 +219,10 @@ 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'; @@ -227,10 +232,7 @@ 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, @@ -299,6 +301,8 @@ 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; @@ -451,6 +455,15 @@ 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(); @@ -2181,35 +2194,6 @@ 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; @@ -2544,136 +2528,6 @@ describe('AppContainer State Management', () => { }); }); - describe('Expansion Persistence', () => { - let rerender: () => void; - let unmount: () => void; - let stdin: ReturnType['stdin']; - - const setupExpansionPersistenceTest = async ( - HighPriorityChild?: React.FC, - ) => { - const getTree = () => ( - - - - - {HighPriorityChild && } - - - - ); - - const renderResult = render(getTree()); - stdin = renderResult.stdin; - await act(async () => { - vi.advanceTimersByTime(100); - }); - rerender = () => renderResult.rerender(getTree()); - unmount = () => renderResult.unmount(); - }; - - const writeStdin = async (sequence: string) => { - await act(async () => { - stdin.write(sequence); - // Advance timers to allow escape sequence parsing and broadcasting - vi.advanceTimersByTime(100); - }); - rerender(); - }; - - beforeEach(() => { - vi.useFakeTimers(); - }); - - afterEach(() => { - vi.useRealTimers(); - vi.restoreAllMocks(); - }); - - it('should reset expansion when a key is NOT handled by anyone', async () => { - await setupExpansionPersistenceTest(); - - // Expand first - act(() => capturedUIActions.setConstrainHeight(false)); - rerender(); - expect(capturedUIState.constrainHeight).toBe(false); - - // Press a random key that no one handles (hits Low priority fallback) - await writeStdin('x'); - - // Should be reset to true (collapsed) - expect(capturedUIState.constrainHeight).toBe(true); - - unmount(); - }); - - it('should toggle expansion when Ctrl+O is pressed', async () => { - await setupExpansionPersistenceTest(); - - // Initial state is collapsed - expect(capturedUIState.constrainHeight).toBe(true); - - // Press Ctrl+O to expand (Ctrl+O is sequence \x0f) - await writeStdin('\x0f'); - expect(capturedUIState.constrainHeight).toBe(false); - - // Press Ctrl+O again to collapse - await writeStdin('\x0f'); - expect(capturedUIState.constrainHeight).toBe(true); - - unmount(); - }); - - it('should NOT collapse when a high-priority component handles the key (e.g., up/down arrows)', async () => { - const NavigationHandler = () => { - // use real useKeypress - useKeypress( - (key: Key) => { - if (key.name === 'up' || key.name === 'down') { - return true; // Handle navigation - } - return false; - }, - { isActive: true, priority: true }, // High priority - ); - return null; - }; - - await setupExpansionPersistenceTest(NavigationHandler); - - // Expand first - act(() => capturedUIActions.setConstrainHeight(false)); - rerender(); - expect(capturedUIState.constrainHeight).toBe(false); - - // 1. Simulate Up arrow (handled by high priority child) - // CSI A is Up arrow - await writeStdin('\u001b[A'); - - // Should STILL be expanded - expect(capturedUIState.constrainHeight).toBe(false); - - // 2. Simulate Down arrow (handled by high priority child) - // CSI B is Down arrow - await writeStdin('\u001b[B'); - - // Should STILL be expanded - expect(capturedUIState.constrainHeight).toBe(false); - - // 3. Sanity check: press an unhandled key - await writeStdin('x'); - - // Should finally collapse - expect(capturedUIState.constrainHeight).toBe(true); - - unmount(); - }); - }); - describe('Shortcuts Help Visibility', () => { let handleGlobalKeypress: (key: Key) => boolean; let mockedUseKeypress: Mock; @@ -3255,30 +3109,6 @@ 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(); @@ -3579,6 +3409,63 @@ 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['stdin']; @@ -3720,7 +3607,7 @@ describe('AppContainer State Management', () => { unmount!(); }); - it('does NOT set showIsExpandableHint when overflow occurs in Alternate Buffer Mode', async () => { + it('DOES set showIsExpandableHint when overflow occurs in Alternate Buffer Mode', async () => { const alternateSettings = mergeSettings({}, {}, {}, {}, true); const settingsWithAlternateBuffer = { merged: { @@ -3748,8 +3635,10 @@ describe('AppContainer State Management', () => { capturedOverflowActions.addOverflowingId('test-id'); }); - // Should NOT show hint because we are in Alternate Buffer Mode - expect(capturedUIState.showIsExpandableHint).toBe(false); + // Should NOW show hint because we are in Alternate Buffer Mode + await waitFor(() => { + expect(capturedUIState.showIsExpandableHint).toBe(true); + }); unmount!(); }); diff --git a/packages/cli/src/ui/AppContainer.tsx b/packages/cli/src/ui/AppContainer.tsx index 4f8d739340..67f2d5dd84 100644 --- a/packages/cli/src/ui/AppContainer.tsx +++ b/packages/cli/src/ui/AppContainer.tsx @@ -80,8 +80,8 @@ import { type ConsentRequestPayload, type AgentsDiscoveredPayload, ChangeAuthRequestedError, + ProjectIdRequiredError, CoreToolCallStatus, - generateSteeringAckMessage, buildUserSteeringHintPrompt, logBillingEvent, ApiKeyUpdatedEvent, @@ -129,7 +129,7 @@ import { appEvents, AppEvent, TransientMessageType } from '../utils/events.js'; import { type UpdateObject } from './utils/updateCheck.js'; import { setUpdateHandler } from '../utils/handleAutoUpdate.js'; import { registerCleanup, runExitCleanup } from '../utils/cleanup.js'; -import { RELAUNCH_EXIT_CODE } from '../utils/processUtils.js'; +import { relaunchApp } from '../utils/processUtils.js'; import type { SessionInfo } from '../utils/sessionUtils.js'; import { useMessageQueue } from './hooks/useMessageQueue.js'; import { useMcpStatus } from './hooks/useMcpStatus.js'; @@ -283,19 +283,18 @@ 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. 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. + * 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. * * 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 && !isAlternateBuffer) { + if (hasOverflowState) { triggerExpandHint(true); } - }, [hasOverflowState, isAlternateBuffer, triggerExpandHint]); + }, [hasOverflowState, overflowingIdsSize, triggerExpandHint]); const [defaultBannerText, setDefaultBannerText] = useState(''); const [warningBannerText, setWarningBannerText] = useState(''); @@ -771,6 +770,12 @@ export const AppContainer = (props: AppContainerProps) => { if (e instanceof ChangeAuthRequestedError) { return; } + if (e instanceof ProjectIdRequiredError) { + // OAuth succeeded but account setup requires project ID + // Show the error message directly without "Failed to authenticate" prefix + onAuthError(getErrorMessage(e)); + return; + } onAuthError( `Failed to authenticate: ${e instanceof Error ? e.message : String(e)}`, ); @@ -781,13 +786,12 @@ export const AppContainer = (props: AppContainerProps) => { authType === AuthType.LOGIN_WITH_GOOGLE && config.isBrowserLaunchSuppressed() ) { - await runExitCleanup(); writeToStdout(` ---------------------------------------------------------------- Logging in with Google... Restarting Gemini CLI to continue. ---------------------------------------------------------------- `); - process.exit(RELAUNCH_EXIT_CODE); + await relaunchApp(); } } setAuthState(AuthState.Authenticated); @@ -1005,10 +1009,10 @@ Logging in with Google... Restarting Gemini CLI to continue. historyManager.addItem( { type: MessageType.INFO, - text: `Memory refreshed successfully. ${ + text: `Memory reloaded 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(), @@ -1416,32 +1420,6 @@ 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 && @@ -1873,10 +1851,7 @@ Logging in with Google... Restarting Gemini CLI to continue. ], ); - useKeypress(handleGlobalKeypress, { - isActive: true, - priority: KeypressPriority.Low, - }); + useKeypress(handleGlobalKeypress, { isActive: true, priority: true }); useKeypress( () => { @@ -2106,15 +2081,6 @@ Logging in with Google... Restarting Gemini CLI to continue. return; } - void generateSteeringAckMessage( - config.getBaseLlmClient(), - pendingHint, - ).then((ackText) => { - historyManager.addItem({ - type: 'info', - text: ackText, - }); - }); void submitQuery([{ text: buildUserSteeringHintPrompt(pendingHint) }]); }, [ config, @@ -2500,8 +2466,7 @@ Logging in with Google... Restarting Gemini CLI to continue. }); } } - await runExitCleanup(); - process.exit(RELAUNCH_EXIT_CODE); + await relaunchApp(); }, handleNewAgentsSelect: async (choice: NewAgentsChoice) => { if (newAgents && choice === NewAgentsChoice.ACKNOWLEDGE) { diff --git a/packages/cli/src/ui/auth/ApiAuthDialog.test.tsx b/packages/cli/src/ui/auth/ApiAuthDialog.test.tsx index 86d3204b84..da8b43dd20 100644 --- a/packages/cli/src/ui/auth/ApiAuthDialog.test.tsx +++ b/packages/cli/src/ui/auth/ApiAuthDialog.test.tsx @@ -29,9 +29,16 @@ vi.mock('../hooks/useKeypress.js', () => ({ useKeypress: vi.fn(), })); -vi.mock('../components/shared/text-buffer.js', () => ({ - useTextBuffer: 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('../contexts/UIStateContext.js', () => ({ useUIState: vi.fn(() => ({ diff --git a/packages/cli/src/ui/auth/ApiAuthDialog.tsx b/packages/cli/src/ui/auth/ApiAuthDialog.tsx index c5ac742955..2caad6fd27 100644 --- a/packages/cli/src/ui/auth/ApiAuthDialog.tsx +++ b/packages/cli/src/ui/auth/ApiAuthDialog.tsx @@ -98,7 +98,7 @@ export function ApiAuthDialog({ return ( { - await runExitCleanup(); - process.exit(RELAUNCH_EXIT_CODE); - }, 100); + setTimeout(relaunchApp, 100); return; } @@ -193,7 +189,7 @@ export function AuthDialog({ return ( { vi.clearAllMocks(); exitSpy.mockClear(); vi.useRealTimers(); + _resetRelaunchStateForTesting(); }); it('renders correctly', async () => { diff --git a/packages/cli/src/ui/auth/LoginWithGoogleRestartDialog.tsx b/packages/cli/src/ui/auth/LoginWithGoogleRestartDialog.tsx index 86cd645fee..94ca359b59 100644 --- a/packages/cli/src/ui/auth/LoginWithGoogleRestartDialog.tsx +++ b/packages/cli/src/ui/auth/LoginWithGoogleRestartDialog.tsx @@ -8,8 +8,7 @@ import { type Config } from '@google/gemini-cli-core'; import { Box, Text } from 'ink'; import { theme } from '../semantic-colors.js'; import { useKeypress } from '../hooks/useKeypress.js'; -import { runExitCleanup } from '../../utils/cleanup.js'; -import { RELAUNCH_EXIT_CODE } from '../../utils/processUtils.js'; +import { relaunchApp } from '../../utils/processUtils.js'; interface LoginWithGoogleRestartDialogProps { onDismiss: () => void; @@ -36,8 +35,7 @@ export const LoginWithGoogleRestartDialog = ({ }); } } - await runExitCleanup(); - process.exit(RELAUNCH_EXIT_CODE); + await relaunchApp(); }, 100); return true; } diff --git a/packages/cli/src/ui/auth/useAuth.test.tsx b/packages/cli/src/ui/auth/useAuth.test.tsx index 36d9aeec4f..20a02ffb21 100644 --- a/packages/cli/src/ui/auth/useAuth.test.tsx +++ b/packages/cli/src/ui/auth/useAuth.test.tsx @@ -15,7 +15,11 @@ import { } from 'vitest'; import { renderHook } from '../../test-utils/render.js'; import { useAuthCommand, validateAuthMethodWithSettings } from './useAuth.js'; -import { AuthType, type Config } from '@google/gemini-cli-core'; +import { + AuthType, + type Config, + ProjectIdRequiredError, +} from '@google/gemini-cli-core'; import { AuthState } from '../types.js'; import type { LoadedSettings } from '../../config/settings.js'; import { waitFor } from '../../test-utils/async.js'; @@ -288,5 +292,21 @@ describe('useAuth', () => { expect(result.current.authState).toBe(AuthState.Updating); }); }); + + it('should handle ProjectIdRequiredError without "Failed to login" prefix', async () => { + const projectIdError = new ProjectIdRequiredError(); + (mockConfig.refreshAuth as Mock).mockRejectedValue(projectIdError); + const { result } = renderHook(() => + useAuthCommand(createSettings(AuthType.LOGIN_WITH_GOOGLE), mockConfig), + ); + + await waitFor(() => { + expect(result.current.authError).toBe( + 'This account requires setting the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID env var. See https://goo.gle/gemini-cli-auth-docs#workspace-gca', + ); + expect(result.current.authError).not.toContain('Failed to login'); + expect(result.current.authState).toBe(AuthState.Updating); + }); + }); }); }); diff --git a/packages/cli/src/ui/auth/useAuth.ts b/packages/cli/src/ui/auth/useAuth.ts index 3faec2d5a8..afd438bb00 100644 --- a/packages/cli/src/ui/auth/useAuth.ts +++ b/packages/cli/src/ui/auth/useAuth.ts @@ -12,6 +12,7 @@ import { loadApiKey, debugLogger, isAccountSuspendedError, + ProjectIdRequiredError, } from '@google/gemini-cli-core'; import { getErrorMessage } from '@google/gemini-cli-core'; import { AuthState } from '../types.js'; @@ -143,6 +144,10 @@ export const useAuthCommand = ( appealUrl: suspendedError.appealUrl, appealLinkText: suspendedError.appealLinkText, }); + } else if (e instanceof ProjectIdRequiredError) { + // OAuth succeeded but account setup requires project ID + // Show the error message directly without "Failed to login" prefix + onAuthError(getErrorMessage(e)); } else { onAuthError(`Failed to login. Message: ${getErrorMessage(e)}`); } diff --git a/packages/cli/src/ui/commands/agentsCommand.test.ts b/packages/cli/src/ui/commands/agentsCommand.test.ts index 6b0a40ed5c..5e6cc36efa 100644 --- a/packages/cli/src/ui/commands/agentsCommand.test.ts +++ b/packages/cli/src/ui/commands/agentsCommand.test.ts @@ -105,34 +105,40 @@ describe('agentsCommand', () => { ); }); - it('should reload the agent registry when refresh subcommand is called', async () => { + it('should reload the agent registry when reload subcommand is called', async () => { const reloadSpy = vi.fn().mockResolvedValue(undefined); mockConfig.getAgentRegistry = vi.fn().mockReturnValue({ reload: reloadSpy, }); - const refreshCommand = agentsCommand.subCommands?.find( - (cmd) => cmd.name === 'refresh', + const reloadCommand = agentsCommand.subCommands?.find( + (cmd) => cmd.name === 'reload', ); - expect(refreshCommand).toBeDefined(); + expect(reloadCommand).toBeDefined(); - const result = await refreshCommand!.action!(mockContext, ''); + const result = await reloadCommand!.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 refreshed successfully.', + content: 'Agents reloaded successfully', }); }); - it('should show an error if agent registry is not available during refresh', async () => { + it('should show an error if agent registry is not available during reload', async () => { mockConfig.getAgentRegistry = vi.fn().mockReturnValue(undefined); - const refreshCommand = agentsCommand.subCommands?.find( - (cmd) => cmd.name === 'refresh', + const reloadCommand = agentsCommand.subCommands?.find( + (cmd) => cmd.name === 'reload', ); - const result = await refreshCommand!.action!(mockContext, ''); + const result = await reloadCommand!.action!(mockContext, ''); expect(result).toEqual({ type: 'message', diff --git a/packages/cli/src/ui/commands/agentsCommand.ts b/packages/cli/src/ui/commands/agentsCommand.ts index a7161dfb77..3658c741ff 100644 --- a/packages/cli/src/ui/commands/agentsCommand.ts +++ b/packages/cli/src/ui/commands/agentsCommand.ts @@ -322,9 +322,9 @@ const configCommand: SlashCommand = { completion: completeAllAgents, }; -const agentsRefreshCommand: SlashCommand = { - name: 'refresh', - altNames: ['reload'], +const agentsReloadCommand: SlashCommand = { + name: 'reload', + altNames: ['refresh'], description: 'Reload the agent registry', kind: CommandKind.BUILT_IN, action: async (context: CommandContext) => { @@ -340,7 +340,7 @@ const agentsRefreshCommand: SlashCommand = { context.ui.addItem({ type: MessageType.INFO, - text: 'Refreshing agent registry...', + text: 'Reloading agent registry...', }); await agentRegistry.reload(); @@ -348,7 +348,7 @@ const agentsRefreshCommand: SlashCommand = { return { type: 'message', messageType: 'info', - content: 'Agents refreshed successfully.', + content: 'Agents reloaded successfully', }; }, }; @@ -359,7 +359,7 @@ export const agentsCommand: SlashCommand = { kind: CommandKind.BUILT_IN, subCommands: [ agentsListCommand, - agentsRefreshCommand, + agentsReloadCommand, enableCommand, disableCommand, configCommand, diff --git a/packages/cli/src/ui/commands/chatCommand.test.ts b/packages/cli/src/ui/commands/chatCommand.test.ts index 6ff8d8a52e..c0288fbef2 100644 --- a/packages/cli/src/ui/commands/chatCommand.test.ts +++ b/packages/cli/src/ui/commands/chatCommand.test.ts @@ -99,8 +99,11 @@ describe('chatCommand', () => { it('should have the correct main command definition', () => { expect(chatCommand.name).toBe('chat'); - expect(chatCommand.description).toBe('Manage conversation history'); - expect(chatCommand.subCommands).toHaveLength(5); + expect(chatCommand.description).toBe( + 'Browse auto-saved conversations and manage chat checkpoints', + ); + expect(chatCommand.autoExecute).toBe(true); + expect(chatCommand.subCommands).toHaveLength(6); }); describe('list subcommand', () => { @@ -158,7 +161,7 @@ describe('chatCommand', () => { expect(result).toEqual({ type: 'message', messageType: 'error', - content: 'Missing tag. Usage: /chat save ', + content: 'Missing tag. Usage: /resume save ', }); }); @@ -252,7 +255,7 @@ describe('chatCommand', () => { expect(result).toEqual({ type: 'message', messageType: 'error', - content: 'Missing tag. Usage: /chat resume ', + content: 'Missing tag. Usage: /resume resume ', }); }); @@ -386,7 +389,7 @@ describe('chatCommand', () => { expect(result).toEqual({ type: 'message', messageType: 'error', - content: 'Missing tag. Usage: /chat delete ', + content: 'Missing tag. Usage: /resume delete ', }); }); diff --git a/packages/cli/src/ui/commands/chatCommand.ts b/packages/cli/src/ui/commands/chatCommand.ts index e1969fff67..8b38204aa2 100644 --- a/packages/cli/src/ui/commands/chatCommand.ts +++ b/packages/cli/src/ui/commands/chatCommand.ts @@ -29,6 +29,8 @@ import { MessageType } from '../types.js'; import { exportHistoryToFile } from '../utils/historyExportUtils.js'; import { convertToRestPayload } from '@google/gemini-cli-core'; +const CHECKPOINT_MENU_GROUP = 'checkpoints'; + const getSavedChatTags = async ( context: CommandContext, mtSortDesc: boolean, @@ -70,7 +72,7 @@ const getSavedChatTags = async ( const listCommand: SlashCommand = { name: 'list', - description: 'List saved conversation checkpoints', + description: 'List saved manual conversation checkpoints', kind: CommandKind.BUILT_IN, autoExecute: true, action: async (context): Promise => { @@ -88,7 +90,7 @@ const listCommand: SlashCommand = { const saveCommand: SlashCommand = { name: 'save', description: - 'Save the current conversation as a checkpoint. Usage: /chat save ', + 'Save the current conversation as a checkpoint. Usage: /resume save ', kind: CommandKind.BUILT_IN, autoExecute: false, action: async (context, args): Promise => { @@ -97,7 +99,7 @@ const saveCommand: SlashCommand = { return { type: 'message', messageType: 'error', - content: 'Missing tag. Usage: /chat save ', + content: 'Missing tag. Usage: /resume save ', }; } @@ -117,7 +119,7 @@ const saveCommand: SlashCommand = { ' already exists. Do you want to overwrite it?', ), originalInvocation: { - raw: context.invocation?.raw || `/chat save ${tag}`, + raw: context.invocation?.raw || `/resume save ${tag}`, }, }; } @@ -153,11 +155,11 @@ const saveCommand: SlashCommand = { }, }; -const resumeCommand: SlashCommand = { +const resumeCheckpointCommand: SlashCommand = { name: 'resume', altNames: ['load'], description: - 'Resume a conversation from a checkpoint. Usage: /chat resume ', + 'Resume a conversation from a checkpoint. Usage: /resume resume ', kind: CommandKind.BUILT_IN, autoExecute: true, action: async (context, args) => { @@ -166,7 +168,7 @@ const resumeCommand: SlashCommand = { return { type: 'message', messageType: 'error', - content: 'Missing tag. Usage: /chat resume ', + content: 'Missing tag. Usage: /resume resume ', }; } @@ -235,7 +237,7 @@ const resumeCommand: SlashCommand = { const deleteCommand: SlashCommand = { name: 'delete', - description: 'Delete a conversation checkpoint. Usage: /chat delete ', + description: 'Delete a conversation checkpoint. Usage: /resume delete ', kind: CommandKind.BUILT_IN, autoExecute: true, action: async (context, args): Promise => { @@ -244,7 +246,7 @@ const deleteCommand: SlashCommand = { return { type: 'message', messageType: 'error', - content: 'Missing tag. Usage: /chat delete ', + content: 'Missing tag. Usage: /resume delete ', }; } @@ -277,7 +279,7 @@ const deleteCommand: SlashCommand = { const shareCommand: SlashCommand = { name: 'share', description: - 'Share the current conversation to a markdown or json file. Usage: /chat share ', + 'Share the current conversation to a markdown or json file. Usage: /resume share ', kind: CommandKind.BUILT_IN, autoExecute: false, action: async (context, args): Promise => { @@ -376,16 +378,40 @@ export const debugCommand: SlashCommand = { }, }; +export const checkpointSubCommands: SlashCommand[] = [ + listCommand, + saveCommand, + resumeCheckpointCommand, + deleteCommand, + shareCommand, +]; + +const checkpointCompatibilityCommand: SlashCommand = { + name: 'checkpoints', + altNames: ['checkpoint'], + description: 'Compatibility command for nested checkpoint operations', + kind: CommandKind.BUILT_IN, + hidden: true, + autoExecute: false, + subCommands: checkpointSubCommands, +}; + +export const chatResumeSubCommands: SlashCommand[] = [ + ...checkpointSubCommands.map((subCommand) => ({ + ...subCommand, + suggestionGroup: CHECKPOINT_MENU_GROUP, + })), + checkpointCompatibilityCommand, +]; + export const chatCommand: SlashCommand = { name: 'chat', - description: 'Manage conversation history', + description: 'Browse auto-saved conversations and manage chat checkpoints', kind: CommandKind.BUILT_IN, - autoExecute: false, - subCommands: [ - listCommand, - saveCommand, - resumeCommand, - deleteCommand, - shareCommand, - ], + autoExecute: true, + action: async () => ({ + type: 'dialog', + dialog: 'sessionBrowser', + }), + subCommands: chatResumeSubCommands, }; diff --git a/packages/cli/src/ui/commands/extensionsCommand.test.ts b/packages/cli/src/ui/commands/extensionsCommand.test.ts index c873050490..89147a1b90 100644 --- a/packages/cli/src/ui/commands/extensionsCommand.test.ts +++ b/packages/cli/src/ui/commands/extensionsCommand.test.ts @@ -755,7 +755,7 @@ describe('extensionsCommand', () => { await uninstallAction!(mockContext, ''); expect(mockContext.ui.addItem).toHaveBeenCalledWith({ type: MessageType.ERROR, - text: 'Usage: /extensions uninstall ', + text: 'Usage: /extensions uninstall |--all', }); expect(mockUninstallExtension).not.toHaveBeenCalled(); }); @@ -892,7 +892,7 @@ describe('extensionsCommand', () => { }); }); - describe('restart', () => { + describe('reload', () => { 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 === 'restart', + (c) => c.name === 'reload', )?.action; expect(restartAction).not.toBeNull(); @@ -911,7 +911,7 @@ describe('extensionsCommand', () => { getExtensions: mockGetExtensions, restartExtension: mockRestartExtension, })); - mockContext.invocation!.name = 'restart'; + mockContext.invocation!.name = 'reload'; }); it('should show a message if no extensions are installed', async () => { @@ -930,7 +930,7 @@ describe('extensionsCommand', () => { }); }); - it('restarts all active extensions when --all is provided', async () => { + it('reloads 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: 'Restarting 2 extensions...', + text: 'Reloading 2 extensions...', }), ); expect(mockContext.ui.addItem).toHaveBeenCalledWith( expect.objectContaining({ type: MessageType.INFO, - text: '2 extensions restarted successfully.', + text: '2 extensions reloaded successfully', }), ); expect(mockContext.ui.dispatchExtensionStateUpdate).toHaveBeenCalledWith({ @@ -986,7 +986,7 @@ describe('extensionsCommand', () => { ); }); - it('restarts only specified active extensions', async () => { + it('reloads 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 restart |--all', + text: 'Usage: /extensions reload |--all', }), ); expect(mockRestartExtension).not.toHaveBeenCalled(); }); - it('handles errors during extension restart', async () => { + it('handles errors during extension reload', 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 restart some extensions:\n ext1: Failed to restart', + text: 'Failed to reload some extensions:\n ext1: Failed to restart', }), ); }); @@ -1066,7 +1066,7 @@ describe('extensionsCommand', () => { ); }); - it('does not restart any extensions if none are found', async () => { + it('does not reload 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 restart command', async () => { - mockContext.invocation!.name = 'restart'; + it('should suggest only enabled extension names for the reload command', async () => { + mockContext.invocation!.name = 'reload'; const mockExtensions = [ { name: 'ext1', isActive: true }, { name: 'ext2', isActive: false }, diff --git a/packages/cli/src/ui/commands/extensionsCommand.ts b/packages/cli/src/ui/commands/extensionsCommand.ts index 842a680a14..051d337019 100644 --- a/packages/cli/src/ui/commands/extensionsCommand.ts +++ b/packages/cli/src/ui/commands/extensionsCommand.ts @@ -176,7 +176,7 @@ async function restartAction( if (!all && names?.length === 0) { context.ui.addItem({ type: MessageType.ERROR, - text: 'Usage: /extensions restart |--all', + text: 'Usage: /extensions reload |--all', }); return Promise.resolve(); } @@ -208,12 +208,12 @@ async function restartAction( const s = extensionsToRestart.length > 1 ? 's' : ''; - const restartingMessage = { + const reloadingMessage = { type: MessageType.INFO, - text: `Restarting ${extensionsToRestart.length} extension${s}...`, + text: `Reloading ${extensionsToRestart.length} extension${s}...`, color: theme.text.primary, }; - context.ui.addItem(restartingMessage); + context.ui.addItem(reloadingMessage); 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 restart some extensions:\n ${errorMessages}`, + text: `Failed to reload some extensions:\n ${errorMessages}`, }); } else { const infoItem: HistoryItemInfo = { type: MessageType.INFO, - text: `${extensionsToRestart.length} extension${s} restarted successfully.`, + text: `${extensionsToRestart.length} extension${s} reloaded successfully`, icon: emptyIcon, color: theme.text.primary, }; @@ -594,33 +594,53 @@ async function uninstallAction(context: CommandContext, args: string) { return; } - const name = args.trim(); - if (!name) { + 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) { context.ui.addItem({ type: MessageType.ERROR, - text: `Usage: /extensions uninstall `, + text: `Usage: /extensions uninstall |--all`, }); return; } - context.ui.addItem({ - type: MessageType.INFO, - text: `Uninstalling extension "${name}"...`, - }); + let namesToUninstall: string[] = []; + if (all) { + namesToUninstall = extensionLoader.getExtensions().map((ext) => ext.name); + } else { + namesToUninstall = names; + } - try { - await extensionLoader.uninstallExtension(name, false); + if (namesToUninstall.length === 0) { context.ui.addItem({ type: MessageType.INFO, - text: `Extension "${name}" uninstalled successfully.`, + text: all ? 'No extensions installed.' : 'No extension name provided.', }); - } catch (error) { + return; + } + + for (const extensionName of namesToUninstall) { context.ui.addItem({ - type: MessageType.ERROR, - text: `Failed to uninstall extension "${name}": ${getErrorMessage( - error, - )}`, + type: MessageType.INFO, + text: `Uninstalling extension "${extensionName}"...`, }); + + 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, + )}`, + }); + } } } @@ -709,7 +729,8 @@ export function completeExtensions( } if ( context.invocation?.name === 'disable' || - context.invocation?.name === 'restart' + context.invocation?.name === 'restart' || + context.invocation?.name === 'reload' ) { extensions = extensions.filter((ext) => ext.isActive); } @@ -804,9 +825,10 @@ const exploreExtensionsCommand: SlashCommand = { action: exploreAction, }; -const restartCommand: SlashCommand = { - name: 'restart', - description: 'Restart all extensions', +const reloadCommand: SlashCommand = { + name: 'reload', + altNames: ['restart'], + description: 'Reload all extensions', kind: CommandKind.BUILT_IN, autoExecute: false, action: restartAction, @@ -843,7 +865,7 @@ export function extensionsCommand( listExtensionsCommand, updateExtensionsCommand, exploreExtensionsCommand, - restartCommand, + reloadCommand, ...conditionalCommands, ], action: (context, args) => diff --git a/packages/cli/src/ui/commands/footerCommand.tsx b/packages/cli/src/ui/commands/footerCommand.tsx new file mode 100644 index 0000000000..4a6760e229 --- /dev/null +++ b/packages/cli/src/ui/commands/footerCommand.tsx @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { + type SlashCommand, + type CommandContext, + type OpenCustomDialogActionReturn, + CommandKind, +} from './types.js'; +import { FooterConfigDialog } from '../components/FooterConfigDialog.js'; + +export const footerCommand: SlashCommand = { + name: 'footer', + altNames: ['statusline'], + description: 'Configure which items appear in the footer (statusline)', + kind: CommandKind.BUILT_IN, + autoExecute: true, + action: (context: CommandContext): OpenCustomDialogActionReturn => ({ + type: 'custom_dialog', + component: , + }), +}; diff --git a/packages/cli/src/ui/commands/mcpCommand.ts b/packages/cli/src/ui/commands/mcpCommand.ts index e488db780f..9ccaaf4273 100644 --- a/packages/cli/src/ui/commands/mcpCommand.ts +++ b/packages/cli/src/ui/commands/mcpCommand.ts @@ -149,7 +149,7 @@ const authCommand: SlashCommand = { return { type: 'message', messageType: 'info', - content: `Successfully authenticated and refreshed tools for '${serverName}'.`, + content: `Successfully authenticated and reloaded tools for '${serverName}'`, }; } catch (error) { return { @@ -325,10 +325,10 @@ const schemaCommand: SlashCommand = { action: (context) => listAction(context, true, true), }; -const refreshCommand: SlashCommand = { - name: 'refresh', - altNames: ['reload'], - description: 'Restarts MCP servers', +const reloadCommand: SlashCommand = { + name: 'reload', + altNames: ['refresh'], + description: 'Reloads MCP servers', kind: CommandKind.BUILT_IN, autoExecute: true, action: async ( @@ -354,7 +354,7 @@ const refreshCommand: SlashCommand = { context.ui.addItem({ type: 'info', - text: 'Restarting MCP servers...', + text: 'Reloading MCP servers...', }); await mcpClientManager.restart(); @@ -460,7 +460,7 @@ async function handleEnableDisable( const mcpClientManager = config.getMcpClientManager(); if (mcpClientManager) { context.ui.addItem( - { type: 'info', text: 'Restarting MCP servers...' }, + { type: 'info', text: 'Reloading MCP servers...' }, Date.now(), ); await mcpClientManager.restart(); @@ -521,7 +521,7 @@ export const mcpCommand: SlashCommand = { descCommand, schemaCommand, authCommand, - refreshCommand, + reloadCommand, enableCommand, disableCommand, ], diff --git a/packages/cli/src/ui/commands/memoryCommand.test.ts b/packages/cli/src/ui/commands/memoryCommand.test.ts index 1a2c7e3936..2d70b67357 100644 --- a/packages/cli/src/ui/commands/memoryCommand.test.ts +++ b/packages/cli/src/ui/commands/memoryCommand.test.ts @@ -39,13 +39,13 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => { return { type: 'message', messageType: 'info', - content: `Memory refreshed successfully. Loaded ${memoryContent.length} characters from ${fileCount} file(s).`, + content: `Memory reloaded successfully. Loaded ${memoryContent.length} characters from ${fileCount} file(s).`, }; } return { type: 'message', messageType: 'info', - content: 'Memory refreshed successfully.', + content: 'Memory reloaded successfully.', }; }), showMemory: vi.fn(), @@ -63,7 +63,7 @@ describe('memoryCommand', () => { let mockContext: CommandContext; const getSubCommand = ( - name: 'show' | 'add' | 'refresh' | 'list', + name: 'show' | 'add' | 'reload' | 'list', ): SlashCommand => { const subCommand = memoryCommand.subCommands?.find( (cmd) => cmd.name === name, @@ -206,15 +206,15 @@ describe('memoryCommand', () => { }); }); - describe('/memory refresh', () => { - let refreshCommand: SlashCommand; + describe('/memory reload', () => { + let reloadCommand: SlashCommand; let mockSetUserMemory: Mock; let mockSetGeminiMdFileCount: Mock; let mockSetGeminiMdFilePaths: Mock; let mockContextManagerRefresh: Mock; beforeEach(() => { - refreshCommand = getSubCommand('refresh'); + reloadCommand = getSubCommand('reload'); 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 (!refreshCommand.action) throw new Error('Command has no action'); + if (!reloadCommand.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 refreshCommand.action(mockContext, ''); + await reloadCommand.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 refreshed successfully. Loaded 18 characters from 3 file(s).', + text: 'Memory reloaded successfully. Loaded 18 characters from 3 file(s).', }, expect.any(Number), ); }); - it('should display success message when memory is refreshed with content (Legacy)', async () => { - if (!refreshCommand.action) throw new Error('Command has no action'); + it('should display success message when memory is reloaded with content (Legacy)', async () => { + if (!reloadCommand.action) throw new Error('Command has no action'); const successMessage = { type: 'message', messageType: MessageType.INFO, content: - 'Memory refreshed successfully. Loaded 18 characters from 2 file(s).', + 'Memory reloaded successfully. Loaded 18 characters from 2 file(s).', }; mockRefreshMemory.mockResolvedValue(successMessage); - await refreshCommand.action(mockContext, ''); + await reloadCommand.action(mockContext, ''); expect(mockContext.ui.addItem).toHaveBeenCalledWith( { type: MessageType.INFO, - text: 'Refreshing memory from source files...', + text: 'Reloading memory from source files...', }, expect.any(Number), ); @@ -316,42 +316,42 @@ describe('memoryCommand', () => { expect(mockContext.ui.addItem).toHaveBeenCalledWith( { type: MessageType.INFO, - text: 'Memory refreshed successfully. Loaded 18 characters from 2 file(s).', + text: 'Memory reloaded successfully. Loaded 18 characters from 2 file(s).', }, expect.any(Number), ); }); - it('should display success message when memory is refreshed with no content', async () => { - if (!refreshCommand.action) throw new Error('Command has no action'); + it('should display success message when memory is reloaded with no content', async () => { + if (!reloadCommand.action) throw new Error('Command has no action'); const successMessage = { type: 'message', messageType: MessageType.INFO, - content: 'Memory refreshed successfully. No memory content found.', + content: 'Memory reloaded successfully. No memory content found.', }; mockRefreshMemory.mockResolvedValue(successMessage); - await refreshCommand.action(mockContext, ''); + await reloadCommand.action(mockContext, ''); expect(mockRefreshMemory).toHaveBeenCalledOnce(); expect(mockContext.ui.addItem).toHaveBeenCalledWith( { type: MessageType.INFO, - text: 'Memory refreshed successfully. No memory content found.', + text: 'Memory reloaded successfully. No memory content found.', }, expect.any(Number), ); }); - it('should display an error message if refreshing fails', async () => { - if (!refreshCommand.action) throw new Error('Command has no action'); + it('should display an error message if reloading fails', async () => { + if (!reloadCommand.action) throw new Error('Command has no action'); const error = new Error('Failed to read memory files.'); mockRefreshMemory.mockRejectedValue(error); - await refreshCommand.action(mockContext, ''); + await reloadCommand.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 refreshing memory: ${error.message}`, + text: `Error reloading memory: ${error.message}`, }, expect.any(Number), ); }); it('should not throw if config service is unavailable', async () => { - if (!refreshCommand.action) throw new Error('Command has no action'); + if (!reloadCommand.action) throw new Error('Command has no action'); const nullConfigContext = createMockCommandContext({ services: { config: null }, }); await expect( - refreshCommand.action(nullConfigContext, ''), + reloadCommand.action(nullConfigContext, ''), ).resolves.toBeUndefined(); expect(nullConfigContext.ui.addItem).toHaveBeenCalledWith( { type: MessageType.INFO, - text: 'Refreshing memory from source files...', + text: 'Reloading memory from source files...', }, expect.any(Number), ); diff --git a/packages/cli/src/ui/commands/memoryCommand.ts b/packages/cli/src/ui/commands/memoryCommand.ts index a31280f824..575c3a32eb 100644 --- a/packages/cli/src/ui/commands/memoryCommand.ts +++ b/packages/cli/src/ui/commands/memoryCommand.ts @@ -63,16 +63,16 @@ export const memoryCommand: SlashCommand = { }, }, { - name: 'refresh', - altNames: ['reload'], - description: 'Refresh the memory from the source', + name: 'reload', + altNames: ['refresh'], + description: 'Reload the memory from the source', kind: CommandKind.BUILT_IN, autoExecute: true, action: async (context) => { context.ui.addItem( { type: MessageType.INFO, - text: 'Refreshing memory from source files...', + text: 'Reloading 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 refreshing memory: ${(error as Error).message}`, + text: `Error reloading memory: ${(error as Error).message}`, }, Date.now(), ); diff --git a/packages/cli/src/ui/commands/planCommand.test.ts b/packages/cli/src/ui/commands/planCommand.test.ts index 2608b44ca9..fab1267b17 100644 --- a/packages/cli/src/ui/commands/planCommand.test.ts +++ b/packages/cli/src/ui/commands/planCommand.test.ts @@ -14,7 +14,9 @@ import { coreEvents, processSingleFileContent, type ProcessedFileReadResult, + readFileWithEncoding, } from '@google/gemini-cli-core'; +import { copyToClipboard } from '../utils/commandUtils.js'; vi.mock('@google/gemini-cli-core', async (importOriginal) => { const actual = @@ -25,6 +27,7 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => { emitFeedback: vi.fn(), }, processSingleFileContent: vi.fn(), + readFileWithEncoding: vi.fn(), partToString: vi.fn((val) => val), }; }); @@ -35,9 +38,14 @@ vi.mock('node:path', async (importOriginal) => { ...actual, default: { ...actual }, join: vi.fn((...args) => args.join('/')), + basename: vi.fn((p) => p.split('/').pop()), }; }); +vi.mock('../utils/commandUtils.js', () => ({ + copyToClipboard: vi.fn(), +})); + describe('planCommand', () => { let mockContext: CommandContext; @@ -115,4 +123,46 @@ describe('planCommand', () => { text: '# Approved Plan Content', }); }); + + describe('copy subcommand', () => { + it('should copy the approved plan to clipboard', async () => { + const mockPlanPath = '/mock/plans/dir/approved-plan.md'; + vi.mocked( + mockContext.services.config!.getApprovedPlanPath, + ).mockReturnValue(mockPlanPath); + vi.mocked(readFileWithEncoding).mockResolvedValue('# Plan Content'); + + const copySubCommand = planCommand.subCommands?.find( + (sc) => sc.name === 'copy', + ); + if (!copySubCommand?.action) throw new Error('Copy action missing'); + + await copySubCommand.action(mockContext, ''); + + expect(readFileWithEncoding).toHaveBeenCalledWith(mockPlanPath); + expect(copyToClipboard).toHaveBeenCalledWith('# Plan Content'); + expect(coreEvents.emitFeedback).toHaveBeenCalledWith( + 'info', + 'Plan copied to clipboard (approved-plan.md).', + ); + }); + + it('should warn if no approved plan is found', async () => { + vi.mocked( + mockContext.services.config!.getApprovedPlanPath, + ).mockReturnValue(undefined); + + const copySubCommand = planCommand.subCommands?.find( + (sc) => sc.name === 'copy', + ); + if (!copySubCommand?.action) throw new Error('Copy action missing'); + + await copySubCommand.action(mockContext, ''); + + expect(coreEvents.emitFeedback).toHaveBeenCalledWith( + 'warning', + 'No approved plan found to copy.', + ); + }); + }); }); diff --git a/packages/cli/src/ui/commands/planCommand.ts b/packages/cli/src/ui/commands/planCommand.ts index d9cc6739da..cfa3f9433e 100644 --- a/packages/cli/src/ui/commands/planCommand.ts +++ b/packages/cli/src/ui/commands/planCommand.ts @@ -4,22 +4,54 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { CommandKind, type SlashCommand } from './types.js'; +import { + type CommandContext, + CommandKind, + type SlashCommand, +} from './types.js'; import { ApprovalMode, coreEvents, debugLogger, processSingleFileContent, partToString, + readFileWithEncoding, } from '@google/gemini-cli-core'; import { MessageType } from '../types.js'; import * as path from 'node:path'; +import { copyToClipboard } from '../utils/commandUtils.js'; + +async function copyAction(context: CommandContext) { + const config = context.services.config; + if (!config) { + debugLogger.debug('Plan copy command: config is not available in context'); + return; + } + + const planPath = config.getApprovedPlanPath(); + + if (!planPath) { + coreEvents.emitFeedback('warning', 'No approved plan found to copy.'); + return; + } + + try { + const content = await readFileWithEncoding(planPath); + await copyToClipboard(content); + coreEvents.emitFeedback( + 'info', + `Plan copied to clipboard (${path.basename(planPath)}).`, + ); + } catch (error) { + coreEvents.emitFeedback('error', `Failed to copy plan: ${error}`, error); + } +} export const planCommand: SlashCommand = { name: 'plan', description: 'Switch to Plan Mode and view current plan', kind: CommandKind.BUILT_IN, - autoExecute: true, + autoExecute: false, action: async (context) => { const config = context.services.config; if (!config) { @@ -62,4 +94,13 @@ export const planCommand: SlashCommand = { ); } }, + subCommands: [ + { + name: 'copy', + description: 'Copy the currently approved plan to your clipboard', + kind: CommandKind.BUILT_IN, + autoExecute: true, + action: copyAction, + }, + ], }; diff --git a/packages/cli/src/ui/commands/resumeCommand.test.ts b/packages/cli/src/ui/commands/resumeCommand.test.ts new file mode 100644 index 0000000000..89097e6833 --- /dev/null +++ b/packages/cli/src/ui/commands/resumeCommand.test.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, expect, it } from 'vitest'; +import { resumeCommand } from './resumeCommand.js'; +import type { CommandContext } from './types.js'; + +describe('resumeCommand', () => { + it('should open the session browser for bare /resume', async () => { + const result = await resumeCommand.action?.({} as CommandContext, ''); + expect(result).toEqual({ + type: 'dialog', + dialog: 'sessionBrowser', + }); + }); + + it('should expose unified chat subcommands directly under /resume', () => { + const visibleSubCommandNames = (resumeCommand.subCommands ?? []) + .filter((subCommand) => !subCommand.hidden) + .map((subCommand) => subCommand.name); + + expect(visibleSubCommandNames).toEqual( + expect.arrayContaining(['list', 'save', 'resume', 'delete', 'share']), + ); + }); + + it('should keep a hidden /resume checkpoints compatibility alias', () => { + const checkpoints = resumeCommand.subCommands?.find( + (subCommand) => subCommand.name === 'checkpoints', + ); + expect(checkpoints?.hidden).toBe(true); + expect( + checkpoints?.subCommands?.map((subCommand) => subCommand.name), + ).toEqual( + expect.arrayContaining(['list', 'save', 'resume', 'delete', 'share']), + ); + }); +}); diff --git a/packages/cli/src/ui/commands/resumeCommand.ts b/packages/cli/src/ui/commands/resumeCommand.ts index 636dfef1b6..bbb35a898c 100644 --- a/packages/cli/src/ui/commands/resumeCommand.ts +++ b/packages/cli/src/ui/commands/resumeCommand.ts @@ -10,10 +10,11 @@ import type { SlashCommand, } from './types.js'; import { CommandKind } from './types.js'; +import { chatResumeSubCommands } from './chatCommand.js'; export const resumeCommand: SlashCommand = { name: 'resume', - description: 'Browse and resume auto-saved conversations', + description: 'Browse auto-saved conversations and manage chat checkpoints', kind: CommandKind.BUILT_IN, autoExecute: true, action: async ( @@ -23,4 +24,5 @@ export const resumeCommand: SlashCommand = { type: 'dialog', dialog: 'sessionBrowser', }), + subCommands: chatResumeSubCommands, }; diff --git a/packages/cli/src/ui/commands/statsCommand.test.ts b/packages/cli/src/ui/commands/statsCommand.test.ts index 2f36c333b9..57fff84b6b 100644 --- a/packages/cli/src/ui/commands/statsCommand.test.ts +++ b/packages/cli/src/ui/commands/statsCommand.test.ts @@ -20,6 +20,7 @@ vi.mock('@google/gemini-cli-core', async (importOriginal) => { UserAccountManager: vi.fn().mockImplementation(() => ({ getCachedGoogleAccount: vi.fn().mockReturnValue('mock@example.com'), })), + getG1CreditBalance: vi.fn().mockReturnValue(undefined), }; }); diff --git a/packages/cli/src/ui/commands/types.ts b/packages/cli/src/ui/commands/types.ts index 2cbb9da9a7..e4f0d0ad52 100644 --- a/packages/cli/src/ui/commands/types.ts +++ b/packages/cli/src/ui/commands/types.ts @@ -177,7 +177,9 @@ export type SlashCommandActionReturn = export enum CommandKind { BUILT_IN = 'built-in', - FILE = 'file', + USER_FILE = 'user-file', + WORKSPACE_FILE = 'workspace-file', + EXTENSION_FILE = 'extension-file', MCP_PROMPT = 'mcp-prompt', AGENT = 'agent', } @@ -188,6 +190,11 @@ export interface SlashCommand { altNames?: string[]; description: string; hidden?: boolean; + /** + * Optional grouping label for slash completion UI sections. + * Commands with the same label are rendered under one separator. + */ + suggestionGroup?: string; kind: CommandKind; @@ -203,6 +210,9 @@ 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, @@ -212,7 +222,7 @@ export interface SlashCommand { | SlashCommandActionReturn | Promise; - // Provides argument completion (e.g., completing a tag for `/chat resume `). + // Provides argument completion (e.g., completing a tag for `/resume resume `). completion?: ( context: CommandContext, partialArg: string, diff --git a/packages/cli/src/ui/components/ApprovalModeIndicator.tsx b/packages/cli/src/ui/components/ApprovalModeIndicator.tsx index b5a981ac7a..4eaf3f18a4 100644 --- a/packages/cli/src/ui/components/ApprovalModeIndicator.tsx +++ b/packages/cli/src/ui/components/ApprovalModeIndicator.tsx @@ -8,22 +8,14 @@ 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 = ({ approvalMode, allowPlanMode, @@ -32,29 +24,32 @@ export const ApprovalModeIndicator: React.FC = ({ 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 = APPROVAL_MODE_TEXT.AUTO_EDIT; + textContent = 'auto-accept edits'; subText = allowPlanMode - ? APPROVAL_MODE_TEXT.HINT_SWITCH_TO_PLAN_MODE - : APPROVAL_MODE_TEXT.HINT_SWITCH_TO_MANUAL_MODE; + ? `${cycleHint} to plan` + : `${cycleHint} to manual`; break; case ApprovalMode.PLAN: textColor = theme.status.success; - textContent = APPROVAL_MODE_TEXT.PLAN; - subText = APPROVAL_MODE_TEXT.HINT_SWITCH_TO_MANUAL_MODE; + textContent = 'plan'; + subText = `${cycleHint} to manual`; break; case ApprovalMode.YOLO: textColor = theme.status.error; - textContent = APPROVAL_MODE_TEXT.YOLO; - subText = APPROVAL_MODE_TEXT.HINT_SWITCH_TO_YOLO_MODE; + textContent = 'YOLO'; + subText = yoloHint; break; case ApprovalMode.DEFAULT: default: textColor = theme.text.accent; textContent = ''; - subText = APPROVAL_MODE_TEXT.HINT_SWITCH_TO_AUTO_EDIT_MODE; + subText = `${cycleHint} to accept edits`; break; } diff --git a/packages/cli/src/ui/components/AskUserDialog.test.tsx b/packages/cli/src/ui/components/AskUserDialog.test.tsx index 1bd29241db..0857306ea8 100644 --- a/packages/cli/src/ui/components/AskUserDialog.test.tsx +++ b/packages/cli/src/ui/components/AskUserDialog.test.tsx @@ -1347,4 +1347,47 @@ 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( + , + { 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}`, + }); + }); + }); }); diff --git a/packages/cli/src/ui/components/AskUserDialog.tsx b/packages/cli/src/ui/components/AskUserDialog.tsx index 9606513510..284e4e1df8 100644 --- a/packages/cli/src/ui/components/AskUserDialog.tsx +++ b/packages/cli/src/ui/components/AskUserDialog.tsx @@ -23,7 +23,11 @@ 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 { useTextBuffer } from './shared/text-buffer.js'; +import { formatCommand } from '../utils/keybindingUtils.js'; +import { + useTextBuffer, + expandPastePlaceholders, +} from './shared/text-buffer.js'; import { getCachedStringWidth } from '../utils/textUtils.js'; import { useTabbedNavigation } from '../hooks/useTabbedNavigation.js'; import { DialogFooter } from './shared/DialogFooter.js'; @@ -252,7 +256,7 @@ const ReviewView: React.FC = ({ @@ -302,10 +306,12 @@ const TextQuestionView: React.FC = ({ const lastTextValueRef = useRef(textValue); useEffect(() => { if (textValue !== lastTextValueRef.current) { - onSelectionChange?.(textValue); + onSelectionChange?.( + expandPastePlaceholders(textValue, buffer.pastedContent), + ); lastTextValueRef.current = textValue; } - }, [textValue, onSelectionChange]); + }, [textValue, onSelectionChange, buffer.pastedContent]); // Handle Ctrl+C to clear all text const handleExtraKeys = useCallback( @@ -588,11 +594,15 @@ const ChoiceQuestionView: React.FC = ({ } }); if (includeCustomOption && customOption.trim()) { - answers.push(customOption.trim()); + const expanded = expandPastePlaceholders( + customOption, + customBuffer.pastedContent, + ); + answers.push(expanded.trim()); } return answers.join(', '); }, - [questionOptions], + [questionOptions, customBuffer.pastedContent], ); // Synchronize selection changes with parent - only when it actually changes @@ -757,7 +767,12 @@ const ChoiceQuestionView: React.FC = ({ } else if (itemValue.type === 'other') { // In single select, selecting other submits it if it has text if (customOptionText.trim()) { - onAnswer(customOptionText.trim()); + onAnswer( + expandPastePlaceholders( + customOptionText, + customBuffer.pastedContent, + ).trim(), + ); } } } @@ -767,6 +782,7 @@ const ChoiceQuestionView: React.FC = ({ selectedIndices, isCustomOptionSelected, customOptionText, + customBuffer.pastedContent, onAnswer, buildAnswerString, ], @@ -1146,7 +1162,7 @@ export const AskUserDialog: React.FC = ({ navigationActions={ questions.length > 1 ? currentQuestion.type === 'text' || isEditingCustomOption - ? 'Tab/Shift+Tab to switch questions' + ? `${formatCommand(Command.DIALOG_NEXT)}/${formatCommand(Command.DIALOG_PREV)} to switch questions` : '←/→ to switch questions' : currentQuestion.type === 'text' || isEditingCustomOption ? undefined diff --git a/packages/cli/src/ui/components/BackgroundShellDisplay.tsx b/packages/cli/src/ui/components/BackgroundShellDisplay.tsx index 03cd10823d..16093ef0d7 100644 --- a/packages/cli/src/ui/components/BackgroundShellDisplay.tsx +++ b/packages/cli/src/ui/components/BackgroundShellDisplay.tsx @@ -427,7 +427,7 @@ export const BackgroundShellDisplay = ({ height="100%" width="100%" borderStyle="single" - borderColor={isFocused ? theme.border.focused : undefined} + borderColor={isFocused ? theme.ui.focus : undefined} > {renderTabs()} diff --git a/packages/cli/src/ui/components/ColorsDisplay.test.tsx b/packages/cli/src/ui/components/ColorsDisplay.test.tsx new file mode 100644 index 0000000000..ec44bd6406 --- /dev/null +++ b/packages/cli/src/ui/components/ColorsDisplay.test.tsx @@ -0,0 +1,118 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { renderWithProviders } from '../../test-utils/render.js'; +import { ColorsDisplay } from './ColorsDisplay.js'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { themeManager } from '../themes/theme-manager.js'; +import type { Theme, ColorsTheme } from '../themes/theme.js'; +import type { SemanticColors } from '../themes/semantic-tokens.js'; + +describe('ColorsDisplay', () => { + beforeEach(() => { + vi.spyOn(themeManager, 'getSemanticColors').mockReturnValue({ + text: { + primary: '#ffffff', + secondary: '#cccccc', + link: '#0000ff', + accent: '#ff00ff', + response: '#ffffff', + }, + background: { + primary: '#000000', + message: '#111111', + input: '#222222', + focus: '#333333', + diff: { + added: '#003300', + removed: '#330000', + }, + }, + border: { + default: '#555555', + }, + ui: { + comment: '#666666', + symbol: '#cccccc', + active: '#0000ff', + dark: '#333333', + focus: '#0000ff', + gradient: undefined, + }, + status: { + error: '#ff0000', + success: '#00ff00', + warning: '#ffff00', + }, + }); + + vi.spyOn(themeManager, 'getActiveTheme').mockReturnValue({ + name: 'Test Theme', + type: 'dark', + colors: {} as unknown as ColorsTheme, + semanticColors: { + text: { + primary: '#ffffff', + secondary: '#cccccc', + link: '#0000ff', + accent: '#ff00ff', + response: '#ffffff', + }, + background: { + primary: '#000000', + message: '#111111', + input: '#222222', + diff: { + added: '#003300', + removed: '#330000', + }, + }, + border: { + default: '#555555', + }, + ui: { + comment: '#666666', + symbol: '#cccccc', + active: '#0000ff', + dark: '#333333', + focus: '#0000ff', + gradient: undefined, + }, + status: { + error: '#ff0000', + success: '#00ff00', + warning: '#ffff00', + }, + } as unknown as SemanticColors, + } as unknown as Theme); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('renders correctly', async () => { + const mockTheme = themeManager.getActiveTheme(); + const { lastFrame, waitUntilReady, unmount } = renderWithProviders( + , + ); + await waitUntilReady(); + const output = lastFrame(); + + // Check for title and description + expect(output).toContain('How do colors get applied?'); + expect(output).toContain('Hex:'); + + // Check for some color names and values expect(output).toContain('text.primary'); + expect(output).toContain('#ffffff'); + expect(output).toContain('background.diff.added'); + expect(output).toContain('#003300'); + expect(output).toContain('border.default'); + expect(output).toContain('#555555'); + + unmount(); + }); +}); diff --git a/packages/cli/src/ui/components/ColorsDisplay.tsx b/packages/cli/src/ui/components/ColorsDisplay.tsx new file mode 100644 index 0000000000..96b98bf540 --- /dev/null +++ b/packages/cli/src/ui/components/ColorsDisplay.tsx @@ -0,0 +1,277 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import type React from 'react'; +import { Box, Text } from 'ink'; +import Gradient from 'ink-gradient'; +import { theme } from '../semantic-colors.js'; +import type { Theme } from '../themes/theme.js'; + +interface StandardColorRow { + type: 'standard'; + name: string; + value: string; +} + +interface GradientColorRow { + type: 'gradient'; + name: string; + value: string[]; +} + +interface BackgroundColorRow { + type: 'background'; + name: string; + value: string; +} + +type ColorRow = StandardColorRow | GradientColorRow | BackgroundColorRow; + +const VALUE_COLUMN_WIDTH = 10; + +const COLOR_DESCRIPTIONS: Record = { + 'text.primary': 'Primary text color (uses terminal default if blank)', + 'text.secondary': 'Secondary/dimmed text color', + 'text.link': 'Hyperlink and highlighting color', + 'text.accent': 'Accent color for emphasis', + 'text.response': + 'Color for model response text (uses terminal default if blank)', + 'background.primary': 'Main terminal background color', + 'background.message': 'Subtle background for message blocks', + 'background.input': 'Background for the input prompt', + 'background.focus': 'Background highlight for selected/focused items', + 'background.diff.added': 'Background for added lines in diffs', + 'background.diff.removed': 'Background for removed lines in diffs', + 'border.default': 'Standard border color', + 'ui.comment': 'Color for code comments and metadata', + 'ui.symbol': 'Color for technical symbols and UI icons', + 'ui.active': 'Border color for active or running elements', + 'ui.dark': 'Deeply dimmed color for subtle UI elements', + 'ui.focus': + 'Color for focused elements (e.g. selected menu items, focused borders)', + 'status.error': 'Color for error messages and critical status', + 'status.success': 'Color for success messages and positive status', + 'status.warning': 'Color for warnings and cautionary status', +}; + +interface ColorsDisplayProps { + activeTheme: Theme; +} + +/** + * Determines a contrasting text color (black or white) based on the background color's luminance. + */ +function getContrastingTextColor(hex: string): string { + if (!hex || !hex.startsWith('#') || hex.length < 7) { + // Fallback for invalid hex codes or named colors + return theme.text.primary; + } + const r = parseInt(hex.slice(1, 3), 16); + const g = parseInt(hex.slice(3, 5), 16); + const b = parseInt(hex.slice(5, 7), 16); + // Using YIQ formula to determine luminance + const yiq = (r * 299 + g * 587 + b * 114) / 1000; + return yiq >= 128 ? '#000000' : '#FFFFFF'; +} + +export const ColorsDisplay: React.FC = ({ + activeTheme, +}) => { + const semanticColors = activeTheme.semanticColors; + + const backgroundRows: BackgroundColorRow[] = []; + const standardRows: StandardColorRow[] = []; + let gradientRow: GradientColorRow | null = null; + + if (semanticColors.ui.gradient && semanticColors.ui.gradient.length > 0) { + gradientRow = { + type: 'gradient', + name: 'ui.gradient', + value: semanticColors.ui.gradient, + }; + } + + /** + * Recursively flattens the semanticColors object. + */ + const flattenColors = (obj: object, path: string = '') => { + for (const [key, value] of Object.entries(obj)) { + if (value === undefined || value === null) continue; + const newPath = path ? `${path}.${key}` : key; + + if (key === 'gradient' && Array.isArray(value)) { + // Gradient handled separately + continue; + } + + if (typeof value === 'object' && !Array.isArray(value)) { + flattenColors(value, newPath); + } else if (typeof value === 'string') { + if (newPath.startsWith('background.')) { + backgroundRows.push({ + type: 'background', + name: newPath, + value, + }); + } else { + standardRows.push({ + type: 'standard', + name: newPath, + value, + }); + } + } + } + }; + + flattenColors(semanticColors); + + // Final order: Backgrounds first, then Standards, then Gradient + const allRows: ColorRow[] = [ + ...backgroundRows, + ...standardRows, + ...(gradientRow ? [gradientRow] : []), + ]; + + return ( + + + + DEVELOPER TOOLS (Not visible to users) + + + + How do colors get applied? + + + + • Hex: Rendered exactly by modern terminals. Not + overridden by app themes. + + + • Blank: Uses your terminal's default + foreground/background. + + + • Compatibility: On older terminals, hex is + approximated to the nearest ANSI color. + + + • ANSI Names: 'red', + 'green', etc. are mapped to your terminal app's + palette. + + + + + + {/* Header */} + + + + Value + + + + + Name + + + + + {/* All Rows */} + + {allRows.map((row) => { + if (row.type === 'standard') return renderStandardRow(row); + if (row.type === 'gradient') return renderGradientRow(row); + if (row.type === 'background') return renderBackgroundRow(row); + return null; + })} + + + ); +}; + +function renderStandardRow({ name, value }: StandardColorRow) { + const isHex = value.startsWith('#'); + const displayColor = isHex ? value : theme.text.primary; + const description = COLOR_DESCRIPTIONS[name] || ''; + + return ( + + + {value || '(blank)'} + + + + {name} + + + {description} + + + + ); +} + +function renderGradientRow({ name, value }: GradientColorRow) { + const description = COLOR_DESCRIPTIONS[name] || ''; + + return ( + + + {value.map((c, i) => ( + + {c} + + ))} + + + + + {name} + + + + {description} + + + + ); +} + +function renderBackgroundRow({ name, value }: BackgroundColorRow) { + const description = COLOR_DESCRIPTIONS[name] || ''; + + return ( + + + + {value || 'default'} + + + + + {name} + + + {description} + + + + ); +} diff --git a/packages/cli/src/ui/components/Composer.test.tsx b/packages/cli/src/ui/components/Composer.test.tsx index 999b1531f9..9a6155da00 100644 --- a/packages/cli/src/ui/components/Composer.test.tsx +++ b/packages/cli/src/ui/components/Composer.test.tsx @@ -374,7 +374,7 @@ describe('Composer', () => { const uiState = createMockUIState({ streamingState: StreamingState.Responding, thought: { - subject: 'Detailed in-history thought', + subject: 'Thinking about code', 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 () => { diff --git a/packages/cli/src/ui/components/Composer.tsx b/packages/cli/src/ui/components/Composer.tsx index 51c879e772..d30f52dddf 100644 --- a/packages/cli/src/ui/components/Composer.tsx +++ b/packages/cli/src/ui/components/Composer.tsx @@ -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 } diff --git a/packages/cli/src/ui/components/ContextUsageDisplay.test.tsx b/packages/cli/src/ui/components/ContextUsageDisplay.test.tsx index bcd5fd62b5..dcb2a3eae7 100644 --- a/packages/cli/src/ui/components/ContextUsageDisplay.test.tsx +++ b/packages/cli/src/ui/components/ContextUsageDisplay.test.tsx @@ -28,7 +28,7 @@ describe('ContextUsageDisplay', () => { ); await waitUntilReady(); const output = lastFrame(); - expect(output).toContain('50% context used'); + expect(output).toContain('50% used'); unmount(); }); @@ -42,7 +42,7 @@ describe('ContextUsageDisplay', () => { ); await waitUntilReady(); const output = lastFrame(); - expect(output).toContain('0% context used'); + expect(output).toContain('0% used'); unmount(); }); @@ -72,7 +72,7 @@ describe('ContextUsageDisplay', () => { ); await waitUntilReady(); const output = lastFrame(); - expect(output).toContain('80% context used'); + expect(output).toContain('80% used'); unmount(); }); @@ -86,7 +86,7 @@ describe('ContextUsageDisplay', () => { ); await waitUntilReady(); const output = lastFrame(); - expect(output).toContain('100% context used'); + expect(output).toContain('100% used'); unmount(); }); }); diff --git a/packages/cli/src/ui/components/ContextUsageDisplay.tsx b/packages/cli/src/ui/components/ContextUsageDisplay.tsx index 66cb8ed234..3e82145dca 100644 --- a/packages/cli/src/ui/components/ContextUsageDisplay.tsx +++ b/packages/cli/src/ui/components/ContextUsageDisplay.tsx @@ -38,7 +38,7 @@ export const ContextUsageDisplay = ({ } const label = - terminalWidth < MIN_TERMINAL_WIDTH_FOR_FULL_LABEL ? '%' : '% context used'; + terminalWidth < MIN_TERMINAL_WIDTH_FOR_FULL_LABEL ? '%' : '% used'; return ( diff --git a/packages/cli/src/ui/components/DebugProfiler.tsx b/packages/cli/src/ui/components/DebugProfiler.tsx index e68b3018dd..b162373473 100644 --- a/packages/cli/src/ui/components/DebugProfiler.tsx +++ b/packages/cli/src/ui/components/DebugProfiler.tsx @@ -171,6 +171,16 @@ export const DebugProfiler = () => { appEvents.on(eventName, handler); } + // Register handlers for extension lifecycle events emitted on coreEvents + // but not part of the CoreEvent enum, to prevent false-positive idle warnings. + const extensionEvents = [ + 'extensionsStarting', + 'extensionsStopping', + ] as const; + for (const eventName of extensionEvents) { + coreEvents.on(eventName, handler); + } + return () => { stdin.off('data', handler); stdout.off('resize', handler); @@ -183,6 +193,10 @@ export const DebugProfiler = () => { appEvents.off(eventName, handler); } + for (const eventName of extensionEvents) { + coreEvents.off(eventName, handler); + } + profiler.profilersActive--; }; }, []); diff --git a/packages/cli/src/ui/components/DialogManager.tsx b/packages/cli/src/ui/components/DialogManager.tsx index c86a4ba8d3..5119c1b343 100644 --- a/packages/cli/src/ui/components/DialogManager.tsx +++ b/packages/cli/src/ui/components/DialogManager.tsx @@ -21,8 +21,7 @@ import { ProQuotaDialog } from './ProQuotaDialog.js'; import { ValidationDialog } from './ValidationDialog.js'; import { OverageMenuDialog } from './OverageMenuDialog.js'; import { EmptyWalletDialog } from './EmptyWalletDialog.js'; -import { runExitCleanup } from '../../utils/cleanup.js'; -import { RELAUNCH_EXIT_CODE } from '../../utils/processUtils.js'; +import { relaunchApp } from '../../utils/processUtils.js'; import { SessionBrowser } from './SessionBrowser.js'; import { PermissionsModifyTrustDialog } from './PermissionsModifyTrustDialog.js'; import { ModelDialog } from './ModelDialog.js'; @@ -231,10 +230,7 @@ export const DialogManager = ({ uiActions.closeSettingsDialog()} - onRestartRequest={async () => { - await runExitCleanup(); - process.exit(RELAUNCH_EXIT_CODE); - }} + onRestartRequest={relaunchApp} availableTerminalHeight={terminalHeight - staticExtraHeight} /> diff --git a/packages/cli/src/ui/components/FolderTrustDialog.test.tsx b/packages/cli/src/ui/components/FolderTrustDialog.test.tsx index bbda51d8f0..012b2aab2f 100644 --- a/packages/cli/src/ui/components/FolderTrustDialog.test.tsx +++ b/packages/cli/src/ui/components/FolderTrustDialog.test.tsx @@ -246,7 +246,9 @@ describe('FolderTrustDialog', () => { it('should call relaunchApp when isRestarting is true', async () => { vi.useFakeTimers(); - const relaunchApp = vi.spyOn(processUtils, 'relaunchApp'); + const relaunchApp = vi + .spyOn(processUtils, 'relaunchApp') + .mockResolvedValue(undefined); const { waitUntilReady, unmount } = renderWithProviders( , ); @@ -259,7 +261,9 @@ describe('FolderTrustDialog', () => { it('should not call relaunchApp if unmounted before timeout', async () => { vi.useFakeTimers(); - const relaunchApp = vi.spyOn(processUtils, 'relaunchApp'); + const relaunchApp = vi + .spyOn(processUtils, 'relaunchApp') + .mockResolvedValue(undefined); const { waitUntilReady, unmount } = renderWithProviders( , ); diff --git a/packages/cli/src/ui/components/FolderTrustDialog.tsx b/packages/cli/src/ui/components/FolderTrustDialog.tsx index 2067a5dc3a..5bb748b28f 100644 --- a/packages/cli/src/ui/components/FolderTrustDialog.tsx +++ b/packages/cli/src/ui/components/FolderTrustDialog.tsx @@ -54,9 +54,7 @@ export const FolderTrustDialog: React.FC = ({ useEffect(() => { let timer: ReturnType; if (isRestarting) { - timer = setTimeout(async () => { - await relaunchApp(); - }, 250); + timer = setTimeout(relaunchApp, 250); } return () => { if (timer) clearTimeout(timer); @@ -313,9 +311,5 @@ export const FolderTrustDialog: React.FC = ({ ); - return isAlternateBuffer ? ( - {content} - ) : ( - content - ); + return {content}; }; diff --git a/packages/cli/src/ui/components/Footer.test.tsx b/packages/cli/src/ui/components/Footer.test.tsx index 7187240249..21aa6ee5c0 100644 --- a/packages/cli/src/ui/components/Footer.test.tsx +++ b/packages/cli/src/ui/components/Footer.test.tsx @@ -4,16 +4,17 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; import { renderWithProviders } from '../../test-utils/render.js'; -import { createMockSettings } from '../../test-utils/settings.js'; import { Footer } from './Footer.js'; -import { - makeFakeConfig, - tildeifyPath, - ToolCallDecision, -} from '@google/gemini-cli-core'; -import type { SessionStatsState } from '../contexts/SessionContext.js'; +import { createMockSettings } from '../../test-utils/settings.js'; +import path from 'node:path'; + +// Normalize paths to POSIX slashes for stable cross-platform snapshots. +const normalizeFrame = (frame: string | undefined) => { + if (!frame) return frame; + return frame.replace(/\\/g, '/'); +}; let mockIsDevelopment = false; @@ -49,14 +50,18 @@ const defaultProps = { branchName: 'main', }; -const mockSessionStats: SessionStatsState = { - sessionId: 'test-session', +const mockSessionStats = { + sessionId: 'test-session-id', sessionStartTime: new Date(), - lastPromptTokenCount: 0, promptCount: 0, + lastPromptTokenCount: 150000, metrics: { - models: {}, + files: { + totalLinesAdded: 12, + totalLinesRemoved: 4, + }, tools: { + count: 0, totalCalls: 0, totalSuccess: 0, totalFail: 0, @@ -65,18 +70,39 @@ const mockSessionStats: SessionStatsState = { accept: 0, reject: 0, modify: 0, - [ToolCallDecision.AUTO_ACCEPT]: 0, + auto_accept: 0, }, byName: {}, + latency: { avg: 0, max: 0, min: 0 }, }, - files: { - totalLinesAdded: 0, - totalLinesRemoved: 0, + models: { + 'gemini-pro': { + api: { + totalRequests: 0, + totalErrors: 0, + totalLatencyMs: 0, + }, + tokens: { + input: 0, + prompt: 0, + candidates: 0, + total: 1500, + cached: 0, + thoughts: 0, + tool: 0, + }, + roles: {}, + }, }, }, }; describe('