diff --git a/.github/skills/ui-action/REFERENCE.md b/.github/skills/ui-action/REFERENCE.md new file mode 100644 index 00000000..65d4fb3e --- /dev/null +++ b/.github/skills/ui-action/REFERENCE.md @@ -0,0 +1,169 @@ +# SWTBot Probe Reference + +## Runner behavior + +`ProbeRunner` is a JUnit 4 test launched by Tycho under a real Eclipse workbench +with `useUIHarness=true` and `useUIThread=false`. It loads the JSON array from +`-Dprobe.script`, executes each `ProbeStep` through `StepExecutor`, writes result +artifacts, and fails the Maven build if any failed step has `failFast` enabled. + +Before the bot starts, the runner pre-populates configuration-scope preferences +so Quick Start, What's New, Welcome, and "Terminal Support Unavailable" dialogs +do not block normal probes. + +`screenshot` and failure screenshots capture the active workbench shell with +`java.awt.Robot`, then fall back to SWTBot's full-display capture if needed. +Screenshots are diagnostic artifacts only; JSON assertions drive pass/fail. + +## Running probes + +Default command from the repository root: + + # macOS / Linux + ./mvnw clean verify -Dprobe.script=probe-scripts/.json + # Windows (PowerShell) + .\mvnw.cmd clean verify -Dprobe.script=probe-scripts/.json + +The narrower module command is useful only after a green root build: + +```bash +./mvnw -pl com.microsoft.copilot.eclipse.swtbot.test -am -Dprobe.script=probe-scripts/.json verify +``` + +The module-only shortcut can fail dependency resolution or reuse stale bundles, +especially after source edits. If widget markers or other code changes appear to +be ignored, run the root `clean verify` command. + +Platform notes: + +- Linux headless: prefix the command with `xvfb-run -a`. +- macOS: keep `${swtbot.platformArgLine}` in + `com.microsoft.copilot.eclipse.swtbot.test/pom.xml` so the `swtbot-osx` + profile can inject `-XstartOnFirstThread`. +- macOS screenshots: the JVM needs Screen Recording permission. Blank or + wallpaper-only PNGs usually mean permission is missing. +- Do not set `-Djava.awt.headless=true`; `Robot` cannot capture screenshots in + headless AWT mode. +- Windows HiDPI: workbench shell bounds are DIP coordinates while `Robot` + expects raw pixels, so captures can clip at scaling above 100%. + +Windows stale cache recovery: + +```powershell +Remove-Item -Recurse -Force $env:USERPROFILE\.m2\repository\com\microsoft\copilot\eclipse +``` + +## Results + +Artifacts are written under +`com.microsoft.copilot.eclipse.swtbot.test/target/probe-results/`: + +```text +results.json # pass/fail summary +workspace.log # sandbox Eclipse .metadata/.log +screenshots/ + .png # from screenshot steps + FAILED-stepNN-.png # auto-captured on step failure +ui-dumps/.xml # from dumpUi steps +``` + +Quick pass/fail checks: + +```bash +jq '{passed, failed, failed_steps: [.steps[] | select(.status=="failed") | {index, action, message}]}' \ + com.microsoft.copilot.eclipse.swtbot.test/target/probe-results/results.json +``` + +```powershell +Get-Content com.microsoft.copilot.eclipse.swtbot.test/target/probe-results/results.json | + ConvertFrom-Json | Select-Object passed, failed, durationMs +``` + +Maven exit code `0` and `results.json` `.failed == 0` means pass. Otherwise, +open the failed step message, `FAILED-stepNN-*.png`, nearest `ui-dumps/*.xml`, +and `workspace.log`. Many "widget not found" failures are downstream of a +Copilot language server startup or authentication failure. + +## Authentication + +The Copilot JS agent reads its GitHub token from the host's standard Copilot +store (`%USERPROFILE%\AppData\Local\github-copilot\apps.json` on Windows; +`~/.config/github-copilot/apps.json` elsewhere). The Tycho JVM inherits it. + +- Signed-in host required for probes that exercise chat completion. +- To probe unauthenticated state, assert the "Sign in to GitHub" UI instead of + polling internal status managers. +- CI-side auth bootstrap is out of scope for this skill. + +## Actions + +Set `"failFast": false` on a step to record a failure without aborting the probe. + +| `action` | Required | Optional | Notes | +|---|---|---|---| +| `screenshot` | - | `id` | PNG of the active workbench window written to `screenshots/`. | +| `sleep` | - | `timeoutSec` default `1` | Plain `Thread.sleep`. Prefer waits over sleeps. | +| `waitForIdle` | - | - | Flushes the SWT event queue. | +| `pressKey` | `key` | `locator` | Supports `ENTER`, `RETURN`, `CR`, `ESC`, `ESCAPE`, `TAB`, `SPACE`, `BS`, `BACKSPACE`, `DELETE`. Uses SWTBot `pressShortcut`; with a text/styled-text locator it targets that widget, otherwise the active shell. | +| `showView` | `idRef` | - | Opens an Eclipse view via `IWorkbenchPage#showView`. | +| `closeView` | `idRef` | - | Hides the view if present. | +| `invokeCommand` | `idRef` | - | Runs a registered Eclipse command via `IHandlerService#executeCommand`. | +| `click` | `locator` | - | Focuses text/styled-text widgets; otherwise reflectively invokes `click()` on the matched widget. | +| `typeIn` | `locator`, `text` | - | Sets text on text/styled-text widgets. | +| `clearElement` | `locator` | - | Clears text/styled-text widgets. | +| `waitFor` | `locator` | `timeoutSec` default `30` | Polls until the locator resolves. | +| `waitForMethod` | `locator`, `method` | `timeoutSec` default `30`, `expectedValue` | Polls a no-arg getter on the located widget until it returns non-null/non-empty, or equals `expectedValue`. | +| `assertExists` | `locator` | `shouldExist` default `true` | Asserts presence or absence. | +| `dumpUi` | - | `id` | Writes shell widget hierarchy XML with class names and SWTBot widget IDs. | +| `newSession` | - | - | Copilot-specific shortcut for the `newChatSession` command. | + +## Locators + +Locators are JSON objects with a `by` discriminator. SWTBot is not XPath-based; +extend `Locator` and `StepExecutor` when the existing vocabulary is not enough. + +| `by` | Other fields | What it finds | +|---|---|---| +| `viewId` | `id` | Eclipse view by ID (`bot.viewById`). | +| `label` | `text` | First label with the given text. | +| `button` | `text` | First button with the given text. | +| `buttonWithTooltip` | `tooltip` | First button whose tooltip matches; useful for icon-only buttons like Send. | +| `text` | `index` default `0` | Nth text field. | +| `styledText` | - | First `StyledText`. | +| `tree` | `labels` array | Tree path under the active tree. | +| `cssId` | `value` | Widget whose `CssConstants.CSS_ID_KEY` data equals `value`. | +| `cssClass` | `value` | Widget whose `CssConstants.CSS_CLASS_NAME_KEY` contains `value` as a whitespace-separated token. | +| `widgetId` | `value` | Widget tagged with `setData("org.eclipse.swtbot.widget.key", value)`. Preferred for widgets you own. | +| `widgetClass` | `value` | First widget whose `getClass().getSimpleName()` equals `value`. Use only when you cannot tag the widget. | + +Stable IDs and signals currently used by probes: + +- `widgetId`: `user-turn`, `copilot-turn`, `model-picker`. +- `cssClass`: `model-info-label` appears only after a Copilot turn has completed. +- `cssId`: `chat-container`, `chat-content-wrapper`, `chat-content-viewer`, + `chat-action-bar-wrapper`, `chat-action-bar`, `chat-history-viewer`. + +## Troubleshooting + +| Symptom | Likely cause / fix | +|---|---| +| `IllegalArgumentException: Missing required field: ...` | Step JSON is missing a field required by that action. Check the action table. | +| `AssertionError: waitFor timed out: locator ...` | Widget did not appear. Add `dumpUi` before the failing step, confirm class/id, or raise `timeoutSec`. | +| `assertExists failed: ... shouldExist=true` | Locator did not match. Confirm the `by` type matches the widget family. | +| `click not supported on ` | Wrapper has no `click()` method. Use a more specific locator, such as `button` instead of `label`. | +| Tests skipped: "No probe script specified" | Pass `-Dprobe.script=probe-scripts/.json`. | +| `model-info-label` wait times out | Usually authentication or language-server startup. Inspect `workspace.log`. | +| All screenshots are blank or tiny identical PNGs | `Robot` capture failed. On macOS, grant Screen Recording permission to the JVM and re-run. | +| Widget-id markers missing from `dumpUi` | Stale bundle cache or stale module jar. Run root `./mvnw clean verify`. | + +## Extending the vocabulary + +Probe support lives in `com.microsoft.copilot.eclipse.swtbot.test/src/.../probe/`: + +- `ProbeStep.java` and `Locator.java`: JSON shape. +- `StepExecutor.java`: action dispatch, locator resolution, screenshots, dumps. +- `ProbeRunner.java`: runner loop, reporting, and workbench setup. + +Add UI-level primitives that mimic user behavior. Do not add actions that call +private production methods, reach into OSGi services, or mutate app state behind +the UI; those hide real UX bugs and break on internal refactors. diff --git a/.github/skills/ui-action/SKILL.md b/.github/skills/ui-action/SKILL.md index a586d100..5b4740cc 100644 --- a/.github/skills/ui-action/SKILL.md +++ b/.github/skills/ui-action/SKILL.md @@ -1,19 +1,18 @@ --- name: ui-action -description: Write or update a SWTBot JSON probe script (e.g. from a test plan), then validate it locally by running the `ProbeRunner` Tycho test against the Copilot for Eclipse plugin. Use this whenever you need end-to-end UI validation against a real Eclipse workbench. +description: Authors and validates SWTBot JSON probe scripts for GitHub Copilot for Eclipse UI flows against a real Eclipse workbench. Use when creating or updating probe-scripts, converting test plans to UI probes, validating end-to-end Eclipse UI behavior, or troubleshooting ProbeRunner failures. --- -# Authoring and Validating SWTBot Probe Scripts (Eclipse) +# SWTBot Probe Scripts -Use this skill to write or update a JSON probe script and validate it by -invoking the `com.microsoft.copilot.eclipse.swtbot.test` Tycho bundle locally. -Probe scripts are JSON, so no Java is compiled per test case. +Use this skill to create or update JSON probes for `com.microsoft.copilot.eclipse.swtbot.test`. +Probes drive the workbench through SWTBot actions and run as Tycho tests; no Java is compiled per test case. ## Quick start -1. Drop a probe at `com.microsoft.copilot.eclipse.swtbot.test/probe-scripts/-.json` - (e.g. `chat-send-receive-001.json`). Start every probe with this preamble that - settles the workbench and opens the Copilot Chat view: +1. Create one focused JSON script at + `com.microsoft.copilot.eclipse.swtbot.test/probe-scripts/-.json`. +2. Start by settling the workbench and opening the view under test: ```json [ @@ -25,275 +24,63 @@ Probe scripts are JSON, so no Java is compiled per test case. ] ``` -2. Run it (cross-platform command; use `./mvnw` on macOS/Linux): +3. Add user-level steps only, such as `click`, `typeIn`, `clearElement`, `pressKey`, + `invokeCommand`, `waitFor`, `waitForMethod`, `assertExists`, `screenshot`, or + `dumpUi`. Prefer `widgetId` locators for widgets the plugin owns. +4. Run from the repository root: - ```powershell + ```bash ./mvnw clean verify -Dprobe.script=probe-scripts/.json ``` - Root `clean verify` is the recommended default. Tycho prefers each - bundle's freshly-packaged jar in `/target/` and silently falls - back to the stale Maven cache if the jar is missing — making `setData` - markers and other source edits appear to be ignored. + Use root `clean verify` as the default. Tycho can reuse stale bundle jars + when only the SWTBot module is run, making source edits appear ignored. Use + `xvfb-run -a` on Linux headless. +5. Read `com.microsoft.copilot.eclipse.swtbot.test/target/probe-results/results.json`, + `workspace.log`, `screenshots/`, and `ui-dumps/`. - The narrower `./mvnw -pl com.microsoft.copilot.eclipse.swtbot.test -am - -Dprobe.script=... verify` shortcut is **experimental**: in practice - it can fail dependency resolution (observed: `Missing requirement: - com.microsoft.copilot.eclipse.core 0.0.0`, with Tycho choosing the - wrong `osgi.arch` on aarch64). Use only as a follow-up, after a green - root `clean verify`. +If `-Dprobe.script` is unset, `ProbeRunner` skips itself so ordinary `./mvnw verify` runs are unaffected. -3. Read results under `com.microsoft.copilot.eclipse.swtbot.test/target/probe-results/`: +## Authoring workflow - ``` - results.json # pass/fail summary - workspace.log # sandbox Eclipse .metadata/.log - screenshots/ - .png # from `screenshot` steps - FAILED-stepNN-.png # auto-captured on step failure - ui-dumps/.xml # from `dumpUi` steps - ``` - -If `-Dprobe.script` is unset the test is skipped, so ordinary `./mvnw verify` -runs are unaffected. - -> **Linux headless:** prefix with `xvfb-run -a`. **macOS:** the swtbot test -> pom carries a `swtbot-osx` profile that injects `-XstartOnFirstThread` -> into the test JVM via the `swtbot.platformArgLine` placeholder -> interpolated into ``. If you ever edit -> `com.microsoft.copilot.eclipse.swtbot.test/pom.xml`, **keep the -> `${swtbot.platformArgLine}` token in ``** — replacing it with a -> plain literal silently drops the macOS arg and the workbench fails with -> `SWTException: Invalid thread access`. **Stale cache recovery:** -> `Remove-Item -Recurse -Force $env:USERPROFILE\.m2\repository\com\microsoft\copilot\eclipse` -> then re-run `clean verify`. - -## How the runner works - -`ProbeRunner` is a JUnit 4 test Tycho launches under a real Eclipse workbench -(`useUIHarness=true`, `useUIThread=false`). It: - -1. Loads the JSON probe pointed at by `-Dprobe.script`. -2. Walks each step via `SWTWorkbenchBot`, wrapping every step in a uniform - try/catch so one failure doesn't crash the run. -3. Writes `results.json`, screenshots (PNG — `SWTBotPreferences.SCREENSHOT_FORMAT` - is pinned), and widget-tree dumps. -4. Fails the Maven build if any `failFast` step failed. - -Before the bot starts, the runner pre-populates configuration-scope -preferences so Quick Start, What's New, Welcome, and "Terminal Support -Unavailable" dialogs don't pop during a probe — probes see a clean workbench. - -`screenshot` and `dumpUi` capture from the **on-screen workbench shell**: -`StepExecutor#captureWorkbenchShell` resolves the active workbench -`Shell`'s bounds, then snapshots those screen pixels with -`java.awt.Robot.createScreenCapture` (with SWTBot's full-display -`bot.captureScreenshot` as a final fallback). SWT's own GC-based capture -(`new GC(display).copyArea(...)` and `Shell#print(GC)`) returns blank -images on macOS Cocoa for workbench shells — Robot is the workaround. -Caveats: - -- **macOS:** the JVM running the tests needs **Screen Recording** - permission (System Settings → Privacy & Security → Screen Recording). - Without it Robot returns blank or wallpaper-only frames. -- **Headless AWT:** `-Djava.awt.headless=true` makes `new Robot()` throw, - and the SWTBot fallback is also blank on Cocoa. Don't set it. -- **Windows HiDPI:** `Shell#getBounds()` returns DIP coordinates; Robot - expects raw screen pixels. At display scaling > 100% the captured - region is undersized / clipped. (At 100% — typical CI runners — it's - a pixel-perfect match.) - -## Authoring rules - -### Drive the UI, don't reach into services - -Probes **must** interact with the workbench the way a user does — SWTBot -clicks, typing, menu navigation, keyboard shortcuts, or `invokeCommand` -against a registered Eclipse command id (the same `IHandlerService#executeCommand` -path that menus and key bindings trigger — useful when an entry point is -buried in a popup like the Copilot status-bar menu, which is awkward to -drive with SWTBot). Do not add actions that reflectively invoke private -methods, call OSGi services to flip state, or read private fields; those -hide real UX bugs and break on every internal refactor. If a scenario needs -a new primitive (e.g. a chat-mode dropdown picker), extend the -action/locator vocabulary in `StepExecutor` with a UI-level primitive, -not a service shortcut. +- Convert one scenario/test case into one probe. Split unrelated behaviors so each failure screenshot has one meaning. +- Drive the UI the way a user does. `invokeCommand` is allowed for registered Eclipse command IDs; do not call + OSGi services, private methods, or test-only shortcuts. +- Pair screenshots with machine-checked assertions. Screenshots never fail a step; `assertExists`, `waitFor`, and + `waitForMethod` decide pass/fail. +- Wait for asynchronous UI state before acting. For chat, wait for the `model-picker` selected model before Send, + then wait for `user-turn` and `model-info-label`. +- When a locator fails, insert `dumpUi` before the failure and inspect `ui-dumps/*.xml` for widget class names and + SWTBot widget IDs. +- For unauthenticated chat probes, assert the "Sign in to GitHub" UI. Do not poll internal auth managers. -### Tag widgets for `widgetId` locators - -SWTBot's blessed identification convention is -`widget.setData("org.eclipse.swtbot.widget.key", "")` at widget -construction, located from tests with the `widgetId` locator. Zero runtime -cost, far more robust than class-name or creation-order lookup. Prefer -`widgetId` over `widgetClass` whenever you control the widget's construction; -use `widgetClass` only for platform / third-party widgets you can't tag. - -Current tags: `user-turn` (`UserTurnWidget`), `copilot-turn` -(`CopilotTurnWidget`), `model-picker` (chat-model `DropdownButton`). - -### Screenshots are artifacts; assertions catch regressions - -`screenshot` never fails a step. Validation has two layers: - -- **Structural** (machine-checked): `assertExists`, `waitFor`, specific - locators. These failures land in `results.json` and drive the build exit - code — the agent judges pass/fail from here. -- **Visual** (agent-checked): after the run, open the PNGs under - `screenshots/` with your vision tool and describe what you see. No - baseline-image comparison in JSON (cross-platform font rendering makes - pixel diffs flaky). - -Pair screenshots with assertions around every non-trivial interaction: +## Chat send skeleton ```json -{ "action": "screenshot", "id": "before-send" }, -{ "action": "click", "locator": { "by": "buttonWithTooltip", "tooltip": "Send" } }, -{ "action": "waitForIdle" }, -{ "action": "assertExists", "locator": { "by": "widgetId", "value": "user-turn" } }, -{ "action": "screenshot", "id": "after-send" } +[ + { "action": "waitForIdle" }, + { "action": "showView", "idRef": "com.microsoft.copilot.eclipse.ui.chat.ChatView" }, + { "action": "waitFor", "locator": { "by": "styledText" }, "timeoutSec": 30 }, + { "action": "clearElement", "locator": { "by": "styledText" } }, + { "action": "typeIn", "locator": { "by": "styledText" }, "text": "hello" }, + { "action": "waitForMethod", "locator": { "by": "widgetId", "value": "model-picker" }, + "method": "getSelectedItemId", "timeoutSec": 60 }, + { "action": "click", "locator": { "by": "buttonWithTooltip", "tooltip": "Send" } }, + { "action": "waitFor", "locator": { "by": "widgetId", "value": "user-turn" }, "timeoutSec": 30 }, + { "action": "waitFor", "locator": { "by": "cssClass", "value": "model-info-label" }, "timeoutSec": 120 }, + { "action": "assertExists", "locator": { "by": "widgetId", "value": "copilot-turn" } }, + { "action": "screenshot", "id": "agent-response" } +] ``` -When a locator is wrong, insert a `dumpUi` step and inspect -`ui-dumps/*.xml` to find the real widget class / id. - -### Authentication prerequisite - -The Copilot JS agent reads its GitHub token from the host's standard Copilot -store (`%USERPROFILE%\AppData\Local\github-copilot\apps.json` on Windows; -`~/.config/github-copilot/apps.json` elsewhere) — the Tycho JVM inherits it. - -- **Signed-in host required** for any probe that exercises chat. Sign in via - any Copilot client (Eclipse plugin, VS Code, `gh auth login`). -- **Probing unauthed state:** assert on the "Sign in to GitHub" button that - replaces the chat input; don't poll internal status managers. -- CI-side auth bootstrap is out of scope for this skill. - -## Reading results & interpreting failures - -Maven exit code `0` **and** `results.json` `.failed == 0` → overall pass. -Otherwise open the failed step's `message`, its `FAILED-stepNN-*.png`, the -nearest `ui-dumps/*.xml`, **and** `workspace.log` — many "widget not found" -failures are downstream of a Copilot LS that never started or authenticated. -Look for `!ENTRY com.microsoft.copilot.eclipse` entries and NPEs on -`CopilotLanguageServer.*`. - -| Symptom | What's wrong / fix | -|---|---| -| `IllegalArgumentException: Missing required field: …` | Step JSON missing a field required by that action (see action table). | -| `AssertionError: waitFor timed out: locator …` | Widget not appearing. Add a `dumpUi` before the failing step, check class/id, or raise `timeoutSec`. | -| `assertExists failed: … shouldExist=true` | Locator didn't match. Confirm `by` matches the widget family. | -| `click not supported on ` | Wrapper has no `click()`; use the right `by` (e.g. `button`, not `label`). | -| Tests skipped: "No probe script specified" | Pass `-Dprobe.script=probe-scripts/.json`. | -| `model-info-label` wait times out | Usually auth; open `workspace.log`. | -| All screenshots are blank / identical ~4KB PNGs across every step | Robot capture failed. macOS: grant Screen Recording permission to the JVM and re-run. Verify by file size — real workbench frames are 50KB+; a uniform 4KB family means the on-screen capture path didn't run or returned empty pixels. | -| Widget-id markers missing from `dumpUi` | Stale Maven cache — run full `clean verify` (see Quick start). | - -Quick pass/fail check: - -```powershell -Get-Content com.microsoft.copilot.eclipse.swtbot.test/target/probe-results/results.json | - ConvertFrom-Json | Select-Object passed, failed, durationMs -``` - -```bash -jq '{passed, failed, failed_steps: [.steps[] | select(.status=="failed") | {index, action, message}]}' \ - com.microsoft.copilot.eclipse.swtbot.test/target/probe-results/results.json -``` - -## Action reference - -Set `"failFast": false` on a step to record a failure without aborting the probe. - -| `action` | Required | Optional | Notes | -|---|---|---|---| -| `screenshot` | — | `id` | PNG of the active workbench window written to `screenshots/`. | -| `sleep` | — | `timeoutSec` (default 1) | Plain `Thread.sleep`. | -| `waitForIdle` | — | — | Flushes the SWT event queue. | -| `pressKey` | `key` | `locator` | Accepts `ENTER`/`CR`, `ESC`/`ESCAPE`, `TAB`, `SPACE`, `BS`/`BACKSPACE`, `DELETE`. Without `locator`, presses on the active shell; with a `locator` targeting a text / styledText widget, sends the key directly (needed for chat input ENTER-to-send). | -| `showView` | `idRef` (Eclipse view id) | — | Opens via `IWorkbenchPage#showView`. | -| `closeView` | `idRef` | — | Hides the view if present. | -| `invokeCommand` | `idRef` (command id) | — | Runs via `IHandlerService#executeCommand`. | -| `click` | `locator` | — | Reflective `click()` on matched widget. | -| `typeIn` | `locator`, `text` | — | Works on text / styled-text widgets. | -| `clearElement` | `locator` | — | Sets text to empty. | -| `waitFor` | `locator` | `timeoutSec` (default 30) | Polls until locator resolves. | -| `waitForMethod` | `locator`, `method` | `timeoutSec` (default 30), `expectedValue` | Polls until a no-arg getter on the located widget returns non-null (and non-empty for `String`), or — if `expectedValue` is set — until `toString()` equals it. Invoked reflectively via the class hierarchy. Use for UI-exposed state not reachable via finders, e.g. `DropdownButton.getSelectedItemId()`. | -| `assertExists` | `locator` | `shouldExist` (default true) | Asserts presence / absence. | -| `dumpUi` | — | `id` | Writes widget hierarchy XML. | -| `newSession` | — | — | Copilot-specific: triggers `newChatSession` command. | - -## Locator reference - -Locators are JSON objects with a `by` discriminator. SWTBot is **not -XPath-based** — stick to this vocabulary; extend `Locator` / `StepExecutor` -if you need a new finder. - -| `by` | Other fields | What it finds | -|---|---|---| -| `viewId` | `id` | Eclipse view by id (`bot.viewById`). | -| `label` | `text` | First label with the given text. | -| `button` | `text` | First button with the given text. | -| `buttonWithTooltip` | `tooltip` | First button whose tooltip matches (use for icon-only buttons like **Send**). | -| `text` | `index` (default 0) | Nth text field. | -| `styledText` | — | First StyledText (editors / chat input). | -| `tree` | `labels` (array) | Tree path under the active tree. | -| `cssId` | `value` | Widget whose `CssConstants.CSS_ID_KEY` equals `value` (e.g. `chat-content-viewer`, `chat-action-bar`). Walks the full shell tree. | -| `cssClass` | `value` | Widget whose `CssConstants.CSS_CLASS_NAME_KEY` contains `value` as a token. `model-info-label` is only set on a **completed** Copilot turn, so waiting on it is a reliable "response received" signal. | -| `widgetId` | `value` | Widget tagged with `setData("org.eclipse.swtbot.widget.key", value)`. **Preferred** identifier for widgets you own. | -| `widgetClass` | `value` | First widget whose `getClass().getSimpleName()` equals `value` (walks the full shell tree). Fallback for widgets you can't tag. | - -## Canonical example: send a prompt and verify a response - -```json -{ "action": "clearElement", "locator": { "by": "styledText" } }, -{ "action": "typeIn", "locator": { "by": "styledText" }, "text": "your prompt" }, -{ "action": "screenshot", "id": "typed" }, - -{ "action": "waitForMethod", - "locator": { "by": "widgetId", "value": "model-picker" }, - "method": "getSelectedItemId", - "timeoutSec": 60 }, - -{ "action": "click", "locator": { "by": "buttonWithTooltip", "tooltip": "Send" } }, - -{ "action": "waitFor", "locator": { "by": "widgetId", "value": "user-turn" }, - "timeoutSec": 30 }, -{ "action": "assertExists", "locator": { "by": "widgetId", "value": "user-turn" } }, - -{ "action": "waitFor", "locator": { "by": "cssClass", "value": "model-info-label" }, - "timeoutSec": 120 }, -{ "action": "screenshot", "id": "agent-response" }, -{ "action": "assertExists", "locator": { "by": "widgetId", "value": "copilot-turn" } } -``` - -Key signals: - -- `model-picker.getSelectedItemId()` non-null — the workbench has resolved an - active chat model. Sending before this NPEs in `onSendInternal` with - "activeModel is null" because auth + model fetch complete asynchronously. -- `user-turn` — the user turn has rendered (Send button dispatched the prompt). -- `model-info-label` — only appears once a Copilot turn has **completed** - (rendered in the turn's footer at end of streaming); the reliable "response - fully received" signal. -- `copilot-turn` — the assistant turn container; good secondary assertion. - -Without a signed-in host the language server can't complete a turn, so -`model-info-label` never appears and the step times out — itself a useful -diagnostic (check `workspace.log`). - -## Extending the vocabulary - -Everything the probe understands lives in -`com.microsoft.copilot.eclipse.swtbot.test/src/.../probe/`: +## Pass/fail judgment -- `ProbeStep.java` / `Locator.java` — JSON shape. -- `StepExecutor.java` — action dispatch + locator resolution. -- `ProbeRunner.java` — runner loop, reporting, screenshots. +A probe passes only when Maven exits `0` and `results.json` has `"failed": 0`. +On failure, inspect the failed step message, `FAILED-stepNN-*.png`, nearest `ui-dumps/*.xml`, and `workspace.log`. -Add a case to the `switch` in `StepExecutor#execute` (or `resolve`) and the new -action is usable from every probe. +## Extending probes -### Keep one probe focused +The vocabulary lives in `com.microsoft.copilot.eclipse.swtbot.test/src/.../probe/`. +Add UI-level primitives in `ProbeStep`, `Locator`, and `StepExecutor`, then update [REFERENCE.md](REFERENCE.md). -Each JSON script represents one test case. Split unrelated behaviours into -separate probes so a single `FAILED-step…` screenshot tells you what broke. \ No newline at end of file +See [REFERENCE.md](REFERENCE.md) for action/locator tables, platform notes, result queries, troubleshooting, and current stable widget IDs. diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a08dc11..bdd3076e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,41 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## 0.20.0 +### Added +- Support organization-enabled custom (BYOK) models automatically in the model picker. [PR#333](https://github.com/microsoft/copilot-for-eclipse/pull/333) + +### Changed +- Move Copilot Menu to the left of the Help menu. [#287](https://github.com/microsoft/copilot-for-eclipse/issues/287) + +### Fixed +- Chat cannot be scrolled down to see the newest messages in long conversations. [#63](https://github.com/microsoft/copilot-for-eclipse/issues/63) +- Copilot asks read permission for a global skill file. [#318](https://github.com/microsoft/copilot-for-eclipse/issues/318) +- Detailed model information on dropdown hover is cropped on Linux. [#113](https://github.com/microsoft/copilot-for-eclipse/issues/113), contributed by [@travkin79](https://github.com/travkin79) +- Automatically scroll the chat view to prompts requiring user action (e.g. "Continue") in Agent mode. [#120](https://github.com/microsoft/copilot-for-eclipse/issues/120), contributed by [@raghucssit](https://github.com/raghucssit) +- Agents become extremely slow due to expensive chat view re-layout on every streamed chunk. [#259](https://github.com/microsoft/copilot-for-eclipse/issues/259) +- UI freezes on editor switch when the Chat view has a long conversation. [#335](https://github.com/microsoft/copilot-for-eclipse/issues/335) + +## 0.19.0 +### Added +- Improve terminal command execution across Windows and Linux. [PR#247](https://github.com/microsoft/copilot-for-eclipse/pull/247) +- Support editing/creating local files outside the workspace. [PR#248](https://github.com/microsoft/copilot-for-eclipse/pull/248) +- Support automatic chat context compression. [PR#250](https://github.com/microsoft/copilot-for-eclipse/pull/250) +- Support tool auto-approve controls. [PR#255](https://github.com/microsoft/copilot-for-eclipse/pull/255) + +### Fixed +- Copilot reports failure when extension-point contributed MCP server has changed. [#153](https://github.com/microsoft/copilot-for-eclipse/issues/153) +- Subagent panel size is not updated if conversation is canceled. [#169](https://github.com/microsoft/copilot-for-eclipse/issues/169), contributed by [@rsd-darshan](https://github.com/rsd-darshan) +- Thinking effort descriptions are truncated in the model picker hover card. [#233](https://github.com/microsoft/copilot-for-eclipse/issues/233) +- Canceled terminal tool calling status will become ongoing again after chat history restoration. [#239](https://github.com/microsoft/copilot-for-eclipse/issues/239) +- Cannot navigate to the file out of workspace. [#262](https://github.com/microsoft/copilot-for-eclipse/issues/262) +- Read the default text editor preferences from platform instead of defaulting to spaces. [PR#267](https://github.com/microsoft/copilot-for-eclipse/pull/267), contributed by [@jomillerOpen](https://github.com/jomillerOpen) + +### Engineering +- Remove unused message keys and properties across various modules. [PR#208](https://github.com/microsoft/copilot-for-eclipse/pull/208) +- Add endgame skill. [PR#230](https://github.com/microsoft/copilot-for-eclipse/pull/230) +- Fix typo in README upgrade recommendation. [PR#251](https://github.com/microsoft/copilot-for-eclipse/pull/251), contributed by [@evanclan](https://github.com/evanclan) + ## 0.18.0 ### Added - ℹ️ Prepare for the [upcoming usage-based billing](https://github.blog/news-insights/company-news/github-copilot-is-moving-to-usage-based-billing/). We strongly recommend upgrading to this version as soon as possible. [#203](https://github.com/microsoft/copilot-for-eclipse/issues/203) diff --git a/com.microsoft.copilot.eclipse.branding/META-INF/MANIFEST.MF b/com.microsoft.copilot.eclipse.branding/META-INF/MANIFEST.MF index 16926659..7a539765 100644 --- a/com.microsoft.copilot.eclipse.branding/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.branding/META-INF/MANIFEST.MF @@ -2,6 +2,6 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: GitHub Copilot Bundle-SymbolicName: com.microsoft.copilot.eclipse.branding;singleton:=true -Bundle-Version: 0.18.0.qualifier +Bundle-Version: 0.20.0.qualifier Bundle-Vendor: GitHub Copilot Automatic-Module-Name: com.microsoft.copilot.eclipse.branding diff --git a/com.microsoft.copilot.eclipse.core.agent.linux.aarch64/META-INF/MANIFEST.MF b/com.microsoft.copilot.eclipse.core.agent.linux.aarch64/META-INF/MANIFEST.MF index 919f4b2b..e13e44f3 100644 --- a/com.microsoft.copilot.eclipse.core.agent.linux.aarch64/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.core.agent.linux.aarch64/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Bundle-ManifestVersion: 2 Bundle-Name: com.microsoft.copilot.eclipse.core.agent.linux.aarch64 Bundle-SymbolicName: com.microsoft.copilot.eclipse.core.agent.linux.aarch64 Automatic-Module-Name: com.microsoft.copilot.eclipse.core.agent.linux.aarch64 -Bundle-Version: 0.18.0.qualifier +Bundle-Version: 0.20.0.qualifier Bundle-Vendor: GitHub Copilot Fragment-Host: com.microsoft.copilot.eclipse.core Bundle-RequiredExecutionEnvironment: JavaSE-17 diff --git a/com.microsoft.copilot.eclipse.core.agent.linux.x64/META-INF/MANIFEST.MF b/com.microsoft.copilot.eclipse.core.agent.linux.x64/META-INF/MANIFEST.MF index d0590971..b8a762ac 100644 --- a/com.microsoft.copilot.eclipse.core.agent.linux.x64/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.core.agent.linux.x64/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Bundle-ManifestVersion: 2 Bundle-Name: com.microsoft.copilot.eclipse.core.agent.linux.x64 Bundle-SymbolicName: com.microsoft.copilot.eclipse.core.agent.linux.x64 Automatic-Module-Name: com.microsoft.copilot.eclipse.core.agent.linux.x64 -Bundle-Version: 0.18.0.qualifier +Bundle-Version: 0.20.0.qualifier Bundle-Vendor: GitHub Copilot Fragment-Host: com.microsoft.copilot.eclipse.core Bundle-RequiredExecutionEnvironment: JavaSE-17 diff --git a/com.microsoft.copilot.eclipse.core.agent.macosx.aarch64/META-INF/MANIFEST.MF b/com.microsoft.copilot.eclipse.core.agent.macosx.aarch64/META-INF/MANIFEST.MF index 14320936..d2a33578 100644 --- a/com.microsoft.copilot.eclipse.core.agent.macosx.aarch64/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.core.agent.macosx.aarch64/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Bundle-ManifestVersion: 2 Bundle-Name: com.microsoft.copilot.eclipse.core.agent.macosx.aarch64 Bundle-SymbolicName: com.microsoft.copilot.eclipse.core.agent.macosx.aarch64 Automatic-Module-Name: com.microsoft.copilot.eclipse.core.agent.macosx.aarch64 -Bundle-Version: 0.18.0.qualifier +Bundle-Version: 0.20.0.qualifier Bundle-Vendor: GitHub Copilot Fragment-Host: com.microsoft.copilot.eclipse.core Bundle-RequiredExecutionEnvironment: JavaSE-17 diff --git a/com.microsoft.copilot.eclipse.core.agent.macosx.x64/META-INF/MANIFEST.MF b/com.microsoft.copilot.eclipse.core.agent.macosx.x64/META-INF/MANIFEST.MF index 1b554a64..a6a5e998 100644 --- a/com.microsoft.copilot.eclipse.core.agent.macosx.x64/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.core.agent.macosx.x64/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Bundle-ManifestVersion: 2 Bundle-Name: com.microsoft.copilot.eclipse.core.agent.macosx.x64 Bundle-SymbolicName: com.microsoft.copilot.eclipse.core.agent.macosx.x64 Automatic-Module-Name: com.microsoft.copilot.eclipse.core.agent.macosx.x64 -Bundle-Version: 0.18.0.qualifier +Bundle-Version: 0.20.0.qualifier Bundle-Vendor: GitHub Copilot Fragment-Host: com.microsoft.copilot.eclipse.core Bundle-RequiredExecutionEnvironment: JavaSE-17 diff --git a/com.microsoft.copilot.eclipse.core.agent.win32/META-INF/MANIFEST.MF b/com.microsoft.copilot.eclipse.core.agent.win32/META-INF/MANIFEST.MF index 69cc83a5..b9c752e5 100644 --- a/com.microsoft.copilot.eclipse.core.agent.win32/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.core.agent.win32/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Bundle-ManifestVersion: 2 Bundle-Name: com.microsoft.copilot.eclipse.core.agent.win32 Bundle-SymbolicName: com.microsoft.copilot.eclipse.core.agent.win32 Automatic-Module-Name: com.microsoft.copilot.eclipse.core.agent.win32 -Bundle-Version: 0.18.0.qualifier +Bundle-Version: 0.20.0.qualifier Bundle-Vendor: GitHub Copilot Fragment-Host: com.microsoft.copilot.eclipse.core Bundle-RequiredExecutionEnvironment: JavaSE-17 diff --git a/com.microsoft.copilot.eclipse.core.test/META-INF/MANIFEST.MF b/com.microsoft.copilot.eclipse.core.test/META-INF/MANIFEST.MF index 583fef61..efcd8dba 100644 --- a/com.microsoft.copilot.eclipse.core.test/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.core.test/META-INF/MANIFEST.MF @@ -2,14 +2,14 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: com.microsoft.copilot.eclipse.core.test Bundle-SymbolicName: com.microsoft.copilot.eclipse.core.test;singleton:=true -Bundle-Version: 0.18.0.qualifier +Bundle-Version: 0.20.0.qualifier Bundle-Vendor: GitHub Copilot Bundle-RequiredExecutionEnvironment: JavaSE-17 Fragment-Host: com.microsoft.copilot.eclipse.core Automatic-Module-Name: com.microsoft.copilot.eclipse.core.test Import-Package: org.objenesis;version="[3.4.0,4.0.0)", org.osgi.framework;version="[1.10.0,2.0.0)" -Require-Bundle: com.microsoft.copilot.eclipse.core;bundle-version="0.15.0", +Require-Bundle: com.microsoft.copilot.eclipse.core;bundle-version="0.20.0", org.mockito.mockito-core;bundle-version="5.14.2", org.eclipse.lsp4e;bundle-version="0.18.1", org.eclipse.jdt.annotation;resolution:=optional, diff --git a/com.microsoft.copilot.eclipse.core.test/pom.xml b/com.microsoft.copilot.eclipse.core.test/pom.xml index 3231acca..dcc3fca9 100644 --- a/com.microsoft.copilot.eclipse.core.test/pom.xml +++ b/com.microsoft.copilot.eclipse.core.test/pom.xml @@ -14,4 +14,27 @@ true - \ No newline at end of file + + + + skip-tests-during-ui-probe + + + probe.script + + + + + + org.eclipse.tycho + tycho-surefire-plugin + ${tycho-version} + + true + + + + + + + diff --git a/com.microsoft.copilot.eclipse.core.test/src/com/microsoft/copilot/eclipse/core/completion/FormatOptionProviderTests.java b/com.microsoft.copilot.eclipse.core.test/src/com/microsoft/copilot/eclipse/core/completion/FormatOptionProviderTests.java index c87449dc..eeeb756d 100644 --- a/com.microsoft.copilot.eclipse.core.test/src/com/microsoft/copilot/eclipse/core/completion/FormatOptionProviderTests.java +++ b/com.microsoft.copilot.eclipse.core.test/src/com/microsoft/copilot/eclipse/core/completion/FormatOptionProviderTests.java @@ -10,10 +10,15 @@ import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.preferences.IEclipsePreferences; +import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.lsp4j.FormattingOptions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.junit.jupiter.MockitoExtension; import com.microsoft.copilot.eclipse.core.format.FormatOptionProvider; @@ -25,7 +30,9 @@ class FormatOptionProviderTests { private IFile mockFile; private IProject mockProject; - private static final int PREFERENCE_DEFAULT_TAB_SIZE = 4; + private static final String EDITOR_PREF_NODE = "org.eclipse.ui.editors"; + private static final String TAB_WIDTH_KEY = "tabWidth"; + private static final String SPACES_FOR_TABS_KEY = "spacesForTabs"; @BeforeEach void setUp() { @@ -52,20 +59,20 @@ void testGetEclipseDefaultJavaTabCharAndSize() { assertEquals(tabSize, formatOptionProvider.getTabSize(mockFile)); } - @Test - void testGetCopilotDefaultTabCharAndSizeForUnknownLanguage() { - when(mockFile.getFileExtension()).thenReturn("js"); - - assertTrue(formatOptionProvider.useSpace(mockFile)); - assertEquals(PREFERENCE_DEFAULT_TAB_SIZE, formatOptionProvider.getTabSize(mockFile)); - } + @ParameterizedTest @NullSource @ValueSource(strings = { "js" }) + void testUsesEclipseTextEditorFormattingOptionsForUnknownOrNoExtension(String extension) { + when(mockFile.getFileExtension()).thenReturn(extension); - @Test - void testGetCopilotDefaultTabCharAndSizeForNoExtensionFile() { - when(mockFile.getFileExtension()).thenReturn(null); + // Set the Eclipse preferences to be something other than the default (false, 4) + setEditorFormattingPreferences(true, 2); assertTrue(formatOptionProvider.useSpace(mockFile)); - assertEquals(PREFERENCE_DEFAULT_TAB_SIZE, formatOptionProvider.getTabSize(mockFile)); + assertEquals(2, formatOptionProvider.getTabSize(mockFile)); } + private void setEditorFormattingPreferences(boolean useSpaces, int tabSize) { + IEclipsePreferences prefs = InstanceScope.INSTANCE.getNode(EDITOR_PREF_NODE); + prefs.putBoolean(SPACES_FOR_TABS_KEY, useSpaces); + prefs.putInt(TAB_WIDTH_KEY, tabSize); + } } diff --git a/com.microsoft.copilot.eclipse.core.test/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CopilotModelTests.java b/com.microsoft.copilot.eclipse.core.test/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CopilotModelTests.java new file mode 100644 index 00000000..37f7b85d --- /dev/null +++ b/com.microsoft.copilot.eclipse.core.test/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CopilotModelTests.java @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.lsp.protocol; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +import org.junit.jupiter.api.Test; + +import com.google.gson.Gson; +import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel.CopilotModelCustomModel; + +/** + * Tests for {@link CopilotModel}, focusing on the {@code customModel} metadata that carries organization- and + * enterprise-contributed custom (BYOK) models exposed through {@code copilot/models}. + */ +class CopilotModelTests { + + private final Gson gson = new Gson(); + + @Test + void testDeserialize_populatesCustomModelMetadata() { + String json = """ + { + "modelFamily": "custom", + "modelName": "Sonnet (Org)", + "id": "claude-sonnet-org", + "scopes": ["chat-panel", "agent-panel"], + "customModel": { + "keyName": "Contoso Azure Key", + "ownerName": "Contoso", + "ownerType": "organization", + "provider": "azure" + } + } + """; + + CopilotModel model = gson.fromJson(json, CopilotModel.class); + + assertNotNull(model.getCustomModel()); + assertEquals("Contoso Azure Key", model.getCustomModel().keyName()); + assertEquals("Contoso", model.getCustomModel().ownerName()); + assertEquals("organization", model.getCustomModel().ownerType()); + assertEquals("azure", model.getCustomModel().provider()); + } + + @Test + void testDeserialize_customModelAbsentIsNull() { + String json = """ + { + "modelFamily": "gpt-4o", + "modelName": "GPT-4o", + "id": "gpt-4o", + "scopes": ["chat-panel"] + } + """; + + CopilotModel model = gson.fromJson(json, CopilotModel.class); + + assertNull(model.getCustomModel()); + } + + @Test + void testEqualsAndHashCode_accountForCustomModel() { + CopilotModel base = new CopilotModel(); + base.setId("claude-sonnet-org"); + base.setModelName("Sonnet (Org)"); + base.setCustomModel(new CopilotModelCustomModel("Contoso Azure Key", "Contoso", "organization", "azure")); + + CopilotModel same = new CopilotModel(); + same.setId("claude-sonnet-org"); + same.setModelName("Sonnet (Org)"); + same.setCustomModel(new CopilotModelCustomModel("Contoso Azure Key", "Contoso", "organization", "azure")); + + CopilotModel differentOwner = new CopilotModel(); + differentOwner.setId("claude-sonnet-org"); + differentOwner.setModelName("Sonnet (Org)"); + differentOwner.setCustomModel(new CopilotModelCustomModel("Contoso Azure Key", "Fabrikam", "organization", + "azure")); + + assertEquals(base, same); + assertEquals(base.hashCode(), same.hashCode()); + assertNotEquals(base, differentOwner); + } +} diff --git a/com.microsoft.copilot.eclipse.core.test/src/com/microsoft/copilot/eclipse/core/utils/FileUtilsTests.java b/com.microsoft.copilot.eclipse.core.test/src/com/microsoft/copilot/eclipse/core/utils/FileUtilsTests.java new file mode 100644 index 00000000..cbbf6d55 --- /dev/null +++ b/com.microsoft.copilot.eclipse.core.test/src/com/microsoft/copilot/eclipse/core/utils/FileUtilsTests.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.nio.file.Path; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class FileUtilsTests { + + @Test + void testGetLocalFilePath_absolutePath_returnsNormalizedPath(@TempDir Path tempDir) { + Path expected = tempDir.resolve("external-file.txt").toAbsolutePath().normalize(); + + assertEquals(expected, FileUtils.getLocalFilePath(expected.toString())); + } + + @Test + void testGetLocalFilePath_fileUriWithFragment_ignoresFragment(@TempDir Path tempDir) { + Path expected = tempDir.resolve("external-file.txt").toAbsolutePath().normalize(); + + assertEquals(expected, FileUtils.getLocalFilePath(expected.toUri() + "#L10")); + } + + @Test + void testGetLocalFilePath_relativePath_returnsNull() { + assertNull(FileUtils.getLocalFilePath("src/main/java/File.java")); + } + + @Test + void testGetLocalFilePath_nonFileUri_returnsNull() { + assertNull(FileUtils.getLocalFilePath("https://example.com/file.java")); + } +} diff --git a/com.microsoft.copilot.eclipse.core/META-INF/MANIFEST.MF b/com.microsoft.copilot.eclipse.core/META-INF/MANIFEST.MF index f5a193f2..9b5eb2d0 100644 --- a/com.microsoft.copilot.eclipse.core/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.core/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: com.microsoft.copilot.eclipse.core Bundle-SymbolicName: com.microsoft.copilot.eclipse.core;singleton:=true -Bundle-Version: 0.18.0.qualifier +Bundle-Version: 0.20.0.qualifier Bundle-Vendor: GitHub Copilot Export-Package: com.microsoft.copilot.eclipse.core, com.microsoft.copilot.eclipse.core.chat, diff --git a/com.microsoft.copilot.eclipse.core/copilot-agent/package-lock.json b/com.microsoft.copilot.eclipse.core/copilot-agent/package-lock.json index 07efeace..eda43152 100644 --- a/com.microsoft.copilot.eclipse.core/copilot-agent/package-lock.json +++ b/com.microsoft.copilot.eclipse.core/copilot-agent/package-lock.json @@ -9,18 +9,18 @@ "version": "0.0.1", "hasInstallScript": true, "dependencies": { - "@github/copilot-language-server": "1.488.0", - "@github/copilot-language-server-darwin-arm64": "1.488.0", - "@github/copilot-language-server-darwin-x64": "1.488.0", - "@github/copilot-language-server-linux-arm64": "1.488.0", - "@github/copilot-language-server-linux-x64": "1.488.0", - "@github/copilot-language-server-win32-x64": "1.488.0" + "@github/copilot-language-server": "1.509.5", + "@github/copilot-language-server-darwin-arm64": "1.509.5", + "@github/copilot-language-server-darwin-x64": "1.509.5", + "@github/copilot-language-server-linux-arm64": "1.509.5", + "@github/copilot-language-server-linux-x64": "1.509.5", + "@github/copilot-language-server-win32-x64": "1.509.5" } }, "node_modules/@github/copilot-language-server": { - "version": "1.488.0", - "resolved": "https://registry.npmjs.org/@github/copilot-language-server/-/copilot-language-server-1.488.0.tgz", - "integrity": "sha512-zCyItvYtqrtQzpdAv6nTjph4Nfws5xTMNAw7cn2gIvBEBHT5NbnaceSwxJm2I96Ll2Jrq4uQG+wifYVMHjQDwg==", + "version": "1.509.5", + "resolved": "https://registry.npmjs.org/@github/copilot-language-server/-/copilot-language-server-1.509.5.tgz", + "integrity": "sha512-cAZVbN5UHrm+ILqroO2NY2gbI7mYojwmiOClCWj8yPD0svXJKSVmmmDonkVrvNZ1VxW3tIbCbE1LRTL6HVN/9g==", "license": "MIT", "dependencies": { "vscode-languageserver-protocol": "^3.17.5" @@ -29,18 +29,18 @@ "copilot-language-server": "dist/language-server.js" }, "optionalDependencies": { - "@github/copilot-language-server-darwin-arm64": "1.488.0", - "@github/copilot-language-server-darwin-x64": "1.488.0", - "@github/copilot-language-server-linux-arm64": "1.488.0", - "@github/copilot-language-server-linux-x64": "1.488.0", - "@github/copilot-language-server-win32-arm64": "1.488.0", - "@github/copilot-language-server-win32-x64": "1.488.0" + "@github/copilot-language-server-darwin-arm64": "1.509.5", + "@github/copilot-language-server-darwin-x64": "1.509.5", + "@github/copilot-language-server-linux-arm64": "1.509.5", + "@github/copilot-language-server-linux-x64": "1.509.5", + "@github/copilot-language-server-win32-arm64": "1.509.5", + "@github/copilot-language-server-win32-x64": "1.509.5" } }, "node_modules/@github/copilot-language-server-darwin-arm64": { - "version": "1.488.0", - "resolved": "https://registry.npmjs.org/@github/copilot-language-server-darwin-arm64/-/copilot-language-server-darwin-arm64-1.488.0.tgz", - "integrity": "sha512-X4jqAKJwNJIM2Ua22UZvPM6/3x7ZiX4lgedvqWadoFA9SJmxF6OlQoe2L6coeC1U8RWj5WEyTqIDkyJkhsF24Q==", + "version": "1.509.5", + "resolved": "https://registry.npmjs.org/@github/copilot-language-server-darwin-arm64/-/copilot-language-server-darwin-arm64-1.509.5.tgz", + "integrity": "sha512-eGb5bHN1OVUEnQYCop1+Hd4z6CR2fZK0iqFRu0pdGeQ3/y370trt2KR+omJv354ibsCUmpDUIqZXb6hOiIZk/Q==", "cpu": [ "arm64" ], @@ -50,9 +50,9 @@ ] }, "node_modules/@github/copilot-language-server-darwin-x64": { - "version": "1.488.0", - "resolved": "https://registry.npmjs.org/@github/copilot-language-server-darwin-x64/-/copilot-language-server-darwin-x64-1.488.0.tgz", - "integrity": "sha512-JHmdBwxwfZfxWkJLNp4M2bydrkD/TsxPoPeojcIOscrHhTj2riWSe7zqUn61IAdtwG0z2HwK1tGS35KOJhW8+A==", + "version": "1.509.5", + "resolved": "https://registry.npmjs.org/@github/copilot-language-server-darwin-x64/-/copilot-language-server-darwin-x64-1.509.5.tgz", + "integrity": "sha512-EonG1QHCx7qmiPc0EsVYSk9oBeWtwHXw0h3fMFOWKN37HOKImMiDeC7JBjv1kG/q9XzHGGhkYjkvReebMKZoOg==", "cpu": [ "x64" ], @@ -62,9 +62,9 @@ ] }, "node_modules/@github/copilot-language-server-linux-arm64": { - "version": "1.488.0", - "resolved": "https://registry.npmjs.org/@github/copilot-language-server-linux-arm64/-/copilot-language-server-linux-arm64-1.488.0.tgz", - "integrity": "sha512-t+MZuQl76nMAs0qzAZDb9hr3SC53cW87CmDI+lgfLfXay8cdunNirjI/IloRnXybYYKFCkjvqDl9cYcLdCA1/g==", + "version": "1.509.5", + "resolved": "https://registry.npmjs.org/@github/copilot-language-server-linux-arm64/-/copilot-language-server-linux-arm64-1.509.5.tgz", + "integrity": "sha512-f1SYaxh8drXeZ2Sf5A/gjFC5gg0qnUdwYUWXA2vpJrMZ2bMbylacGS9hwhkwk9jDaHkeOmjOWWh+g2csdLgVTw==", "cpu": [ "arm64" ], @@ -74,9 +74,9 @@ ] }, "node_modules/@github/copilot-language-server-linux-x64": { - "version": "1.488.0", - "resolved": "https://registry.npmjs.org/@github/copilot-language-server-linux-x64/-/copilot-language-server-linux-x64-1.488.0.tgz", - "integrity": "sha512-hhJ2ZVweqLCk0lptMXyHlXPrkSiHypcpza5gVUwMGMuw7Z87o3SkK8fD5jDpBvKJ0gJTGjPZ2yXzGtErpY20Sw==", + "version": "1.509.5", + "resolved": "https://registry.npmjs.org/@github/copilot-language-server-linux-x64/-/copilot-language-server-linux-x64-1.509.5.tgz", + "integrity": "sha512-T0ihY6w2H7sdKMaF0k7pHBQV3wTj4Uzq38kx8pGKAFTupUIgivMUHOWysiLdsBgQ9rafByIMzHR3slnpYcH1SQ==", "cpu": [ "x64" ], @@ -86,9 +86,9 @@ ] }, "node_modules/@github/copilot-language-server-win32-arm64": { - "version": "1.488.0", - "resolved": "https://registry.npmjs.org/@github/copilot-language-server-win32-arm64/-/copilot-language-server-win32-arm64-1.488.0.tgz", - "integrity": "sha512-ke8czQwJcOtZpD9CnyBE7nVrFU9oa8nrLMp8xWoxKybs77Rpt36v2CGw535QHrih9f3Hp4dQtFlaRdvjnL1vZg==", + "version": "1.509.5", + "resolved": "https://registry.npmjs.org/@github/copilot-language-server-win32-arm64/-/copilot-language-server-win32-arm64-1.509.5.tgz", + "integrity": "sha512-T4fyhZIJCU+ETyp3vcIw0Y+sIvcsnq8C59s2l7RR9jX6lwHacwsU2PUcRYQqETfWOkM5YX7wzKiThLxvsOAc9g==", "cpu": [ "arm64" ], @@ -99,9 +99,9 @@ ] }, "node_modules/@github/copilot-language-server-win32-x64": { - "version": "1.488.0", - "resolved": "https://registry.npmjs.org/@github/copilot-language-server-win32-x64/-/copilot-language-server-win32-x64-1.488.0.tgz", - "integrity": "sha512-TOxA86DcpO7VYfsePj5PmbzqKaTwGXse6OBdMAPKPBBBCiusEI1kmYO3O/ywi8n5cCF1X9LvrqbunNRzokxRug==", + "version": "1.509.5", + "resolved": "https://registry.npmjs.org/@github/copilot-language-server-win32-x64/-/copilot-language-server-win32-x64-1.509.5.tgz", + "integrity": "sha512-tv12/MayELMseV7V+ghdC/AY5GgKh/lyncAU/A7eEpPt8ACNEErBZ51mriAT1F/EqSfB1iEUKVtgZ4/+eTe9Fw==", "cpu": [ "x64" ], diff --git a/com.microsoft.copilot.eclipse.core/copilot-agent/package.json b/com.microsoft.copilot.eclipse.core/copilot-agent/package.json index 06f8e77a..d6c12fb7 100644 --- a/com.microsoft.copilot.eclipse.core/copilot-agent/package.json +++ b/com.microsoft.copilot.eclipse.core/copilot-agent/package.json @@ -12,11 +12,11 @@ "postinstall": "node copy-binaries.js" }, "dependencies": { - "@github/copilot-language-server": "1.488.0", - "@github/copilot-language-server-win32-x64": "1.488.0", - "@github/copilot-language-server-darwin-x64": "1.488.0", - "@github/copilot-language-server-darwin-arm64": "1.488.0", - "@github/copilot-language-server-linux-x64": "1.488.0", - "@github/copilot-language-server-linux-arm64": "1.488.0" + "@github/copilot-language-server": "1.509.5", + "@github/copilot-language-server-win32-x64": "1.509.5", + "@github/copilot-language-server-darwin-x64": "1.509.5", + "@github/copilot-language-server-darwin-arm64": "1.509.5", + "@github/copilot-language-server-linux-x64": "1.509.5", + "@github/copilot-language-server-linux-arm64": "1.509.5" } } diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/Constants.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/Constants.java index 165d17cf..176bc245 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/Constants.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/Constants.java @@ -54,6 +54,16 @@ private Constants() { public static final String GITHUB_JOBS_VIEW_ID = "com.microsoft.copilot.eclipse.ui.jobs.JobsView"; public static final String SUPPRESS_TERMINAL_DEPENDENCY_DIALOG = "suppressTerminalDependencyDialog"; + // Auto-Approve settings + public static final String AUTO_APPROVE_TERMINAL_RULES = "autoApproveTerminalRules"; + public static final String AUTO_APPROVE_UNMATCHED_TERMINAL = "autoApproveUnmatchedTerminal"; + public static final String AUTO_APPROVE_FILE_OP_RULES = "autoApproveEditRules"; + public static final String AUTO_APPROVE_UNMATCHED_FILE_OP = "autoApproveUnmatchedFileOp"; + public static final String AUTO_APPROVE_MCP_SERVERS = "autoApproveMcpServers"; + public static final String AUTO_APPROVE_MCP_TOOLS = "autoApproveMcpTools"; + public static final String AUTO_APPROVE_TRUST_TOOL_ANNOTATIONS = "autoApproveTrustToolAnnotations"; + public static final String AUTO_APPROVE_YOLO_MODE = "autoApproveYoloMode"; + // Base excluded file types shared by both // Copied from InelliJ, excluded file extension list // https://github.com/microsoft/copilot-intellij/blob/main/core/src/main/kotlin/com/github/copilot/chat/references/FileSearchService.kt diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/FeatureFlags.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/FeatureFlags.java index 1e9a6bf0..f54e0bfa 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/FeatureFlags.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/FeatureFlags.java @@ -25,6 +25,10 @@ public class FeatureFlags { private boolean customAgentPolicyEnabled = true; + private boolean autoApprovalTokenEnabled = true; + + private boolean autoApprovalPolicyEnabled = true; + public boolean isAgentModeEnabled() { return agentModeEnabled; } @@ -84,6 +88,25 @@ public void setCustomAgentPolicyEnabled(boolean customAgentPolicyEnabled) { this.customAgentPolicyEnabled = customAgentPolicyEnabled; } + /** + * Returns true if the auto-approval feature is available. + * Requires both the server token ({@code agent_mode_auto_approval}) and + * the organization policy ({@code agentMode.autoApproval.enabled}) to permit it. + * + * @return true if auto-approval is permitted + */ + public boolean isAutoApprovalEnabled() { + return autoApprovalTokenEnabled && autoApprovalPolicyEnabled; + } + + public void setAutoApprovalTokenEnabled(boolean autoApprovalTokenEnabled) { + this.autoApprovalTokenEnabled = autoApprovalTokenEnabled; + } + + public void setAutoApprovalPolicyEnabled(boolean autoApprovalPolicyEnabled) { + this.autoApprovalPolicyEnabled = autoApprovalPolicyEnabled; + } + public boolean isClientPreviewFeatureEnabled() { return clientPreviewFeatureEnabled; } diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/ConfirmationAction.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/ConfirmationAction.java new file mode 100644 index 00000000..07f10d92 --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/ConfirmationAction.java @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.chat; + +import java.util.Map; +import java.util.Objects; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Represents a button action in the confirmation UI. Each action has a label, + * a decision (accept or dismiss), a persistence scope, and optional metadata + * for the handler to know what to persist. + */ +public class ConfirmationAction { + + /** Metadata key for the action type enum name. */ + public static final String META_ACTION = "action"; + + private final String label; + private final boolean accept; + private final ConfirmationActionScope scope; + private final Map metadata; + private final boolean primary; + + /** + * Creates a new confirmation action. + * + * @param label the button label + * @param accept true for accept, false for dismiss + * @param scope the persistence scope (null for dismiss actions) + * @param metadata extra data for the handler (e.g., command names, server name) + * @param primary whether this is the primary/default button + */ + public ConfirmationAction(String label, boolean accept, + ConfirmationActionScope scope, Map metadata, + boolean primary) { + this.label = label; + this.accept = accept; + this.scope = scope; + this.metadata = metadata != null ? metadata : Map.of(); + this.primary = primary; + } + + public String getLabel() { + return label; + } + + public boolean isAccept() { + return accept; + } + + public ConfirmationActionScope getScope() { + return scope; + } + + public Map getMetadata() { + return metadata; + } + + public boolean isPrimary() { + return primary; + } + + /** Creates a primary accept action (scope = ONCE). */ + public static ConfirmationAction allowOnce(String label) { + return new ConfirmationAction(label, true, + ConfirmationActionScope.ONCE, null, true); + } + + /** Creates a dismiss action. */ + public static ConfirmationAction skip(String label) { + return new ConfirmationAction(label, false, null, null, false); + } + + @Override + public int hashCode() { + return Objects.hash(accept, label, metadata, primary, scope); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ConfirmationAction other = (ConfirmationAction) obj; + return accept == other.accept + && Objects.equals(label, other.label) + && Objects.equals(metadata, other.metadata) + && primary == other.primary && scope == other.scope; + } + + @Override + public String toString() { + return new ToStringBuilder(this) + .append("label", label) + .append("accept", accept) + .append("scope", scope) + .append("metadata", metadata) + .append("primary", primary) + .toString(); + } +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/ConfirmationActionScope.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/ConfirmationActionScope.java new file mode 100644 index 00000000..37fc6d88 --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/ConfirmationActionScope.java @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.chat; + +/** + * Scope of how a confirmation decision should be persisted. + */ +public enum ConfirmationActionScope { + /** One-time acceptance for this single invocation. */ + ONCE, + /** Remember for the current conversation session (in-memory). */ + SESSION, + /** Remember globally (application-level persistent, synced to CLS). */ + GLOBAL +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/ConfirmationContent.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/ConfirmationContent.java new file mode 100644 index 00000000..abc588fc --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/ConfirmationContent.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.chat; + +import java.util.List; +import java.util.Objects; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Complete content for rendering a confirmation UI. Returned by handlers when a tool call + * needs user confirmation. Contains the display text and the list of action buttons. + */ +public class ConfirmationContent { + + private final String title; + private final String message; + private final List actions; + + /** + * Creates a new confirmation content. + * + * @param title bold title text displayed at the top + * @param message description text (may be null) + * @param actions list of button actions for the confirmation UI + */ + public ConfirmationContent(String title, String message, + List actions) { + this.title = title; + this.message = message; + this.actions = actions; + } + + public String getTitle() { + return title; + } + + public String getMessage() { + return message; + } + + public List getActions() { + return actions; + } + + @Override + public int hashCode() { + return Objects.hash(actions, message, title); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ConfirmationContent other = (ConfirmationContent) obj; + return Objects.equals(actions, other.actions) + && Objects.equals(message, other.message) + && Objects.equals(title, other.title); + } + + @Override + public String toString() { + return new ToStringBuilder(this) + .append("title", title) + .append("message", message) + .append("actions", actions) + .toString(); + } +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/ConfirmationHandler.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/ConfirmationHandler.java new file mode 100644 index 00000000..b8553435 --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/ConfirmationHandler.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.chat; + +import com.microsoft.copilot.eclipse.core.lsp.protocol.InvokeClientToolConfirmationParams; + +/** + * Evaluates whether a tool confirmation request can be auto-approved. + * Each implementation handles a specific category of tool (terminal, file operations, MCP, etc.). + */ +public interface ConfirmationHandler { + + /** + * Evaluates whether the given confirmation request should be auto-approved. + * + * @param params the confirmation request parameters from CLS + * @return ConfirmationResult.AUTO_APPROVED if the tool call can proceed without user + * confirmation, or ConfirmationResult.NEEDS_CONFIRMATION if the user must approve + */ + ConfirmationResult evaluate(InvokeClientToolConfirmationParams params); +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/ConfirmationResult.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/ConfirmationResult.java new file mode 100644 index 00000000..a496ab10 --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/ConfirmationResult.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.chat; + +import java.util.Objects; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Result of evaluating an auto-approve confirmation request. + * Either AUTO_APPROVED (no UI needed) or NEEDS_CONFIRMATION with content for the dialog. + */ +public class ConfirmationResult { + + /** Auto-approved, no user confirmation needed. */ + public static final ConfirmationResult AUTO_APPROVED = new ConfirmationResult(true, false, null); + + /** Dismissed — malformed or unhandleable request; CLS should be told to skip the tool. */ + public static final ConfirmationResult DISMISSED = new ConfirmationResult(false, true, null); + + private final boolean autoApproved; + private final boolean dismissed; + private final ConfirmationContent content; + + private ConfirmationResult(boolean autoApproved, boolean dismissed, ConfirmationContent content) { + this.autoApproved = autoApproved; + this.dismissed = dismissed; + this.content = content; + } + + /** Creates a result that requires user confirmation with the given content. */ + public static ConfirmationResult needsConfirmation( + ConfirmationContent content) { + return new ConfirmationResult(false, false, content); + } + + public boolean isAutoApproved() { + return autoApproved; + } + + /** Returns true if the request should be dismissed without showing UI. */ + public boolean isDismissed() { + return dismissed; + } + + /** Returns the confirmation content, or null if auto-approved or using defaults. */ + public ConfirmationContent getContent() { + return content; + } + + @Override + public int hashCode() { + return Objects.hash(autoApproved, dismissed, content); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ConfirmationResult other = (ConfirmationResult) obj; + return autoApproved == other.autoApproved + && dismissed == other.dismissed + && Objects.equals(content, other.content); + } + + @Override + public String toString() { + return new ToStringBuilder(this) + .append("autoApproved", autoApproved) + .append("dismissed", dismissed) + .append("content", content) + .toString(); + } +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/FileOperationAutoApproveRule.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/FileOperationAutoApproveRule.java new file mode 100644 index 00000000..9f5c819d --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/FileOperationAutoApproveRule.java @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.chat; + +import java.util.Objects; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * A single file-operation auto-approve rule mapping a glob pattern to an allow/deny decision. + */ +public class FileOperationAutoApproveRule { + private String pattern; + private String description; + private boolean autoApprove; + private transient boolean isDefault; + + /** + * Creates a new rule. + * + * @param pattern the glob pattern (e.g., "**\/.github/instructions/*") + * @param description human-readable description of what this pattern matches + * @param autoApprove true to auto-approve, false to always require confirmation + */ + public FileOperationAutoApproveRule(String pattern, String description, boolean autoApprove) { + this(pattern, description, autoApprove, false); + } + + /** + * Creates a new rule. + * + * @param pattern the glob pattern + * @param description human-readable description + * @param autoApprove true to auto-approve, false to always require confirmation + * @param isDefault true if this is a CLS default rule (non-removable) + */ + public FileOperationAutoApproveRule(String pattern, String description, + boolean autoApprove, boolean isDefault) { + this.pattern = pattern; + this.description = description; + this.autoApprove = autoApprove; + this.isDefault = isDefault; + } + + /** Default constructor for Gson deserialization. */ + public FileOperationAutoApproveRule() { + } + + public String getPattern() { + return pattern; + } + + public void setPattern(String pattern) { + this.pattern = pattern; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public boolean isAutoApprove() { + return autoApprove; + } + + public void setAutoApprove(boolean autoApprove) { + this.autoApprove = autoApprove; + } + + public boolean isDefault() { + return isDefault; + } + + public void setDefault(boolean isDefault) { + this.isDefault = isDefault; + } + + @Override + public int hashCode() { + return Objects.hash(pattern, description, autoApprove); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + FileOperationAutoApproveRule other = (FileOperationAutoApproveRule) obj; + return Objects.equals(pattern, other.pattern) + && Objects.equals(description, other.description) + && autoApprove == other.autoApprove; + } + + @Override + public String toString() { + return new ToStringBuilder(this) + .append("pattern", pattern) + .append("description", description) + .append("autoApprove", autoApprove) + .toString(); + } +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/TerminalAutoApproveRule.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/TerminalAutoApproveRule.java new file mode 100644 index 00000000..b70a2797 --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/TerminalAutoApproveRule.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.chat; + +import java.util.Objects; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * A single terminal auto-approve rule mapping a command name or regex pattern to an + * allow/deny decision. + */ +public class TerminalAutoApproveRule { + private String command; + private boolean autoApprove; + + /** + * Creates a new rule. + * + * @param command the command name or regex pattern + * @param autoApprove true to auto-approve, false to always require confirmation + */ + public TerminalAutoApproveRule(String command, boolean autoApprove) { + this.command = command; + this.autoApprove = autoApprove; + } + + /** Default constructor for Gson deserialization. */ + public TerminalAutoApproveRule() { + } + + public String getCommand() { + return command; + } + + public void setCommand(String command) { + this.command = command; + } + + public boolean isAutoApprove() { + return autoApprove; + } + + public void setAutoApprove(boolean autoApprove) { + this.autoApprove = autoApprove; + } + + @Override + public int hashCode() { + return Objects.hash(autoApprove, command); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + TerminalAutoApproveRule other = (TerminalAutoApproveRule) obj; + return autoApprove == other.autoApprove + && Objects.equals(command, other.command); + } + + @Override + public String toString() { + return new ToStringBuilder(this) + .append("command", command) + .append("autoApprove", autoApprove) + .toString(); + } +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/service/CustomizationFileService.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/service/CustomizationFileService.java new file mode 100644 index 00000000..c94c14f7 --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/service/CustomizationFileService.java @@ -0,0 +1,144 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.chat.service; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CompletableFuture; + +import org.eclipse.e4.core.contexts.EclipseContextFactory; +import org.eclipse.e4.core.services.events.IEventBroker; +import org.eclipse.lsp4j.WorkspaceFolder; +import org.osgi.framework.FrameworkUtil; +import org.osgi.service.event.EventHandler; + +import com.microsoft.copilot.eclipse.core.CopilotCore; +import com.microsoft.copilot.eclipse.core.events.CopilotEventConstants; +import com.microsoft.copilot.eclipse.core.lsp.CopilotLanguageServerConnection; +import com.microsoft.copilot.eclipse.core.lsp.protocol.CustomizationFileInfo; +import com.microsoft.copilot.eclipse.core.utils.FileUtils; +import com.microsoft.copilot.eclipse.core.utils.WorkspaceUtils; + +/** + * Default {@link ICustomizationFileService} backed by the language server's {@code copilot/custom*} + * list requests. Each customization type is fetched and snapshotted independently. + */ +public class CustomizationFileService implements ICustomizationFileService { + + private final CopilotLanguageServerConnection lsConnection; + private final IEventBroker eventBroker; + private final EventHandler customizationFilesChangedHandler; + + private volatile Set promptFiles = Set.of(); + private volatile Set instructionFiles = Set.of(); + private volatile Set agentFiles = Set.of(); + private volatile Set skillFolders = Set.of(); + + private volatile Set customizationFiles = Set.of(); + + /** + * Creates the service and subscribes to customization-file change events. + * + * @param lsConnection the language server connection used to issue the list requests + */ + public CustomizationFileService(CopilotLanguageServerConnection lsConnection) { + this.lsConnection = lsConnection; + this.eventBroker = EclipseContextFactory + .getServiceContext(FrameworkUtil.getBundle(getClass()).getBundleContext()).get(IEventBroker.class); + this.customizationFilesChangedHandler = event -> { + if (event.getProperty(IEventBroker.DATA) instanceof CustomizationType type) { + CompletableFuture.runAsync(() -> refreshType(type, WorkspaceUtils.listWorkspaceFolders())); + } + }; + if (eventBroker != null) { + eventBroker.subscribe(CopilotEventConstants.TOPIC_CHAT_DID_CHANGE_CUSTOMIZATION_FILES, + customizationFilesChangedHandler); + } + } + + /** Unsubscribes from customization-file change events. */ + public void dispose() { + if (eventBroker != null) { + eventBroker.unsubscribe(customizationFilesChangedHandler); + } + } + + @Override + public Set getCustomizationFiles() { + return customizationFiles; + } + + @Override + public Set getSkillFolders() { + return skillFolders; + } + + @Override + public void refreshAllAsync() { + CompletableFuture.runAsync(() -> { + List workspaceFolders = WorkspaceUtils.listWorkspaceFolders(); + for (CustomizationType type : CustomizationType.values()) { + refreshType(type, workspaceFolders); + } + }); + } + + private void refreshType(CustomizationType type, List workspaceFolders) { + switch (type) { + case SKILL -> toPaths(lsConnection.listCustomSkills(workspaceFolders)).thenAccept(paths -> { + Set folders = new HashSet<>(); + for (Path skillFile : paths) { + Path parent = skillFile.getParent(); + if (parent != null) { + folders.add(parent); + } + } + this.skillFolders = Set.copyOf(folders); + }); + case PROMPT -> toPaths(lsConnection.listCustomPrompts(workspaceFolders)).thenAccept(paths -> { + this.promptFiles = Set.copyOf(paths); + rebuildCustomizationFiles(); + }); + case INSTRUCTION -> toPaths(lsConnection.listCustomInstructions(workspaceFolders)).thenAccept(paths -> { + this.instructionFiles = Set.copyOf(paths); + rebuildCustomizationFiles(); + }); + case AGENT -> toPaths(lsConnection.listCustomAgents(workspaceFolders)).thenAccept(paths -> { + this.agentFiles = Set.copyOf(paths); + rebuildCustomizationFiles(); + }); + default -> { + // No other customization types. + } + } + } + + private synchronized void rebuildCustomizationFiles() { + Set all = new HashSet<>(promptFiles); + all.addAll(instructionFiles); + all.addAll(agentFiles); + this.customizationFiles = Set.copyOf(all); + } + + private CompletableFuture> toPaths(CompletableFuture future) { + return future.thenApply(infos -> { + List paths = new ArrayList<>(); + if (infos != null) { + for (CustomizationFileInfo info : infos) { + Path path = FileUtils.getLocalFilePath(info.uri()); + if (path != null) { + paths.add(path.toAbsolutePath().normalize()); + } + } + } + return paths; + }).exceptionally(ex -> { + CopilotCore.LOGGER.error("Failed to list customization files", ex); + return List.of(); + }); + } +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/service/IChatServiceManager.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/service/IChatServiceManager.java index 65aa911e..d6b0784f 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/service/IChatServiceManager.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/service/IChatServiceManager.java @@ -17,4 +17,9 @@ public interface IChatServiceManager { * Get the MCP config service. */ IMcpConfigService getMcpConfigService(); + + /** + * Get the customization file service tracking skill/prompt/instruction/agent file locations. + */ + ICustomizationFileService getCustomizationFileService(); } diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/service/ICustomizationFileService.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/service/ICustomizationFileService.java new file mode 100644 index 00000000..736df418 --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/chat/service/ICustomizationFileService.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.chat.service; + +import java.nio.file.Path; +import java.util.Set; + +/** + * Maintains an up-to-date view of the Copilot customization files (skills, prompts, instructions, + * and agents) reported by the language server, keyed by their on-disk location. + * + */ +public interface ICustomizationFileService { + + /** The customization kinds, each backed by a distinct language-server list request. */ + enum CustomizationType { + SKILL, PROMPT, INSTRUCTION, AGENT + } + + /** + * Returns the absolute paths of single-file customization files (prompts, instructions, agents). + * The returned set is an immutable snapshot. + */ + Set getCustomizationFiles(); + + /** + * Returns the absolute paths of skill folders (the directory containing each {@code SKILL.md}). + * A read of any file within one of these folders is a skill read. The returned set is an immutable + * snapshot. + */ + Set getSkillFolders(); + + /** + * Refreshes every customization type from the language server. Used for the initial load. + * Fire-and-forget; the work completes asynchronously off the caller's thread. + */ + void refreshAllAsync(); +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/events/CopilotEventConstants.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/events/CopilotEventConstants.java index 1e34f256..1a2d3c9e 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/events/CopilotEventConstants.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/events/CopilotEventConstants.java @@ -151,6 +151,17 @@ public class CopilotEventConstants { */ public static final String TOPIC_MCP_SERVER_STATE_CHANGE = TOPIC_MCP + "SERVER_STATE_CHANGE"; + /** + * Event when the MCP registration extension-point manager has finished detecting and verifying + * the contributed servers (either at startup or after a policy toggle / user approval) and the + * approved-servers JSON for the language server is ready to be pushed. + * + *

Payload (via {@code IEventBroker.DATA}): the approved-servers JSON {@code String}, or + * {@code null} when no extension-contributed servers are approved. + */ + public static final String TOPIC_MCP_EXTENSION_POINT_REGISTRATION_COMPLETED = TOPIC_MCP + + "EXTENSION_POINT_REGISTRATION_COMPLETED"; + /** * Event when NES suggestion is accepted. */ @@ -172,8 +183,18 @@ public class CopilotEventConstants { public static final String TOPIC_QUOTA_WARNING = TOPIC_QUOTA + "WARNING"; /** - * Event when custom prompts, skills, agents, or instructions change on the language server. Clients should re-fetch - * conversation templates on receipt. + * Event when custom prompts, skills, agents, or instructions change on the language server. The event data is the + * {@link com.microsoft.copilot.eclipse.core.chat.service.ICustomizationFileService.CustomizationType} that changed. */ public static final String TOPIC_CHAT_DID_CHANGE_CUSTOMIZATION_FILES = TOPIC_CHAT + "DID_CHANGE_CUSTOMIZATION_FILES"; + + /** + * Event when automatic conversation compression starts. + */ + public static final String TOPIC_CHAT_COMPRESSION_STARTED = TOPIC_CHAT + "COMPRESSION_STARTED"; + + /** + * Event when automatic conversation compression completes. + */ + public static final String TOPIC_CHAT_COMPRESSION_COMPLETED = TOPIC_CHAT + "COMPRESSION_COMPLETED"; } diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/format/FormatOptionProvider.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/format/FormatOptionProvider.java index 8b06a164..b738929f 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/format/FormatOptionProvider.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/format/FormatOptionProvider.java @@ -9,6 +9,8 @@ import org.apache.commons.lang3.StringUtils; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.preferences.IPreferencesService; import org.eclipse.lsp4j.FormattingOptions; import com.microsoft.copilot.eclipse.core.CopilotCore; @@ -26,6 +28,9 @@ public class FormatOptionProvider { private static final String CPP_LANGUAGE_ID = "cpp"; private static final String[] CPP_LANGUAGE_EXTENSIONS = new String[] { "cpp", "c++", "cc", "cp", "cxx", "h", "h++", "hh", ".hpp", ".hxx", ".inc", ".inl", ".ipp", ".tcc", ".tpp" }; + private static final String EDITOR_PREF_NODE = "org.eclipse.ui.editors"; + private static final String TAB_WIDTH_KEY = "tabWidth"; + private static final String SPACES_FOR_TABS_KEY = "spacesForTabs"; private static final boolean DEFAULT_USE_SPACE = LanguageFormatReader.PREFERENCE_DEFAULT_TAB_CHAR.equals("space"); private static final int DEFAULT_TAB_SIZE = LanguageFormatReader.PREFERENCE_DEFAULT_TAB_SIZE; @@ -85,13 +90,13 @@ private FormattingOptions getLanguageFormat(IFile file) { IProject project = file.getProject(); if (project == null) { CopilotCore.LOGGER.info("Project is null for file: " + file.getName() + "default format will be applied."); - return null; + return getEclipseTextEditorFormattingOptions(); } String fileExtension = file.getFileExtension(); if (StringUtils.isEmpty(fileExtension)) { CopilotCore.LOGGER.info("File extension is null or empty for file: " + file.getName()); - return null; + return getEclipseTextEditorFormattingOptions(); } else { fileExtension = fileExtension.toLowerCase(); } @@ -110,7 +115,7 @@ private FormattingOptions getLanguageFormat(IFile file) { if (languageFormatReaderForProject == null) { languageFormatReaderForProject = loadFormatReaderForTheProject(languageId, project); if (languageFormatReaderForProject == null) { - return new FormattingOptions(DEFAULT_TAB_SIZE, DEFAULT_USE_SPACE); + return getEclipseTextEditorFormattingOptions(); } projectToLanguageFormatReaderMap.put(project, languageFormatReaderForProject); } @@ -118,6 +123,38 @@ private FormattingOptions getLanguageFormat(IFile file) { return languageFormatReaderForProject.getFormattingOptions(); } + /** + * Attempts to read the Eclipse default text editor preferences for tab size and spaces-for-tabs. + * Falls back to hardcoded defaults if the preferences cannot be read. + */ + private FormattingOptions getEclipseTextEditorFormattingOptions() { + try { + IPreferencesService service = Platform.getPreferencesService(); + + boolean useSpaces = service.getBoolean( + EDITOR_PREF_NODE, + SPACES_FOR_TABS_KEY, + DEFAULT_USE_SPACE, + null + ); + + int tabSize = service.getInt( + EDITOR_PREF_NODE, + TAB_WIDTH_KEY, + DEFAULT_TAB_SIZE, + null + ); + + return new FormattingOptions(tabSize, useSpaces); + } catch (Exception e) { + CopilotCore.LOGGER.info( + "Failed to read Eclipse text editor preferences, using defaults"); + return new FormattingOptions(DEFAULT_TAB_SIZE, DEFAULT_USE_SPACE); + } + } + + + private LanguageFormatReader loadFormatReaderForTheProject(String languageId, IProject project) { switch (languageId) { case JAVA_LANGUAGE_ID: @@ -129,4 +166,4 @@ private LanguageFormatReader loadFormatReaderForTheProject(String languageId, IP return null; } } -} \ No newline at end of file +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/CopilotLanguageClient.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/CopilotLanguageClient.java index c3897ad9..cf0e81ad 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/CopilotLanguageClient.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/CopilotLanguageClient.java @@ -37,12 +37,15 @@ import com.microsoft.copilot.eclipse.core.CopilotCore; import com.microsoft.copilot.eclipse.core.FeatureFlags; import com.microsoft.copilot.eclipse.core.chat.service.IChatServiceManager; +import com.microsoft.copilot.eclipse.core.chat.service.ICustomizationFileService.CustomizationType; import com.microsoft.copilot.eclipse.core.chat.service.IMcpConfigService; import com.microsoft.copilot.eclipse.core.chat.service.IReferencedFileService; import com.microsoft.copilot.eclipse.core.events.CopilotEventConstants; import com.microsoft.copilot.eclipse.core.lsp.mcp.McpOauthRequest; import com.microsoft.copilot.eclipse.core.lsp.mcp.McpRuntimeLog; import com.microsoft.copilot.eclipse.core.lsp.protocol.ChatProgressValue; +import com.microsoft.copilot.eclipse.core.lsp.protocol.CompressionCompletedParams; +import com.microsoft.copilot.eclipse.core.lsp.protocol.CompressionStartedParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.ConversationCapabilities; import com.microsoft.copilot.eclipse.core.lsp.protocol.ConversationContextParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.CurrentEditorContext; @@ -262,24 +265,42 @@ public void onRateLimitWarning(RateLimitWarningParams params) { } /** - * Notify when custom skills change (global or workspace). Signal-only; clients re-fetch templates. + * Notify when custom skills change (global or workspace). */ @JsonNotification("copilot/customSkill/didChange") public void onDidChangeCustomSkill(Object params) { - notifyCustomizationFilesChanged(); + postCustomizationFilesChanged(CustomizationType.SKILL); } /** - * Notify when custom prompts change (global or workspace). Signal-only; clients re-fetch templates. + * Notify when custom prompts change (global or workspace). */ @JsonNotification("copilot/customPrompt/didChange") public void onDidChangeCustomPrompt(Object params) { - notifyCustomizationFilesChanged(); + postCustomizationFilesChanged(CustomizationType.PROMPT); } - private void notifyCustomizationFilesChanged() { + /** + * Notify when custom instructions change (global or workspace). + */ + @JsonNotification("copilot/customInstruction/didChange") + public void onDidChangeCustomInstruction(Object params) { + postCustomizationFilesChanged(CustomizationType.INSTRUCTION); + } + + /** + * Notify when custom agents change (global or workspace). + */ + @JsonNotification("copilot/customAgent/didChange") + public void onDidChangeCustomAgent(Object params) { + postCustomizationFilesChanged(CustomizationType.AGENT); + } + + // Broadcasts the change on the event bus; subscribers (the customization-file service and the + // slash-command service) react without this class depending on them directly. + private void postCustomizationFilesChanged(CustomizationType type) { if (eventBroker != null) { - eventBroker.post(CopilotEventConstants.TOPIC_CHAT_DID_CHANGE_CUSTOMIZATION_FILES, null); + eventBroker.post(CopilotEventConstants.TOPIC_CHAT_DID_CHANGE_CUSTOMIZATION_FILES, type); } } @@ -310,6 +331,7 @@ public void onDidChangeFeatureFlags(DidChangeFeatureFlagsParams params) { flags.setMcpEnabled(params.isMcpEnabled()); flags.setByokEnabled(params.isByokEnabled()); flags.setClientPreviewFeatureEnabled(params.isClientPreviewFeaturesEnabled()); + flags.setAutoApprovalTokenEnabled(params.isAutoApprovalEnabled()); } if (eventBroker != null) { @@ -337,6 +359,7 @@ public void onDidChangePolicy(DidChangePolicyParams params) { flags.setCustomAgentPolicyEnabled(params.isCustomAgentEnabled()); eventBroker.post(CopilotEventConstants.TOPIC_DID_CHANGE_CUSTOM_AGENT_POLICY, params.isCustomAgentEnabled()); } + flags.setAutoApprovalPolicyEnabled(params.isAutoApprovalPolicyEnabled()); } } @@ -364,6 +387,26 @@ public void onQuotaWarning(QuotaWarningParams params) { } } + /** + * Notify when automatic conversation compression starts. + */ + @JsonNotification("$/copilot/compressionStarted") + public void onCompressionStarted(CompressionStartedParams params) { + if (eventBroker != null) { + eventBroker.post(CopilotEventConstants.TOPIC_CHAT_COMPRESSION_STARTED, params); + } + } + + /** + * Notify when automatic conversation compression completes. + */ + @JsonNotification("$/copilot/compressionCompleted") + public void onCompressionCompleted(CompressionCompletedParams params) { + if (eventBroker != null) { + eventBroker.post(CopilotEventConstants.TOPIC_CHAT_COMPRESSION_COMPLETED, params); + } + } + /** * Reads the contents and stats of a file given its URI. */ diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/CopilotLanguageServer.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/CopilotLanguageServer.java index aae71950..f238d933 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/CopilotLanguageServer.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/CopilotLanguageServer.java @@ -29,13 +29,14 @@ import com.microsoft.copilot.eclipse.core.lsp.protocol.ConversationMode; import com.microsoft.copilot.eclipse.core.lsp.protocol.ConversationModesParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.ConversationTemplate; -import com.microsoft.copilot.eclipse.core.lsp.protocol.ConversationTemplatesParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.ConversationTurnParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel; import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotStatusResult; +import com.microsoft.copilot.eclipse.core.lsp.protocol.CustomizationFileInfo; import com.microsoft.copilot.eclipse.core.lsp.protocol.DidShowInlineEditParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.GenerateThinkingTitleParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.GenerateThinkingTitleResponse; +import com.microsoft.copilot.eclipse.core.lsp.protocol.GetDefaultFileSafetyRulesResult; import com.microsoft.copilot.eclipse.core.lsp.protocol.LanguageModelToolInformation; import com.microsoft.copilot.eclipse.core.lsp.protocol.NextEditSuggestionsParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.NextEditSuggestionsResult; @@ -50,6 +51,7 @@ import com.microsoft.copilot.eclipse.core.lsp.protocol.TelemetryExceptionParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.UpdateConversationToolsStatusParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.UpdateMcpToolsStatusParams; +import com.microsoft.copilot.eclipse.core.lsp.protocol.WorkspaceFoldersParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.byok.ByokApiKey; import com.microsoft.copilot.eclipse.core.lsp.protocol.byok.ByokListApiKeyResponse; import com.microsoft.copilot.eclipse.core.lsp.protocol.byok.ByokListModelParams; @@ -145,7 +147,39 @@ public interface CopilotLanguageServer extends LanguageServer { * @param params includes workspace folders for discovering workspace-specific prompt files and skills */ @JsonRequest("conversation/templates") - CompletableFuture listTemplates(ConversationTemplatesParams params); + CompletableFuture listTemplates(WorkspaceFoldersParams params); + + /** + * List custom skill files (each carries its on-disk {@code uri}). + * + * @param params includes the workspace folders to scan + */ + @JsonRequest("copilot/customSkill/list") + CompletableFuture listCustomSkills(WorkspaceFoldersParams params); + + /** + * List custom prompt files (each carries its on-disk {@code uri}). + * + * @param params includes the workspace folders to scan + */ + @JsonRequest("copilot/customPrompt/list") + CompletableFuture listCustomPrompts(WorkspaceFoldersParams params); + + /** + * List custom instruction files (each carries its on-disk {@code uri}). + * + * @param params includes the workspace folders to scan + */ + @JsonRequest("copilot/customInstruction/list") + CompletableFuture listCustomInstructions(WorkspaceFoldersParams params); + + /** + * List custom agent files (each carries its on-disk {@code uri}). + * + * @param params includes the workspace folders to scan + */ + @JsonRequest("copilot/customAgent/list") + CompletableFuture listCustomAgents(WorkspaceFoldersParams params); /** * List conversation modes. @@ -285,6 +319,13 @@ public interface CopilotLanguageServer extends LanguageServer { @JsonRequest("githubApi/searchPR") CompletableFuture searchPr(SearchPrParams params); + /** + * Get the default file safety rules from CLS. + */ + @JsonRequest("getDefaultFileSafetyRules") + CompletableFuture getDefaultFileSafetyRules( + NullParams params); + /** * Notify that an inline edit was shown. */ diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/CopilotLanguageServerConnection.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/CopilotLanguageServerConnection.java index 7820652b..5844c4f7 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/CopilotLanguageServerConnection.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/CopilotLanguageServerConnection.java @@ -46,14 +46,15 @@ import com.microsoft.copilot.eclipse.core.lsp.protocol.ConversationMode; import com.microsoft.copilot.eclipse.core.lsp.protocol.ConversationModesParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.ConversationTemplate; -import com.microsoft.copilot.eclipse.core.lsp.protocol.ConversationTemplatesParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.ConversationTurnParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel; import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotStatusResult; +import com.microsoft.copilot.eclipse.core.lsp.protocol.CustomizationFileInfo; import com.microsoft.copilot.eclipse.core.lsp.protocol.DidChangeCopilotWatchedFilesParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.DidShowInlineEditParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.GenerateThinkingTitleParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.GenerateThinkingTitleResponse; +import com.microsoft.copilot.eclipse.core.lsp.protocol.GetDefaultFileSafetyRulesResult; import com.microsoft.copilot.eclipse.core.lsp.protocol.LanguageModelToolInformation; import com.microsoft.copilot.eclipse.core.lsp.protocol.ModelInfo; import com.microsoft.copilot.eclipse.core.lsp.protocol.NextEditSuggestionsParams; @@ -71,6 +72,7 @@ import com.microsoft.copilot.eclipse.core.lsp.protocol.Turn; import com.microsoft.copilot.eclipse.core.lsp.protocol.UpdateConversationToolsStatusParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.UpdateMcpToolsStatusParams; +import com.microsoft.copilot.eclipse.core.lsp.protocol.WorkspaceFoldersParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.byok.ByokApiKey; import com.microsoft.copilot.eclipse.core.lsp.protocol.byok.ByokListApiKeyResponse; import com.microsoft.copilot.eclipse.core.lsp.protocol.byok.ByokListModelParams; @@ -153,6 +155,16 @@ public CompletableFuture checkQuota() { return this.languageServerWrapper.execute(fn); } + /** + * Get the default file safety rules from CLS. + */ + public CompletableFuture getDefaultFileSafetyRules() { + Function> fn = + server -> ((CopilotLanguageServer) server) + .getDefaultFileSafetyRules(new NullParams()); + return this.languageServerWrapper.execute(fn); + } + /** * Get single completion for the given parameters. */ @@ -363,11 +375,51 @@ public CompletableFuture addConversationTurn(String workDoneToke */ public CompletableFuture listConversationTemplates(List workspaceFolders) { Function> fn = server -> { - return ((CopilotLanguageServer) server).listTemplates(new ConversationTemplatesParams(workspaceFolders)); + return ((CopilotLanguageServer) server).listTemplates(new WorkspaceFoldersParams(workspaceFolders)); }; return this.languageServerWrapper.execute(fn); } + /** + * List custom skill files, each carrying its on-disk {@code uri}. + * + * @param workspaceFolders the workspace folders to scan + */ + public CompletableFuture listCustomSkills(List workspaceFolders) { + return this.languageServerWrapper.execute(server -> + ((CopilotLanguageServer) server).listCustomSkills(new WorkspaceFoldersParams(workspaceFolders))); + } + + /** + * List custom prompt files, each carrying its on-disk {@code uri}. + * + * @param workspaceFolders the workspace folders to scan + */ + public CompletableFuture listCustomPrompts(List workspaceFolders) { + return this.languageServerWrapper.execute(server -> + ((CopilotLanguageServer) server).listCustomPrompts(new WorkspaceFoldersParams(workspaceFolders))); + } + + /** + * List custom instruction files, each carrying its on-disk {@code uri}. + * + * @param workspaceFolders the workspace folders to scan + */ + public CompletableFuture listCustomInstructions(List workspaceFolders) { + return this.languageServerWrapper.execute(server -> + ((CopilotLanguageServer) server).listCustomInstructions(new WorkspaceFoldersParams(workspaceFolders))); + } + + /** + * List custom agent files, each carrying its on-disk {@code uri}. + * + * @param workspaceFolders the workspace folders to scan + */ + public CompletableFuture listCustomAgents(List workspaceFolders) { + return this.languageServerWrapper.execute(server -> + ((CopilotLanguageServer) server).listCustomAgents(new WorkspaceFoldersParams(workspaceFolders))); + } + /** * List the conversation modes. */ @@ -697,19 +749,15 @@ private String getModelName(CopilotModel activeModel) { } /** - * Builds the {@link ModelInfo} payload to forward with chat requests. Returns {@code null} when no reasoning effort - * is available so we do not send redundant {@code id}/{@code providerName} fields ahead of the future migration - * away from the legacy {@code model}/{@code modelProviderName} fields. Today the language server only consumes - * {@code modelInfo.reasoningEffort}, so suppressing the payload when there is nothing meaningful to forward keeps - * the protocol surface minimal and avoids implicit behaviour changes if the server starts honouring id/providerName - * before the client migration lands. + * Builds the {@link ModelInfo} payload for chat requests. Always sends the concrete model id (which the server + * prefers over the legacy {@code model} family field), since the family is not unique across models. Returns + * {@code null} when no model id is available. */ private static ModelInfo buildModelInfo(CopilotModel activeModel, String reasoningEffort) { - if (StringUtils.isBlank(reasoningEffort)) { + if (activeModel == null || StringUtils.isBlank(activeModel.getId())) { return null; } - String id = activeModel != null ? activeModel.getId() : null; - String providerName = activeModel != null ? activeModel.getProviderName() : null; - return new ModelInfo(id, providerName, reasoningEffort); + String effort = StringUtils.isBlank(reasoningEffort) ? null : reasoningEffort; + return new ModelInfo(activeModel.getId(), activeModel.getProviderName(), effort, null); } } diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CompressionCompletedParams.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CompressionCompletedParams.java new file mode 100644 index 00000000..28869330 --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CompressionCompletedParams.java @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.lsp.protocol; + +/** + * Parameters for the {@code $/copilot/compressionCompleted} notification sent by the language server when automatic + * conversation compression finishes. The {@code contextInfo} field is optional and may be {@code null}. + */ +public record CompressionCompletedParams( + String conversationId, + int archivedPartitionId, + int newPartitionId, + int summaryLength, + int turnCount, + int durationMs, + ContextSizeInfo contextInfo) { +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CompressionStartedParams.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CompressionStartedParams.java new file mode 100644 index 00000000..247826bd --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CompressionStartedParams.java @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.lsp.protocol; + +/** + * Parameters for the {@code $/copilot/compressionStarted} notification sent by the language server when automatic + * conversation compression begins. + */ +public record CompressionStartedParams(String conversationId, int partitionId, String reason) { +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ContextSizeInfo.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ContextSizeInfo.java index 0edd83a8..2331bab7 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ContextSizeInfo.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ContextSizeInfo.java @@ -9,6 +9,7 @@ */ public record ContextSizeInfo( int totalTokenLimit, + int reservedOutputTokens, int systemPromptTokens, int toolDefinitionTokens, int userMessagesTokens, diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ConversationTemplatesParams.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ConversationTemplatesParams.java deleted file mode 100644 index 6b384b94..00000000 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ConversationTemplatesParams.java +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -package com.microsoft.copilot.eclipse.core.lsp.protocol; - -import java.util.Collections; -import java.util.List; - -import org.eclipse.lsp4j.WorkspaceFolder; - -/** - * Parameters for the {@code conversation/templates} request. - * - * @param workspaceFolders the workspace folders used to discover workspace-specific prompt files and skills - */ -public record ConversationTemplatesParams(List workspaceFolders) { - /** Compact constructor that defaults {@code null} workspace folders to an empty list. */ - public ConversationTemplatesParams { - workspaceFolders = workspaceFolders != null ? workspaceFolders : Collections.emptyList(); - } -} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CopilotAgentSettings.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CopilotAgentSettings.java index 5a54d5e1..818fbd36 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CopilotAgentSettings.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CopilotAgentSettings.java @@ -3,6 +3,7 @@ package com.microsoft.copilot.eclipse.core.lsp.protocol; +import java.util.Map; import java.util.Objects; import com.google.gson.annotations.SerializedName; @@ -16,9 +17,141 @@ public class CopilotAgentSettings { @SerializedName("maxToolCallingLoop") private int agentMaxRequests; private boolean enableSkills; + private boolean autoCompress; private String transcriptDirectory; + @SerializedName("autoApproveUnmatchedTerminal") + private boolean autoApproveUnmatchedTerminal; + + @SerializedName("autoApproveUnmatchedFileOp") + private boolean autoApproveUnmatchedFileOp; + + // Tells CLS to always send confirmation requests to the editor + @SerializedName("editorHandlesAllConfirmation") + private boolean editorHandlesAllConfirmation = true; + + private ToolsSettings tools; + + /** Nested tools settings matching CLS agent.tools structure. */ + public static class ToolsSettings { + private TerminalSettings terminal; + private EditSettings edit; + + /** Gets terminal settings, creating if needed. */ + public TerminalSettings getTerminal() { + if (terminal == null) { + terminal = new TerminalSettings(); + } + return terminal; + } + + /** Gets edit settings, creating if needed. */ + public EditSettings getEdit() { + if (edit == null) { + edit = new EditSettings(); + } + return edit; + } + + @Override + public int hashCode() { + return Objects.hash(terminal, edit); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + ToolsSettings other = (ToolsSettings) obj; + return Objects.equals(terminal, other.terminal) && Objects.equals(edit, other.edit); + } + + @Override + public String toString() { + return new ToStringBuilder(this) + .append("terminal", terminal) + .append("edit", edit) + .toString(); + } + } + + /** Terminal auto-approve rules: command/pattern -> allow(true)/deny(false). */ + public static class TerminalSettings { + private Map autoApprove; + + public Map getAutoApprove() { + return autoApprove; + } + + public void setAutoApprove(Map autoApprove) { + this.autoApprove = autoApprove; + } + + @Override + public int hashCode() { + return Objects.hash(autoApprove); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + return Objects.equals(autoApprove, ((TerminalSettings) obj).autoApprove); + } + + @Override + public String toString() { + return new ToStringBuilder(this) + .append("autoApprove", autoApprove) + .toString(); + } + } + + /** Edit (file operation) auto-approve rules: pattern → allow(true)/deny(false). */ + public static class EditSettings { + private Map autoApprove; + + public Map getAutoApprove() { + return autoApprove; + } + + public void setAutoApprove(Map autoApprove) { + this.autoApprove = autoApprove; + } + + @Override + public int hashCode() { + return Objects.hash(autoApprove); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + return Objects.equals(autoApprove, ((EditSettings) obj).autoApprove); + } + + @Override + public String toString() { + return new ToStringBuilder(this) + .append("autoApprove", autoApprove) + .toString(); + } + } + public int getAgentMaxRequests() { return agentMaxRequests; } @@ -46,13 +179,50 @@ public String getTranscriptDirectory() { return transcriptDirectory; } + public boolean isAutoCompress() { + return autoCompress; + } + + public void setAutoCompress(boolean autoCompress) { + this.autoCompress = autoCompress; + } + public void setTranscriptDirectory(String transcriptDirectory) { this.transcriptDirectory = transcriptDirectory; } + public boolean isEditorHandlesAllConfirmation() { + return editorHandlesAllConfirmation; + } + + public boolean isAutoApproveUnmatchedTerminal() { + return autoApproveUnmatchedTerminal; + } + + public void setAutoApproveUnmatchedTerminal(boolean autoApproveUnmatchedTerminal) { + this.autoApproveUnmatchedTerminal = autoApproveUnmatchedTerminal; + } + + public boolean isAutoApproveUnmatchedFileOp() { + return autoApproveUnmatchedFileOp; + } + + public void setAutoApproveUnmatchedFileOp(boolean autoApproveUnmatchedFileOp) { + this.autoApproveUnmatchedFileOp = autoApproveUnmatchedFileOp; + } + + /** Gets tools settings, creating if needed. */ + public ToolsSettings getTools() { + if (tools == null) { + tools = new ToolsSettings(); + } + return tools; + } + @Override public int hashCode() { - return Objects.hash(agentMaxRequests, enableSkills, transcriptDirectory); + return Objects.hash(agentMaxRequests, enableSkills, autoCompress, transcriptDirectory, + editorHandlesAllConfirmation, autoApproveUnmatchedTerminal, autoApproveUnmatchedFileOp, tools); } @Override @@ -68,7 +238,12 @@ public boolean equals(Object obj) { } CopilotAgentSettings other = (CopilotAgentSettings) obj; return agentMaxRequests == other.agentMaxRequests && enableSkills == other.enableSkills - && Objects.equals(transcriptDirectory, other.transcriptDirectory); + && autoCompress == other.autoCompress + && Objects.equals(transcriptDirectory, other.transcriptDirectory) + && editorHandlesAllConfirmation == other.editorHandlesAllConfirmation + && autoApproveUnmatchedTerminal == other.autoApproveUnmatchedTerminal + && autoApproveUnmatchedFileOp == other.autoApproveUnmatchedFileOp + && Objects.equals(tools, other.tools); } @Override @@ -76,7 +251,12 @@ public String toString() { ToStringBuilder builder = new ToStringBuilder(this); builder.append("agentMaxRequests", agentMaxRequests); builder.append("enableSkills", enableSkills); + builder.append("autoCompress", autoCompress); builder.append("transcriptDirectory", transcriptDirectory); + builder.append("editorHandlesAllConfirmation", editorHandlesAllConfirmation); + builder.append("autoApproveUnmatchedTerminal", autoApproveUnmatchedTerminal); + builder.append("autoApproveUnmatchedFileOp", autoApproveUnmatchedFileOp); + builder.append("tools", tools); return builder.toString(); } diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CopilotModel.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CopilotModel.java index fe54ea25..b766f49c 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CopilotModel.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CopilotModel.java @@ -6,6 +6,7 @@ import java.util.List; import java.util.Objects; +import com.google.gson.annotations.SerializedName; import org.apache.commons.lang3.builder.ToStringBuilder; /** @@ -24,6 +25,7 @@ public class CopilotModel { private boolean isChatFallback; private CopilotModelCapabilities capabilities; private CopilotModelBilling billing; + private CopilotModelCustomModel customModel; private String degradationReason; private String providerName; private String modelPickerCategory; @@ -97,17 +99,46 @@ public String toString() { } /** - * Per-token prices for the model, returned in USD. + * Per-tier token prices, quoted in USD per {@link CopilotModelBillingTokenPrices#batchSize} tokens and applying up + * to {@code maxContext} context tokens. Requests larger than the {@code default} tier's {@code maxContext} are + * billed at the {@code longContext} tier. All components are optional ({@code null} when the server does not provide + * a value). + * + * @param cachePrice the price for cached input tokens + * @param inputPrice the price for input tokens + * @param outputPrice the price for output tokens + * @param maxContext the maximum number of context (input) tokens this tier applies to */ - public record CopilotModelBillingTokenPrices(Double cachePrice, Double inputPrice, Double outputPrice, - Double tokenUnit) { + public record CopilotModelTokenPriceTier(Double cachePrice, Double inputPrice, Double outputPrice, + Integer maxContext) { @Override public String toString() { ToStringBuilder builder = new ToStringBuilder(this); builder.append("cachePrice", cachePrice); builder.append("inputPrice", inputPrice); builder.append("outputPrice", outputPrice); - builder.append("tokenUnit", tokenUnit); + builder.append("maxContext", maxContext); + return builder.toString(); + } + } + + /** + * Per-tier token prices for the model. When token-based billing is enabled the server returns a {@code default} + * tier and, for models that support long context, a {@code longContext} tier. + * + * @param batchSize the number of tokens each tier price is quoted per + * @param defaultTier the {@code default} price tier (deserialized from the {@code default} JSON field) + * @param longContext the {@code longContext} price tier, or {@code null} when the model does not support long + * context + */ + public record CopilotModelBillingTokenPrices(Double batchSize, + @SerializedName("default") CopilotModelTokenPriceTier defaultTier, CopilotModelTokenPriceTier longContext) { + @Override + public String toString() { + ToStringBuilder builder = new ToStringBuilder(this); + builder.append("batchSize", batchSize); + builder.append("defaultTier", defaultTier); + builder.append("longContext", longContext); return builder.toString(); } } @@ -128,6 +159,28 @@ public String toString() { } } + /** + * Metadata describing a custom (BYOK) model that is contributed to the user by an organization or enterprise. When + * present, the model is served through a key that the owner configured, so it is surfaced in the model picker + * automatically without the user having to register their own API key. + * + * @param keyName the display name of the API key the model is served through + * @param ownerName the name of the organization, enterprise, or user that contributed the model + * @param ownerType the type of the owner (e.g. {@code organization}, {@code enterprise}, {@code user}) + * @param provider the underlying model provider (e.g. {@code azure}, {@code openai}) + */ + public record CopilotModelCustomModel(String keyName, String ownerName, String ownerType, String provider) { + @Override + public String toString() { + ToStringBuilder builder = new ToStringBuilder(this); + builder.append("keyName", keyName); + builder.append("ownerName", ownerName); + builder.append("ownerType", ownerType); + builder.append("provider", provider); + return builder.toString(); + } + } + public String getModelFamily() { return modelFamily; } @@ -216,6 +269,14 @@ public void setBilling(CopilotModelBilling billing) { this.billing = billing; } + public CopilotModelCustomModel getCustomModel() { + return customModel; + } + + public void setCustomModel(CopilotModelCustomModel customModel) { + this.customModel = customModel; + } + public String getDegradationReason() { return degradationReason; } @@ -270,6 +331,7 @@ public boolean equals(Object obj) { } CopilotModel other = (CopilotModel) obj; return Objects.equals(billing, other.billing) && Objects.equals(capabilities, other.capabilities) + && Objects.equals(customModel, other.customModel) && Objects.equals(degradationReason, other.degradationReason) && Objects.equals(id, other.id) && isChatDefault == other.isChatDefault && isChatFallback == other.isChatFallback && Objects.equals(modelFamily, other.modelFamily) && Objects.equals(modelName, other.modelName) @@ -282,8 +344,9 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return Objects.hash(billing, capabilities, degradationReason, id, isChatDefault, isChatFallback, modelFamily, - modelName, modelPickerCategory, modelPickerPriceCategory, modelPolicy, preview, providerName, scopes, vendor); + return Objects.hash(billing, capabilities, customModel, degradationReason, id, isChatDefault, isChatFallback, + modelFamily, modelName, modelPickerCategory, modelPickerPriceCategory, modelPolicy, preview, providerName, + scopes, vendor); } @Override @@ -300,6 +363,7 @@ public String toString() { builder.append("isChatFallback", isChatFallback); builder.append("capabilities", capabilities); builder.append("billing", billing); + builder.append("customModel", customModel); builder.append("degradationReason", degradationReason); builder.append("providerName", providerName); builder.append("modelPickerCategory", modelPickerCategory); diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CustomizationFileInfo.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CustomizationFileInfo.java new file mode 100644 index 00000000..c164b1dd --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/CustomizationFileInfo.java @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.lsp.protocol; + +/** + * Metadata for a Copilot customization file (skill, prompt, instruction, or agent) as returned by + * the language server's customization list requests. + * + * @param id the stable identifier, when provided by the language server + * @param name the user-facing name + * @param uri the on-disk file URI, or {@code null} for entries without a backing file + * @param storage the storage scope reported by the language server (for example {@code local} or {@code user}) + */ +public record CustomizationFileInfo(String id, String name, String uri, String storage) { +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/DidChangeFeatureFlagsParams.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/DidChangeFeatureFlagsParams.java index 44dd3e4c..cdd0e839 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/DidChangeFeatureFlagsParams.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/DidChangeFeatureFlagsParams.java @@ -76,6 +76,15 @@ public boolean isClientPreviewFeaturesEnabled() { return !disabled; } + /** + * Checks if the auto-approval feature is enabled. + * Disabled only when the feature flag "agent_mode_auto_approval" is set to "0". + */ + public boolean isAutoApprovalEnabled() { + boolean disabled = featureFlags != null && "0".equals(featureFlags.get("agent_mode_auto_approval")); + return !disabled; + } + @Override public int hashCode() { return Objects.hash(activeExps, featureFlags, envelope, byokEnabled); diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/FileSafetyRuleInfo.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/FileSafetyRuleInfo.java new file mode 100644 index 00000000..90348463 --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/FileSafetyRuleInfo.java @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.lsp.protocol; + +import java.util.Objects; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * A file safety rule as returned by CLS {@code getDefaultFileSafetyRules}. + * + *

Field names match the CLS JSON-RPC response exactly.

+ */ +public class FileSafetyRuleInfo { + + private String pattern; + private boolean requiresConfirmation; + private String description; + + /** Default constructor for Gson deserialization. */ + public FileSafetyRuleInfo() { + } + + /** + * Creates a new FileSafetyRuleInfo. + * + * @param pattern the glob pattern + * @param requiresConfirmation whether the file requires confirmation + * @param description description of the rule + */ + public FileSafetyRuleInfo(String pattern, boolean requiresConfirmation, + String description) { + this.pattern = pattern; + this.requiresConfirmation = requiresConfirmation; + this.description = description; + } + + public String getPattern() { + return pattern; + } + + + public void setPattern(String pattern) { + this.pattern = pattern; + } + + public boolean isRequiresConfirmation() { + return requiresConfirmation; + } + + public void setRequiresConfirmation(boolean requiresConfirmation) { + this.requiresConfirmation = requiresConfirmation; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public int hashCode() { + return Objects.hash(description, pattern, requiresConfirmation); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + FileSafetyRuleInfo other = (FileSafetyRuleInfo) obj; + return Objects.equals(description, other.description) + && Objects.equals(pattern, other.pattern) + && requiresConfirmation == other.requiresConfirmation; + } + + @Override + public String toString() { + return new ToStringBuilder(this) + .append("pattern", pattern) + .append("requiresConfirmation", requiresConfirmation) + .append("description", description) + .toString(); + } + +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/GetDefaultFileSafetyRulesResult.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/GetDefaultFileSafetyRulesResult.java new file mode 100644 index 00000000..a88e2c6c --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/GetDefaultFileSafetyRulesResult.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.lsp.protocol; + +import java.util.List; +import java.util.Objects; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Result of the {@code getDefaultFileSafetyRules} CLS request. + */ +public class GetDefaultFileSafetyRulesResult { + + private List defaultRules; + + /** Default constructor for Gson deserialization. */ + public GetDefaultFileSafetyRulesResult() { + } + + /** + * Creates a new result with the given default rules. + * + * @param defaultRules the list of default file safety rules + */ + public GetDefaultFileSafetyRulesResult( + List defaultRules) { + this.defaultRules = defaultRules; + } + + public List getDefaultRules() { + return defaultRules; + } + + public void setDefaultRules(List defaultRules) { + this.defaultRules = defaultRules; + } + + @Override + public int hashCode() { + return Objects.hash(defaultRules); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + GetDefaultFileSafetyRulesResult other = (GetDefaultFileSafetyRulesResult) obj; + return Objects.equals(defaultRules, other.defaultRules); + } + + @Override + public String toString() { + return new ToStringBuilder(this) + .append("defaultRules", defaultRules) + .toString(); + } +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/InvokeClientToolConfirmationParams.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/InvokeClientToolConfirmationParams.java index ba40b954..2066c74c 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/InvokeClientToolConfirmationParams.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/InvokeClientToolConfirmationParams.java @@ -52,6 +52,16 @@ public class InvokeClientToolConfirmationParams { */ private String toolCallId; + /** + * The MCP tool annotations describing tool behavior hints. + */ + private ToolAnnotations annotations; + + /** + * Additional metadata associated with the tool invocation. + */ + private ToolMetadata toolMetadata; + public String getName() { return name; } @@ -116,9 +126,26 @@ public void setToolCallId(String toolCallId) { this.toolCallId = toolCallId; } + public ToolAnnotations getAnnotations() { + return annotations; + } + + public void setAnnotations(ToolAnnotations annotations) { + this.annotations = annotations; + } + + public ToolMetadata getToolMetadata() { + return toolMetadata; + } + + public void setToolMetadata(ToolMetadata toolMetadata) { + this.toolMetadata = toolMetadata; + } + @Override public int hashCode() { - return Objects.hash(conversationId, input, message, name, roundId, title, toolCallId, turnId); + return Objects.hash(annotations, conversationId, input, message, name, roundId, title, toolCallId, toolMetadata, + turnId); } @Override @@ -133,10 +160,11 @@ public boolean equals(Object obj) { return false; } InvokeClientToolConfirmationParams other = (InvokeClientToolConfirmationParams) obj; - return Objects.equals(conversationId, other.conversationId) && Objects.equals(input, other.input) + return Objects.equals(annotations, other.annotations) + && Objects.equals(conversationId, other.conversationId) && Objects.equals(input, other.input) && Objects.equals(message, other.message) && Objects.equals(name, other.name) && roundId == other.roundId && Objects.equals(title, other.title) && Objects.equals(toolCallId, other.toolCallId) - && Objects.equals(turnId, other.turnId); + && Objects.equals(toolMetadata, other.toolMetadata) && Objects.equals(turnId, other.turnId); } @Override @@ -150,6 +178,8 @@ public String toString() { builder.append("turnId", turnId); builder.append("roundId", roundId); builder.append("toolCallId", toolCallId); + builder.append("annotations", annotations); + builder.append("toolMetadata", toolMetadata); return builder.toString(); } } diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ModelInfo.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ModelInfo.java index 729e9768..e7ff3e84 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ModelInfo.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ModelInfo.java @@ -7,14 +7,15 @@ * Optional model metadata associated with a conversation turn. Mirrors the {@code modelInfo} field on the * {@code conversation/create} and {@code conversation/turn} LSP requests and responses. * - *

The {@code id} and {@code providerName} fields are reserved for a future migration away from the legacy - * {@code model} / {@code modelProviderName} fields and should not be relied upon today. The {@code reasoningEffort} - * field carries the user-selected reasoning effort level (e.g. {@code low}, {@code medium}, {@code high}) when the - * model surfaces selectable effort levels. + *

The language server resolves the turn's model from {@code id} (and {@code providerName} for BYOK models) in + * preference to the legacy {@code model} / {@code modelProviderName} request fields, so {@code id} should carry the + * concrete model id of the user-selected model. The {@code reasoningEffort} field carries the user-selected reasoning + * effort level (e.g. {@code low}, {@code medium}, {@code high}) when the model surfaces selectable effort levels. * * @param id model identifier (optional) * @param providerName provider name (optional) * @param reasoningEffort user-selected reasoning effort (optional) + * @param contextSize context size (optional) */ -public record ModelInfo(String id, String providerName, String reasoningEffort) { +public record ModelInfo(String id, String providerName, String reasoningEffort, String contextSize) { } diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ToolAnnotations.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ToolAnnotations.java new file mode 100644 index 00000000..a59f3598 --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ToolAnnotations.java @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.lsp.protocol; + +import java.util.Objects; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * MCP tool annotations describing tool behavior hints (e.g., readOnly, destructive). + * Provided by CLS, originally sourced from the MCP server's tool definition. + */ +public class ToolAnnotations { + private boolean readOnlyHint; + private boolean destructiveHint; + private boolean idempotentHint; + private boolean openWorldHint; + + public boolean isReadOnlyHint() { + return readOnlyHint; + } + + public void setReadOnlyHint(boolean readOnlyHint) { + this.readOnlyHint = readOnlyHint; + } + + public boolean isDestructiveHint() { + return destructiveHint; + } + + public void setDestructiveHint(boolean destructiveHint) { + this.destructiveHint = destructiveHint; + } + + public boolean isIdempotentHint() { + return idempotentHint; + } + + public void setIdempotentHint(boolean idempotentHint) { + this.idempotentHint = idempotentHint; + } + + public boolean isOpenWorldHint() { + return openWorldHint; + } + + public void setOpenWorldHint(boolean openWorldHint) { + this.openWorldHint = openWorldHint; + } + + @Override + public int hashCode() { + return Objects.hash(readOnlyHint, destructiveHint, idempotentHint, openWorldHint); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ToolAnnotations other = (ToolAnnotations) obj; + return readOnlyHint == other.readOnlyHint + && destructiveHint == other.destructiveHint + && idempotentHint == other.idempotentHint + && openWorldHint == other.openWorldHint; + } + + @Override + public String toString() { + ToStringBuilder builder = new ToStringBuilder(this); + builder.append("readOnlyHint", readOnlyHint); + builder.append("destructiveHint", destructiveHint); + builder.append("idempotentHint", idempotentHint); + builder.append("openWorldHint", openWorldHint); + return builder.toString(); + } +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ToolMetadata.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ToolMetadata.java new file mode 100644 index 00000000..9883a504 --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/ToolMetadata.java @@ -0,0 +1,189 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.lsp.protocol; + +import java.util.Arrays; +import java.util.Objects; + +import org.apache.commons.lang3.builder.ToStringBuilder; + +/** + * Tool-specific metadata provided by CLS as part of the confirmation request, used by the + * auto-approve system to make confirmation decisions. + */ +public class ToolMetadata { + + private TerminalCommandData terminalCommandData; + private SensitiveFileData sensitiveFileData; + + public TerminalCommandData getTerminalCommandData() { + return terminalCommandData; + } + + public void setTerminalCommandData(TerminalCommandData terminalCommandData) { + this.terminalCommandData = terminalCommandData; + } + + public SensitiveFileData getSensitiveFileData() { + return sensitiveFileData; + } + + public void setSensitiveFileData(SensitiveFileData sensitiveFileData) { + this.sensitiveFileData = sensitiveFileData; + } + + @Override + public int hashCode() { + return Objects.hash(terminalCommandData, sensitiveFileData); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + ToolMetadata other = (ToolMetadata) obj; + return Objects.equals(terminalCommandData, other.terminalCommandData) + && Objects.equals(sensitiveFileData, other.sensitiveFileData); + } + + @Override + public String toString() { + ToStringBuilder builder = new ToStringBuilder(this); + builder.append("terminalCommandData", terminalCommandData); + builder.append("sensitiveFileData", sensitiveFileData); + return builder.toString(); + } + + /** + * Data describing a terminal command and its sub-commands. + */ + public static class TerminalCommandData { + private String[] subCommands; + private String[] commandNames; + + public String[] getSubCommands() { + return subCommands; + } + + public void setSubCommands(String[] subCommands) { + this.subCommands = subCommands; + } + + public String[] getCommandNames() { + return commandNames; + } + + public void setCommandNames(String[] commandNames) { + this.commandNames = commandNames; + } + + @Override + public int hashCode() { + return Objects.hash(Arrays.hashCode(subCommands), Arrays.hashCode(commandNames)); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + TerminalCommandData other = (TerminalCommandData) obj; + return Arrays.equals(subCommands, other.subCommands) + && Arrays.equals(commandNames, other.commandNames); + } + + @Override + public String toString() { + ToStringBuilder builder = new ToStringBuilder(this); + builder.append("subCommands", subCommands); + builder.append("commandNames", commandNames); + return builder.toString(); + } + } + + /** + * Data describing a sensitive file that requires confirmation. + */ + public static class SensitiveFileData { + private String filePath; + private String matchingRule; + private String ruleDescription; + private boolean isGlobal; + + public String getFilePath() { + return filePath; + } + + public void setFilePath(String filePath) { + this.filePath = filePath; + } + + public String getMatchingRule() { + return matchingRule; + } + + public void setMatchingRule(String matchingRule) { + this.matchingRule = matchingRule; + } + + public String getRuleDescription() { + return ruleDescription; + } + + public void setRuleDescription(String ruleDescription) { + this.ruleDescription = ruleDescription; + } + + public boolean isGlobal() { + return isGlobal; + } + + public void setGlobal(boolean isGlobal) { + this.isGlobal = isGlobal; + } + + @Override + public int hashCode() { + return Objects.hash(filePath, matchingRule, ruleDescription, isGlobal); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + SensitiveFileData other = (SensitiveFileData) obj; + return Objects.equals(filePath, other.filePath) + && Objects.equals(matchingRule, other.matchingRule) + && Objects.equals(ruleDescription, other.ruleDescription) + && isGlobal == other.isGlobal; + } + + @Override + public String toString() { + ToStringBuilder builder = new ToStringBuilder(this); + builder.append("filePath", filePath); + builder.append("matchingRule", matchingRule); + builder.append("ruleDescription", ruleDescription); + builder.append("isGlobal", isGlobal); + return builder.toString(); + } + } +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/WorkspaceFoldersParams.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/WorkspaceFoldersParams.java new file mode 100644 index 00000000..5f3e3574 --- /dev/null +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/WorkspaceFoldersParams.java @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.core.lsp.protocol; + +import java.util.List; + +import org.eclipse.lsp4j.WorkspaceFolder; + +/** + * Generic parameters for language-server requests scoped to a set of workspace folders. + * + * @param workspaceFolders the workspace folders to scan + */ +public record WorkspaceFoldersParams(List workspaceFolders) { + /** Compact constructor that defensively copies the folders, defaulting {@code null} to empty. */ + public WorkspaceFoldersParams { + workspaceFolders = workspaceFolders != null ? List.copyOf(workspaceFolders) : List.of(); + } +} diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/policy/DidChangePolicyParams.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/policy/DidChangePolicyParams.java index b5087205..3d21772a 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/policy/DidChangePolicyParams.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/lsp/protocol/policy/DidChangePolicyParams.java @@ -22,6 +22,9 @@ public class DidChangePolicyParams { @SerializedName("customAgent.enabled") private boolean customAgentEnabled = true; + @SerializedName("agentMode.autoApproval.enabled") + private boolean autoApprovalPolicyEnabled = true; + public boolean isMcpContributionPointEnabled() { return mcpContributionPointEnabled; } @@ -46,9 +49,18 @@ public void setCustomAgentEnabled(boolean customAgentEnabled) { this.customAgentEnabled = customAgentEnabled; } + public boolean isAutoApprovalPolicyEnabled() { + return autoApprovalPolicyEnabled; + } + + public void setAutoApprovalPolicyEnabled(boolean autoApprovalPolicyEnabled) { + this.autoApprovalPolicyEnabled = autoApprovalPolicyEnabled; + } + @Override public int hashCode() { - return Objects.hash(mcpContributionPointEnabled, subAgentEnabled, customAgentEnabled); + return Objects.hash(mcpContributionPointEnabled, subAgentEnabled, customAgentEnabled, + autoApprovalPolicyEnabled); } @Override @@ -65,7 +77,8 @@ public boolean equals(Object obj) { DidChangePolicyParams other = (DidChangePolicyParams) obj; return mcpContributionPointEnabled == other.mcpContributionPointEnabled && subAgentEnabled == other.subAgentEnabled - && customAgentEnabled == other.customAgentEnabled; + && customAgentEnabled == other.customAgentEnabled + && autoApprovalPolicyEnabled == other.autoApprovalPolicyEnabled; } @Override @@ -74,6 +87,7 @@ public String toString() { builder.append("mcpContributionPointEnabled", mcpContributionPointEnabled); builder.append("subAgentEnabled", subAgentEnabled); builder.append("customAgentEnabled", customAgentEnabled); + builder.append("autoApprovalPolicyEnabled", autoApprovalPolicyEnabled); return builder.toString(); } } diff --git a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/utils/FileUtils.java b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/utils/FileUtils.java index 3dd51c39..06bbb611 100644 --- a/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/utils/FileUtils.java +++ b/com.microsoft.copilot.eclipse.core/src/com/microsoft/copilot/eclipse/core/utils/FileUtils.java @@ -181,6 +181,53 @@ public static IFile getFileFromUri(String fileUri) { return null; } + /** + * Resolves an absolute local filesystem path from a path or file URI. + * + * @param filePath the path or URI to resolve + * @return the local filesystem path, or null if the input is not an absolute local path + */ + @Nullable + public static Path getLocalFilePath(String filePath) { + if (StringUtils.isBlank(filePath)) { + return null; + } + + try { + // For file URIs, '#' is always a fragment delimiter (literal '#' in filenames is encoded as %23). + if (filePath.startsWith("file:")) { + String uriWithoutFragment = stripFragment(filePath); + return Paths.get(new URI(uriWithoutFragment)).toAbsolutePath().normalize(); + } + + String pathWithoutFragment = stripFragment(filePath); + if (URI_SCHEME_PATTERN.matcher(pathWithoutFragment).find() && !hasDriveLetter(pathWithoutFragment)) { + return null; + } + + // For raw paths, try the full string first since '#' is a valid filename character on Unix/Linux. + // Only fall back to stripping the fragment if the full path doesn't exist. + Path fullPath = Paths.get(filePath); + if (fullPath.isAbsolute()) { + if (Files.exists(fullPath)) { + return fullPath.toAbsolutePath().normalize(); + } + // Fall back: treat '#...' as a line-number fragment + Path strippedPath = Paths.get(pathWithoutFragment); + return strippedPath.isAbsolute() ? strippedPath.toAbsolutePath().normalize() : null; + } + return null; + } catch (IllegalArgumentException | URISyntaxException e) { + CopilotCore.LOGGER.error("Invalid local file path: " + filePath, e); + return null; + } + } + + private static String stripFragment(String pathOrUri) { + int fragmentIndex = pathOrUri.indexOf('#'); + return fragmentIndex > 0 ? pathOrUri.substring(0, fragmentIndex) : pathOrUri; + } + /** * Normalizes a file path or URI string to a proper file URI string. Handles Windows absolute paths, POSIX absolute * paths, and existing URI strings. Line number fragments (e.g., #L123) are preserved. diff --git a/com.microsoft.copilot.eclipse.feature/feature.xml b/com.microsoft.copilot.eclipse.feature/feature.xml index a9f0b117..f53843fa 100644 --- a/com.microsoft.copilot.eclipse.feature/feature.xml +++ b/com.microsoft.copilot.eclipse.feature/feature.xml @@ -2,7 +2,7 @@ diff --git a/com.microsoft.copilot.eclipse.repository/category.xml b/com.microsoft.copilot.eclipse.repository/category.xml index b9b1f538..394c11c3 100644 --- a/com.microsoft.copilot.eclipse.repository/category.xml +++ b/com.microsoft.copilot.eclipse.repository/category.xml @@ -1,6 +1,6 @@ - + diff --git a/com.microsoft.copilot.eclipse.swtbot.test/META-INF/MANIFEST.MF b/com.microsoft.copilot.eclipse.swtbot.test/META-INF/MANIFEST.MF index 9ccba384..8fbc5c1a 100644 --- a/com.microsoft.copilot.eclipse.swtbot.test/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.swtbot.test/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: com.microsoft.copilot.eclipse.swtbot.test Bundle-SymbolicName: com.microsoft.copilot.eclipse.swtbot.test;singleton:=true -Bundle-Version: 0.18.0.qualifier +Bundle-Version: 0.20.0.qualifier Bundle-Vendor: GitHub Copilot Bundle-RequiredExecutionEnvironment: JavaSE-17 Automatic-Module-Name: com.microsoft.copilot.eclipse.swtbot.test diff --git a/com.microsoft.copilot.eclipse.swtbot.test/test-plans/cls-session-persistence/cls-session-persistence.md b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/cls-session-persistence/cls-session-persistence.md index 454c5b8b..813bffab 100644 --- a/com.microsoft.copilot.eclipse.swtbot.test/test-plans/cls-session-persistence/cls-session-persistence.md +++ b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/cls-session-persistence/cls-session-persistence.md @@ -181,6 +181,34 @@ This feature integrates CLS (Copilot Language Server) server-side session persis --- +### TC-008: Cancelled terminal tool call stays cancelled after restoration + +**Type:** `Regression` +**Priority:** `P0` + +#### Preconditions +- Copilot Chat is open in Agent mode +- A workspace is open so the `run_in_terminal` tool can execute +- A model that supports tool calls is selected + +#### Steps +1. Send a message that makes Copilot use the `run_in_terminal` tool to perform a longer-running task (e.g. "run a command that takes a while, such as `ping -n 30 127.0.0.1`") +2. While the terminal tool call is still running (spinner active on the tool status), click Cancel on the chat response +3. Verify the terminal tool call status updates to the **cancelled** icon (no longer spinning) +4. Click "New Chat" to start a fresh conversation +5. Open chat history and select the original conversation to restore it + +#### Expected Result +- After restoration, the terminal tool call still shows the **cancelled** icon +- The tool call status does **not** revert to running/spinning (no rotating/ongoing indicator reappears) +- The cancelled status is consistent between the live cancel and the restored view + +#### 📸 Key Screenshots +- [ ] **After cancel** — Terminal tool call showing the cancelled icon (not spinning) +- [ ] **After restore** — Same terminal tool call restored with the cancelled icon, not reverted to running + +--- + ## Screenshots Checklist > Consolidated list of all key screenshot moments. @@ -195,3 +223,5 @@ This feature integrates CLS (Copilot Language Server) server-side session persis - [ ] `TC-006` Restored history with successful follow-up and no 400 error - [ ] `TC-007` Original conversation showing assistant reply - [ ] `TC-007` Restored conversation with correctly attributed messages and no duplicates +- [ ] `TC-008` Cancelled terminal tool call showing cancelled icon after cancel +- [ ] `TC-008` Restored terminal tool call still cancelled, not reverted to running diff --git a/com.microsoft.copilot.eclipse.swtbot.test/test-plans/context-compress/context-compress.md b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/context-compress/context-compress.md new file mode 100644 index 00000000..e3b52987 --- /dev/null +++ b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/context-compress/context-compress.md @@ -0,0 +1,163 @@ +# Auto Context Compression + +## Overview +Verifies the **Auto Compress** feature that automatically compresses long +conversations to keep context usage within the model's limit. Auto Compress +is always enabled (no user-facing preference). While compression is in +progress, the chat view shows a "Compacting conversation..." spinner below +the latest Copilot turn, and the context size donut updates once it +completes. + +Entry points: +- **Copilot Chat view** → latest Copilot turn (spinner banner appears here). +- **Copilot Chat view** → control bar **Context Size Donut** (updates after + compression completes). + +--- + +## Prerequisites + +- Eclipse IDE with the GitHub Copilot for Eclipse plugin installed (built from + the branch containing the staged Auto Compress changes). +- A valid GitHub Copilot subscription is active (authentication completed). +- A model that supports a finite context window is selected (so the donut and + compression can be exercised — e.g. Claude Sonnet 4.6 or GPT-4.1). +- The Copilot Chat view is open and visible. + +--- + +## Test Cases + +### TC-001: Compacting banner appears when compression starts + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- The Copilot Chat view is open with a new conversation. + +#### Steps +1. Start a conversation and drive the context usage toward the model limit — + for example, attach several large files and/or run multiple tool-heavy + turns until the **Context Size Donut** approaches its warning threshold + (≥90 %). +2. Continue sending messages until the conversation goes over the threshold + so the server initiates automatic compression. +3. Observe the latest Copilot turn while the server processes the request. + +#### Expected Result +- A small banner appears **below the latest Copilot turn** containing: + - An animated spinner. + - The status text **"Compacting conversation..."**. +- The chat view layout refreshes so the banner is fully visible (not clipped). +- No error dialogs are shown. + +#### 📸 Key Screenshots +- [ ] **Compacting banner** — spinner + "Compacting conversation..." text + rendered under the latest Copilot turn. + +--- + +### TC-002: Compacting banner is dismissed and context donut updates on completion + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- TC-001 has been executed and the "Compacting conversation..." banner is + currently visible. + +#### Steps +1. Wait for the server to finish compression (typically a few seconds). +2. Observe the latest Copilot turn after compression completes. +3. Hover the **Context Size Donut** in the chat view control bar. + +#### Expected Result +- The "Compacting conversation..." banner is removed from the Copilot turn. +- The chat view scroller relayouts cleanly (no leftover blank space, no + clipping). +- The Context Size Donut updates to reflect the new, smaller token usage + (the ring's filled portion shrinks). +- The **Context Window** popup shows the post-compression token breakdown + consistent with the new total. +- The subsequent reply continues to stream normally on top of the freshly + compressed history. + +#### 📸 Key Screenshots +- [ ] **After completion** — Copilot turn without the banner. +- [ ] **Donut after compression** — Context Size Donut showing reduced usage. +- [ ] **Context Window popup** — Token breakdown after compression. + +--- + +### TC-003: Cancelling a chat hides the compacting banner + +**Type:** `Edge Case` +**Priority:** `P1` + +#### Preconditions +- A conversation is set up so the next send will trigger compression + (as in TC-001). + +#### Steps +1. Send the message that triggers compression and wait for the + "Compacting conversation..." banner to appear. +2. While the banner is showing, click the **Cancel** (stop) button in the + chat input action bar. + +#### Expected Result +- The send button is restored from its stop/cancel state back to its normal + send state. +- The "Compacting conversation..." banner is removed from the latest Copilot + turn. +- Any buffered reply text that arrived just before cancellation is rendered + (no missing trailing line). +- The chat view relayouts cleanly so the flushed reply is fully visible. +- The user can immediately send a new message in the same conversation. + +#### 📸 Key Screenshots +- [ ] **After cancel** — banner gone, send button reset, any buffered reply + visible. + +--- + +### TC-004: Compacting banner only updates the matching conversation + +**Type:** `Edge Case` +**Priority:** `P2` + +#### Preconditions +- Two conversations exist in chat history: *Conversation A* (about to + trigger compression) and *Conversation B* (short, well under the limit). + +#### Steps +1. In *Conversation A*, send a message that triggers compression and wait + for the "Compacting conversation..." banner to appear. +2. Without waiting for completion, open chat history and switch to + *Conversation B*. +3. Inspect *Conversation B* for any compaction banner. +4. Switch back to *Conversation A*. + +#### Expected Result +- *Conversation B* never shows a "Compacting conversation..." banner — the + compaction status is scoped to *Conversation A* only. +- When you return to *Conversation A*, its state is consistent with the + compression outcome (banner cleared if it completed in the meantime; new + reply continues to stream if still in progress). +- No errors or stale spinners are left behind in either conversation. + +#### 📸 Key Screenshots +- [ ] **Conversation B during A's compaction** — no banner shown. + +--- + +## Screenshots Checklist +> Consolidated list of all key screenshot moments. + +- [ ] `TC-001` Compacting banner under latest Copilot turn. +- [ ] `TC-002` Copilot turn after compaction completes (banner gone). +- [ ] `TC-002` Context Size Donut after compaction (reduced usage). +- [ ] `TC-002` Context Window popup with post-compaction token breakdown. +- [ ] `TC-003` State after cancel — banner gone, send button reset, buffered + reply visible. +- [ ] `TC-004` Conversation B during Conversation A's compaction (no banner). diff --git a/com.microsoft.copilot.eclipse.swtbot.test/test-plans/editor-indentation-preferences/editor-indentation-preferences.md b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/editor-indentation-preferences/editor-indentation-preferences.md new file mode 100644 index 00000000..eab55438 --- /dev/null +++ b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/editor-indentation-preferences/editor-indentation-preferences.md @@ -0,0 +1,168 @@ +# Editor Indentation Preferences for Inline Completions + +## Overview +When Copilot produces an **inline completion (ghost text)**, the indentation it +suggests (tab character vs. spaces and the tab width) should follow the +platform's **default text editor preferences** instead of always defaulting to +spaces with a tab size of 4. + +The formatting options are resolved by `FormatOptionProvider` and sent on each +completion request as `CompletionDocument.insertSpaces` / `tabSize` by +`CompletionProvider`. For Java and C/C++ projects the language-specific +formatter settings continue to apply. For every other case — an unknown +language, a file with no extension, or a file with no project — the provider +now reads the Eclipse text editor preferences +`org.eclipse.ui.editors/spacesForTabs` and `org.eclipse.ui.editors/tabWidth`. +If those preferences cannot be read it falls back to the previous hardcoded +defaults (spaces, tab width 4). + +> **Important:** these options affect **inline completions only**, not the +> Agent-mode file create/edit tools. The verification must therefore be done +> by triggering ghost-text completions in an editor, not by asking Agent mode +> to write a file. + +These preferences are configured under +**Preferences → General → Editors → Text Editors**: +- **"Insert spaces for tabs"** maps to `spacesForTabs`. +- **"Displayed tab width"** maps to `tabWidth`. + +Entry points: +- Window → Preferences → General → Editors → Text Editors +- Typing in a text editor to trigger an inline completion (ghost text) + +Not exercised: +- Direct unit-level invocation of `FormatOptionProvider` (covered by + `FormatOptionProviderTests`). +- Agent-mode file create/edit tools (they do not consult these options). +- Java/C-specific formatter configuration screens. + +--- + +## Prerequisites + +- Eclipse IDE with the GitHub Copilot for Eclipse plugin installed and + activated. +- The user is signed in to GitHub Copilot and inline completions are enabled. +- A workspace with at least one open project that is **neither a Java nor a + C/C++ project** (a General/empty project), so the editor text preferences + are the deciding factor. +- Knowledge of the current values of **Preferences → General → Editors → + Text Editors → "Insert spaces for tabs"** and **"Displayed tab width"** so + they can be restored after testing. +- Because completion content is model-influenced, prefer a prompt/context that + reliably forces an **indented multi-line suggestion** (e.g. an opening + brace/block), and inspect the **raw whitespace** of the accepted text rather + than relying on the displayed tab width. + +--- + +## 1. Spaces configuration + +### TC-001: Inline completion uses spaces when "insert spaces for tabs" is on + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- A non-Java/non-C project is open in the workspace. +- A file whose language is unknown / has no extension (e.g. a file named + `sample` with code-like content) is open in the editor. + +#### Steps +1. Open **Preferences → General → Editors → Text Editors**, check + **"Insert spaces for tabs"**, set **"Displayed tab width"** to `2`, then + click **Apply and Close**. +2. In the editor, type content that forces an indented multi-line + continuation, for example an opening block and a newline: + `function greet() {` then press Enter so Copilot suggests the indented + body as ghost text. +3. Accept the inline completion (Tab). +4. Reveal whitespace ("Show whitespace characters") or inspect the raw bytes + of the inserted lines. + +#### Expected Result +- The accepted completion indents the body with **spaces** (not tabs), at + **2 spaces** per level, matching the configured tab width. +- No error dialog appears and the Eclipse error log has no formatting + exception. + +#### 📸 Key Screenshots +- [ ] **Editor preferences** — "Insert spaces for tabs" checked, tab width 2. +- [ ] **Accepted completion whitespace** — Indentation shown as 2-space groups. + +--- + +## 2. Tabs configuration + +### TC-002: Inline completion uses tabs, and switching the preference updates the next request + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- A non-Java/non-C project is open in the workspace. +- An unknown-language / extensionless file is open in the editor. + +#### Steps +1. Open **Preferences → General → Editors → Text Editors**, **uncheck** + "Insert spaces for tabs", set **"Displayed tab width"** to `4`, then click + **Apply and Close**. +2. In the editor, trigger an indented multi-line completion (as in TC-001) and + accept it. Reveal whitespace / inspect raw bytes. +3. Change editor preferences to **spaces**, tab width `2`. Apply and close. +4. Trigger another indented completion in the same or a new unknown-language + file and accept it. Reveal whitespace. + +#### Expected Result +- The first accepted completion indents with **tab characters** (`\t`). +- After switching the preference, the next completion indents with **2 + spaces**. +- The provider reads the current editor preference value on **each completion + request** rather than caching the first observed value. +- No error dialog appears and the Eclipse error log has no formatting + exception. + +#### 📸 Key Screenshots +- [ ] **Tabs completion** — Tab indentation under the tabs preference. +- [ ] **Spaces completion** — 2-space indentation after switching the preference. + +--- + +## 3. Regression — language-specific projects are unaffected + +### TC-003: Java completion still uses the Java formatter settings, not editor preferences + +**Type:** `Regression` +**Priority:** `P0` + +#### Preconditions +- A **Java** project is open in the workspace with its own + formatter/indentation settings (e.g., tabs for Java). +- Editor preferences (General → Text Editors) are set to a **different** + value than the Java formatter (e.g., spaces, tab width 2). +- A `.java` source file is open in the editor. + +#### Steps +1. In the Java file, trigger an indented multi-line inline completion (e.g. + inside a method body) and accept it. +2. Reveal whitespace / inspect raw bytes of the inserted lines. + +#### Expected Result +- The Java completion follows the **Java formatter** indentation settings, not + the generic text editor preferences. +- Only unknown/extensionless/projectless cases consult the editor + preferences; Java (and C/C++) behavior is unchanged. + +#### 📸 Key Screenshots +- [ ] **Java completion whitespace** — Indentation matches the Java formatter, + independent of the General text-editor preference. + +--- + +## Screenshots Checklist + +- [ ] TC-001 — Editor preferences (spaces, width 2) + accepted completion with + 2-space indentation. +- [ ] TC-002 — Tabs completion vs. spaces completion after a preference switch. +- [ ] TC-003 — Java completion indentation unchanged by the General + text-editor preference. diff --git a/com.microsoft.copilot.eclipse.swtbot.test/test-plans/file-operation-auto-approve/file-operation-auto-approve.md b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/file-operation-auto-approve/file-operation-auto-approve.md new file mode 100644 index 00000000..e5ddf4e8 --- /dev/null +++ b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/file-operation-auto-approve/file-operation-auto-approve.md @@ -0,0 +1,415 @@ +# File Operation Auto Approve + +## Overview +Tests the file-operation (read/write) auto-approve feature end-to-end: +configuring glob-pattern rules in the preference page, attaching context +files, then triggering Agent Mode tool calls and observing whether the +confirmation dialog appears or the operation runs automatically. + +Each test case exercises the full stack: preference store → CLS sync → +Agent Mode prompt → tool confirmation request → `ConfirmationService` → +`FileOperationConfirmationHandler` → dialog (or auto-approve) → file +operation execution. This mirrors the real user workflow: tweak settings, +attach files, chat with Copilot, observe behavior. + +Entry points exercised: +- **Preferences → GitHub Copilot → Tool Auto Approve** — the file + operation rule table (add / remove / toggle / reset). +- **Agent Mode chat** — sending prompts that trigger `copilot.read_file`, + `copilot.editFile`, `copilot.createFile`, or `copilot.deleteFile` tool + calls. +- **Confirmation dialog** — the button with session/global allow actions. +- **Attached files** — the context panel for user-attached files. + +--- + +## Prerequisites + +- Eclipse IDE with the GitHub Copilot for Eclipse plugin installed and + activated. +- A signed-in Copilot account on the host machine. +- Network access to `api.githubcopilot.com`. +- **Agent Mode** selected in the chat mode dropdown. +- A workspace with at least one Java project open (e.g., `demo`). +- No previous file-operation auto-approve rules beyond the defaults + (reset via "Reset to Defaults" before each scenario). +- "Auto approve file operations not covered by rules" is **unchecked** + unless the test specifies otherwise. + +--- + +## 1. Default behavior and dialog UI + +### TC-001: File read in workspace triggers confirmation dialog + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- Default rules are active (not modified). +- "Auto approve file operations not covered by rules" is **unchecked**. + +#### Steps +1. Open **Preferences → GitHub Copilot → Tool Auto Approve**. +2. Verify the "File Operation Auto Approve" section is visible with a + table showing default deny rules (e.g., `.github/instructions/*`, + `github-copilot/**/*`). +3. **Manually uncheck** "Auto approve file operations not covered by rules" + (system default is checked; uncheck it for this test). Close preferences. +4. Open the **Copilot Chat** view, select **Agent** mode. +5. Type: `read the file src/demo/App.java and summarize it`. +6. Wait for the agent to invoke the `copilot.read_file` tool. +7. Observe the confirmation dialog. Verify it shows: + - Title: **"Read file"**, message mentioning the file name. + - **"Allow Once"** button with dropdown, and a **"Skip"** button. +8. Click the dropdown arrow. Verify the menu contains: + - "Allow this file in this Session" + - "Always Allow" +9. Click **"Skip"**. +10. Verify the agent receives a dismiss result — no file content. + +#### Expected Result +- No matching allow rule → confirmation dialog appears. +- Dialog renders correctly with session/global actions. +- Skip prevents execution. + +#### 📸 Key Screenshots +- [ ] Preference page with default rules. +- [ ] Confirmation dialog with dropdown expanded. +- [ ] Agent turn after skip. + +--- + +## 2. Attached file auto-approval + +### TC-002: Attached file auto-approves; deny rule does not block attached files + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- **Manually uncheck** "Auto approve file operations not covered by rules" + (system default is checked; uncheck it for this test). + +#### Steps +1. Open preferences, add a deny rule `**/*.java` → **Deny**. + Apply and close. +2. Open `src/demo/App.java` in the editor. +3. Open the **Copilot Chat** view, select **Agent** mode. +4. Attach `App.java` via the context panel (paperclip / "Add Context"). +5. Type: `read App.java and explain what it does`. +6. Observe **no confirmation dialog** — the file is auto-approved + because it is attached, even though the deny rule matches. +7. Verify the agent reads and summarizes the file content. +8. In the **same conversation**, type: `now read Helper.java`. +9. Observe **confirmation dialog appears** — `Helper.java` is not + attached and the deny rule matches. + +#### Expected Result +- Attached file auto-approval takes precedence over deny rules. +- Non-attached files still respect rules normally. + +#### 📸 Key Screenshots +- [ ] Context panel showing attached `App.java`. +- [ ] Agent auto-approved read without dialog. +- [ ] Dialog appears for non-attached `Helper.java`. + +--- + +## 3. Session-level file approval + +### TC-003: Session approval — read, then write, then new conversation + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- **Manually uncheck** "Auto approve file operations not covered by rules" + (system default is checked; uncheck it so the initial read triggers a dialog). + +#### Steps +1. Ensure no custom rules exist for the test file. +2. In Agent Mode, type: `read src/demo/App.java`. +3. Confirmation dialog appears. +4. Click dropdown → **"Allow this file in this Session"**. +5. The file is read successfully. +6. In the **same conversation**, type: `read src/demo/App.java again`. +7. Observe **auto-approved** — session cache hit. +8. In the **same conversation**, type: `add a comment "// test" to + the top of src/demo/App.java`. +9. The agent invokes `copilot.editFile` for `App.java`. +10. Observe **auto-approved** — session approval is path-based, covers + both reads and writes. +11. Start a **new conversation** (click "New Chat"). +12. Type: `read src/demo/App.java`. +13. Observe **confirmation dialog appears** — session approvals do not + carry to new conversations. + +#### Expected Result +- Session approval: same file re-read auto-approves. +- Session approval: write to same file auto-approves. +- New conversation: resets session state. + +#### 📸 Key Screenshots +- [ ] First dialog: selecting "Allow this file in this Session". +- [ ] Write auto-approved in same conversation. +- [ ] New conversation: dialog reappears. + +--- + +## 4. Global rules — allow, deny, and "Always Allow" from dialog + +### TC-004: Glob allow and deny rules with unmatched toggle + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Steps +1. Open **Preferences → GitHub Copilot → Tool Auto Approve**. +2. Add rule: `**/*.java` → **Allow**. Click OK. +3. Add rule: `**/secret/**` → **Deny**. Click OK. +4. Enable **"Auto approve file operations not covered by rules"**. +5. Click **"Apply and Close"**. +6. In Agent Mode, type: `read src/demo/App.java`. +7. Observe **auto-approved** — matches `**/*.java` allow rule. +8. Type: `read src/secret/config.properties`. +9. Observe **confirmation dialog** — matches `**/secret/**` deny rule, + even though unmatched is enabled. +10. Click **"Skip"**. +11. Type: `read README.md`. +12. Observe **auto-approved** — no rule matches, unmatched fallback. +13. Open preferences, **uncheck** "Auto approve file operations not + covered by rules". Apply and close. +14. Type: `read README.md`. +15. Observe **confirmation dialog** — unmatched now disabled. + +#### Expected Result +- Allow glob rule auto-approves matching files. +- Deny glob rule blocks matching files even with unmatched enabled. +- Unmatched toggle controls fallback for non-matching files. + +#### 📸 Key Screenshots +- [ ] Preference page with both rules. +- [ ] `.java` auto-approved, `secret/**` denied, `README.md` varies. + +--- + +### TC-005: "Always Allow" persists as global rule and overrides deny + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- **Manually uncheck** "Auto approve file operations not covered by rules" + (system default is checked; uncheck it for this test). + +#### Steps +1. Open preferences, add deny rule for the file's absolute path + (e.g., `C:\\demo\src\demo\App.java`) → **Deny**. Apply and close. +2. In Agent Mode, trigger a file read for `App.java`. +3. Confirmation dialog appears (deny rule matches). +4. Click dropdown → **"Always Allow"**. +5. The file is read. +6. Open **Preferences → Tool Auto Approve**. +7. Verify the rule changed from **Deny → Allow** (no duplicate). +8. Close preferences. +9. Start a **new conversation**. +10. Type: `read src/demo/App.java`. +11. Observe **auto-approved** — the updated global rule persists. + +#### Expected Result +- "Always Allow" writes/updates the file path as a global allow rule. +- Overrides existing deny rule (case-insensitive match, no duplicates). +- Persists across conversations. + +#### 📸 Key Screenshots +- [ ] Preference page: deny → allow transition. +- [ ] New conversation: auto-approved. + +--- + +## 5. Outside-workspace files and folder-level approval + +### TC-006: Outside-workspace file requires confirmation with folder +approval + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Steps +1. Enable "Auto approve file operations not covered by rules". +2. Add allow rule `**/*`. Apply and close. +3. In Agent Mode, type: `read C:\temp\test\file1.txt` + (path outside workspace). +4. Observe **confirmation dialog** — outside-workspace files always + require confirmation regardless of rules. +5. Verify the dialog offers folder-level approval: + - "Allow Once" + - "Allow files in 'test' folder in this Session" + - "Skip" +6. Click dropdown → **"Allow files in 'test' folder in this Session"**. +7. The file is read. +8. In the same conversation, trigger read for `C:\temp\test\file2.txt`. +9. Observe **auto-approved** — same folder. +10. Trigger read for `C:\temp\other\file3.txt`. +11. Observe **confirmation dialog** — different folder. + +#### Expected Result +- Outside-workspace files bypass rules, always show dialog. +- Folder-level session approval covers sibling files. +- Different folders still require confirmation. + +#### 📸 Key Screenshots +- [ ] Dialog with folder-level action. +- [ ] Same-folder auto-approved. +- [ ] Different-folder dialog. + +--- + +## 6. Session approval overrides deny rule + +### TC-007: Session approval overrides deny rule within conversation + +**Type:** `Edge Case` +**Priority:** `P1` + +#### Steps +1. Add deny rule `**/App.java` in preferences. Apply and close. +2. In Agent Mode, trigger a read for `src/demo/App.java`. +3. Confirmation dialog appears (deny rule). +4. Click dropdown → **"Allow this file in this Session"**. +5. The file is read. +6. In the same conversation, trigger another read for `App.java`. +7. Observe **auto-approved** — session approval checked before rules. + +#### Expected Result +- Session-level approval overrides global deny rules. + +--- + +## 7. Subagent inherits parent session approvals + +### TC-008: Session file approval applies to subagent + +**Type:** `Edge Case` +**Priority:** `P1` + +#### Preconditions +- No custom rules for the test file. +- "Auto approve file operations not covered by rules" is **unchecked**. + +#### Steps +1. In Agent Mode, trigger a read for `App.java`. +2. Confirmation dialog appears. +3. Select **"Allow this file in this Session"**. +4. The file is read. +5. In the **same conversation**, send a prompt that spawns a subagent + (e.g., `use a subagent to analyze App.java`). +6. The subagent invokes `copilot.read_file` for `App.java`. +7. Observe **auto-approved** — session approval carries to subagent. + +#### Expected Result +- Subagent shares parent conversation's session scope. + +--- + +## 8. Reset to Defaults + +### TC-009: Reset clears custom rules and reverts behavior + +**Type:** `Happy Path` +**Priority:** `P2` + +#### Steps +1. Add custom rules: `**/*.java` → Allow, `**/secret/*` → Deny. + Apply and close. +2. Verify in Agent Mode: `.java` files auto-approve. +3. Open preferences, click **"Reset to Defaults"** and confirm. +4. **Manually uncheck** "Auto approve file operations not covered by rules" + (Reset to Defaults only clears rules, it does not reset this checkbox). + Apply and close. +5. Verify only default deny rules remain (`.github/instructions/*`, + `github-copilot/**/*`). +5. Apply and close. +6. In Agent Mode, trigger a `.java` file read. +7. Observe **confirmation dialog** — custom allow rule removed. + +#### Expected Result +- Reset removes all custom rules and restores defaults. + +#### 📸 Key Screenshots +- [ ] Preference page after reset — only defaults. +- [ ] `.java` file shows confirmation dialog post-reset. + +--- + +## 9. Customization file reads (skills, instructions, prompts, agents) + +Reading a Copilot customization file is always auto-approved, even with +"Auto approve file operations not covered by rules" **unchecked** and even +when a deny rule would otherwise match (e.g. the default `.github/instructions/*` +rule). The exemption is read-only and covers both workspace and user-global +(`~/.copilot`, `~/.claude`, `~/.agents`) locations. Recognized files: +`//**` (the whole skill folder, including helper files), +`*.instructions.md`, `*.prompt.md`, `*.agent.md`, and the fixed names +`copilot-instructions.md`, `git-commit-instructions.md`, `AGENTS.md`, `CLAUDE.md`. + +### TC-010: Customization reads auto-approve; edits and ordinary files still prompt + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- "Auto approve file operations not covered by rules" is **unchecked**. +- The project contains `.github/skills/demo/SKILL.md` (whose body also tells + Copilot to read a sibling `notes.md`), `.github/instructions/coding.instructions.md`, + and `.github/copilot-instructions.md`. + +#### Steps +1. In Agent Mode, invoke the demo skill (or ask Copilot to read + `.github/skills/demo/SKILL.md`). +2. Observe **no confirmation** for `SKILL.md` **or** the referenced `notes.md`. +3. Type: `read the project instructions and summarize them`. +4. Observe **no confirmation** for `coding.instructions.md` — even though the + default `.github/instructions/*` deny rule matches. +5. Type: `read .github/copilot-instructions.md`. +6. Observe **no confirmation**. +7. Type: `add a comment line to .github/skills/demo/SKILL.md`. +8. Observe **confirmation dialog appears** — editing is not exempt. +9. Type: `read src/demo/App.java`. +10. Observe **confirmation dialog appears** — ordinary files are unaffected. + +#### Expected Result +- Reads of skill files (and their helpers), instruction/prompt/agent files, and + the fixed well-known files auto-approve with no dialog. +- Editing a customization file still prompts. +- Ordinary (non-customization) reads still prompt. + +#### 📸 Key Screenshots +- [ ] Skill `SKILL.md` + `notes.md` read with no confirmation. +- [ ] Instruction file read with no confirmation despite the deny rule. +- [ ] Edit to `SKILL.md` shows a confirmation dialog. + +--- + +### TC-011: User-global customization files auto-approve + +**Type:** `Edge Case` +**Priority:** `P1` + +#### Preconditions +- "Auto approve file operations not covered by rules" is **unchecked**. +- A user-global skill exists, e.g. `~/.copilot/skills/demo-global/SKILL.md`. + +#### Steps +1. In Agent Mode, invoke the global demo skill (or ask Copilot to read its + `SKILL.md`). +2. Observe **no confirmation** — global customization files are exempt even + though they live outside the workspace (an ordinary outside-workspace file + would still prompt, per TC-006). + +#### Expected Result +- User-global customization reads auto-approve without a dialog. + +#### 📸 Key Screenshots +- [ ] Global skill read with no confirmation. diff --git a/com.microsoft.copilot.eclipse.swtbot.test/test-plans/file-system/local-file-edit-and-create-tools.md b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/file-system/local-file-edit-and-create-tools.md new file mode 100644 index 00000000..0e55246e --- /dev/null +++ b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/file-system/local-file-edit-and-create-tools.md @@ -0,0 +1,286 @@ +# Support Editing and Creating Local Files Outside the Workspace + +## Overview +Verify that Copilot Agent mode can edit and create local filesystem files that are outside the Eclipse workspace, and +that those changes are surfaced through the file change summary bar with the same review actions users expect for +workspace files. + +This covers the user-visible flow for the `insert_edit_into_file` and `create_file` tools when the target is an +absolute local path rather than an Eclipse `IFile`. + +Entry points: +- Window -> Show View -> Other... -> Copilot -> Copilot Chat -> Agent mode + +Not exercised: +- Direct unit-level invocation of the file tools. +- Workspace-file edit coverage. +- Low-level compare editor APIs; this plan verifies the Compare UI through the summary bar. + +--- + +## Prerequisites + +- Eclipse IDE with the GitHub Copilot for Eclipse plugin installed and activated. +- The user is signed in to GitHub Copilot and Agent mode is available in the Copilot Chat view. +- A writable local directory outside the Eclipse workspace is available, for example: + - Windows: `%TEMP%\\copilot-eclipse-local-file-tools` + - macOS/Linux: `/tmp/copilot-eclipse-local-file-tools` +- The local directory contains an existing text file named `existing-local-file.txt` with this content: + `before local edit` +- The local directory does not contain `created-local-file.txt` before the create-file test starts. + +--- + +## 1. Edit an existing local file outside the workspace + +### TC-001: Agent edits a local file and exposes the change in the summary bar + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- The Eclipse workbench is open. +- Copilot Chat is open in a fresh or cleared conversation. +- `existing-local-file.txt` exists outside the workspace and contains `before local edit`. + +#### Steps +1. Open **Copilot Chat** from `Window -> Show View -> Other... -> Copilot -> Copilot Chat`. +2. Switch the chat mode selector to **Agent**. +3. Send a prompt that asks Agent mode to edit the external local file by absolute path, for example: + `Edit so its entire content is exactly "after local edit".` +4. If Copilot asks for tool confirmation, approve the file edit operation. +5. Wait for the Agent turn to complete. +6. Verify the file change summary bar appears in the Chat view. +7. Verify the summary bar includes `existing-local-file.txt` and displays a local filesystem path for that file. +8. Click **View Diff** for `existing-local-file.txt`. +9. Verify the Compare editor opens and shows the original content `before local edit` against the modified content + `after local edit`. +10. Close the Compare editor. + +#### Expected Result +- Copilot completes the edit without reporting that the file is outside the workspace or cannot be edited. +- The local file on disk contains `after local edit`. +- The summary bar lists `existing-local-file.txt` even though it is not an Eclipse workspace file. +- The Compare editor opens from **View Diff** and shows the correct before/after content. +- No error dialog is shown. The Eclipse error log has no uncaught exception from `insert_edit_into_file`, local file + path handling, or compare editor creation. + +#### Key Screenshots +- [ ] **Agent edit prompt** -- Copilot Chat in Agent mode with the absolute local file path visible. +- [ ] **Summary bar after local edit** -- The changed local file appears in the file change summary bar. +- [ ] **Local file Compare editor** -- The Compare editor shows `before local edit` vs. `after local edit`. + +#### Notes on failure modes +- The edit succeeds on disk but the file is missing from the summary bar -- the local `Path` change may not be tracked + by the summary bar model. +- **View Diff** does nothing or throws an error -- local files may not be routed through the local Compare input path. +- The diff baseline shows the modified content on both sides -- the original content may not have been cached before + applying the edit. + +### TC-002: Keep clears the local file change and later edits use a new baseline + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- The Eclipse workbench is open. +- Copilot Chat is open in a fresh or cleared conversation. +- `existing-local-file.txt` exists outside the workspace and contains `before local edit`. +- Agent mode has edited `existing-local-file.txt` so it contains `after local edit`, and the file is listed in the + summary bar. + +#### Steps +1. Click **Keep** for `existing-local-file.txt` in the file change summary bar. +2. Verify the file is removed from the summary bar. +3. Send another Agent prompt to edit the same absolute file path so its entire content is exactly `second local edit`. +4. Approve the edit if prompted and wait for the turn to complete. +5. Click **View Diff** for `existing-local-file.txt`. +6. Verify the Compare editor shows `after local edit` as the original content and `second local edit` as the modified + content. + +#### Expected Result +- **Keep** accepts the current local file content and clears the tracked change. +- The next edit of the same local file starts a new diff baseline from the kept content. +- The file remains accessible through the summary bar and Compare editor after the second edit. + +#### Key Screenshots +- [ ] **After Keep** -- The summary bar no longer lists the local file. +- [ ] **Second local diff** -- The Compare editor shows the kept content as the new baseline. + +### TC-003: Undo restores the original local file content + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- The Eclipse workbench is open. +- Copilot Chat is open in a fresh or cleared conversation. +- `existing-local-file.txt` exists outside the workspace and contains `before local edit`. +- Agent mode has edited `existing-local-file.txt` so it contains `after local edit`, and the file is listed in the + summary bar. + +#### Steps +1. Click **Undo** for `existing-local-file.txt` in the file change summary bar. +2. Verify the file is removed from the summary bar. +3. Open `existing-local-file.txt` from the local filesystem and inspect its content. + +#### Expected Result +- **Undo** restores the file to the original content captured before the tracked edit. +- The file is removed from the summary bar after undo completes. +- No error dialog is shown and the Eclipse error log has no local file undo exception. + +#### Key Screenshots +- [ ] **Before Undo** -- The summary bar lists the edited local file. +- [ ] **After Undo** -- The summary bar no longer lists the local file and the file content is restored. + +--- + +## 2. Create a new local file outside the workspace + +### TC-004: Agent creates a local file and opens it from the summary bar + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- `created-local-file.txt` does not exist in the local test directory. +- Copilot Chat is open in Agent mode. + +#### Steps +1. Send a prompt that asks Agent mode to create the external local file by absolute path, for example: + `Create with the exact content "created local content".` +2. If Copilot asks for tool confirmation, approve the file create operation. +3. Wait for the Agent turn to complete. +4. Verify `created-local-file.txt` exists on disk and contains `created local content`. +5. Verify the file change summary bar lists `created-local-file.txt`. +6. Click **View Diff** for `created-local-file.txt`. +7. Verify Eclipse opens `created-local-file.txt` in an editor and shows `created local content`. + +#### Expected Result +- Copilot creates the local file without requiring it to be inside an Eclipse workspace project. +- The created file is listed in the summary bar. +- The created local file can be opened from the summary bar. +- No error dialog is shown and the Eclipse error log has no local file create or editor-open exception. + +#### Key Screenshots +- [ ] **Agent create prompt** -- Copilot Chat in Agent mode with the absolute create path visible. +- [ ] **Summary bar after local create** -- The created local file appears in the file change summary bar. +- [ ] **Created local file editor** -- The external local file opens in an editor with the created content. + +### TC-005: Undo removes a created local file + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- The Eclipse workbench is open. +- Copilot Chat is open in Agent mode. +- `created-local-file.txt` does not exist in the local test directory. +- Agent mode has created `created-local-file.txt` with content `created local content`, and the file is listed in the + summary bar. + +#### Steps +1. Click **Undo** for `created-local-file.txt` in the file change summary bar. +2. Verify the file is removed from the summary bar. +3. Verify `created-local-file.txt` no longer exists on disk. + +#### Expected Result +- **Undo** for a created local file deletes the file, matching the create-file semantics. +- The summary bar no longer lists the created file after undo completes. +- No error dialog is shown and the Eclipse error log has no local file deletion exception. + +#### Key Screenshots +- [ ] **Before created-file Undo** -- The summary bar lists `created-local-file.txt`. +- [ ] **After created-file Undo** -- The summary bar is clear and the file is absent from disk. + +--- + +## 3. Navigate to local files from tool links + +### TC-006: Tool result links open local files outside the workspace + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- The Eclipse workbench is open. +- Copilot Chat is open in Agent mode. +- The local test directory outside the workspace exists and contains `existing-local-file.txt`. + +#### Steps +1. Send a prompt that causes Agent mode to reference or edit `existing-local-file.txt` by absolute path. +2. When the tool call appears in the Chat view, click the file path link for `existing-local-file.txt`. +3. Verify Eclipse opens `existing-local-file.txt` in an editor. + +#### Expected Result +- File links for paths outside the Eclipse workspace open the local file in an Eclipse editor. +- No error dialog is shown and the Eclipse error log has no local file navigation exception. + +#### Key Screenshots +- [ ] **Local file tool link** -- The tool result shows a clickable absolute path outside the workspace. +- [ ] **External local file editor** -- The external local file opens in an Eclipse editor. + +### TC-007: Workspace directory and project links reveal in the Project Explorer + +**Type:** `Happy Path` +**Priority:** `P1` + +#### Preconditions +- The Eclipse workbench is open with at least one project (e.g., `demo`) that contains a sub-folder (e.g., `src`). +- The **Project Explorer** view is open. +- Copilot Chat is open in Agent mode. + +#### Steps +1. Send a prompt that causes Agent mode to reference the workspace sub-folder by path (for example, ask it to list the + contents of the `src` folder so the tool result renders a directory link). +2. When the tool call appears in the Chat view, click the directory link for the `src` folder. +3. Verify the `src` folder is selected and revealed in the **Project Explorer** (no external browser opens). +4. Send a prompt that causes Agent mode to reference the project root, then click the project link in the tool result. +5. Verify the project is selected and revealed in the **Project Explorer**. + +#### Expected Result +- Clicking a workspace folder or project link reveals and selects that resource in the Project Explorer. +- No external browser or web page is opened for directory/project links. +- No error dialog is shown and the Eclipse error log has no navigation exception. + +#### Key Screenshots +- [ ] **Directory tool link** -- The tool result shows a clickable workspace folder link. +- [ ] **Folder revealed** -- The `src` folder is selected and revealed in the Project Explorer. +- [ ] **Project revealed** -- The project root is selected and revealed in the Project Explorer. + +#### Notes on failure modes +- Clicking the directory link opens a browser or does nothing -- the folder/project branch may not route through + `UiUtils.revealInExplorer`. +- The resource is opened in an editor instead of being revealed -- folder/project types may be incorrectly treated as + files. + +### TC-008: File URI link with a line-number fragment opens the external local file + +**Type:** `Edge Case` +**Priority:** `P2` + +#### Preconditions +- The Eclipse workbench is open. +- Copilot Chat is open in Agent mode. +- The local test directory outside the workspace exists and contains `existing-local-file.txt` with multiple lines. + +#### Steps +1. Send a prompt that causes Agent mode to reference `existing-local-file.txt` by absolute path with a line-number + fragment (for example, a link ending in `#L10` or a `file:` URI with a `#L10` fragment). +2. When the tool call appears in the Chat view, click the file path link. +3. Verify Eclipse opens `existing-local-file.txt` in an editor (the trailing line-number fragment is treated as a + fragment, not part of the file name). + +#### Expected Result +- The line-number fragment is stripped when resolving the local path, so the correct external file opens. +- Eclipse does not report a missing file named `existing-local-file.txt#L10` or a path-resolution error. +- No error dialog is shown and the Eclipse error log has no local file navigation exception. + +#### Key Screenshots +- [ ] **Fragment file link** -- The tool result shows a clickable local path with a `#L10` fragment. +- [ ] **External file opened** -- The external local file opens in an Eclipse editor despite the fragment. + +#### Notes on failure modes +- Eclipse reports the file cannot be found -- the `#` fragment may not be stripped before resolving the local path. +- A relative-path or `https:` link is unexpectedly opened as a local file -- the URI-scheme guard in + `FileUtils.getLocalFilePath` may be bypassed. diff --git a/com.microsoft.copilot.eclipse.swtbot.test/test-plans/global-auto-approve/global-auto-approve.md b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/global-auto-approve/global-auto-approve.md new file mode 100644 index 00000000..09cf4171 --- /dev/null +++ b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/global-auto-approve/global-auto-approve.md @@ -0,0 +1,125 @@ +# Global Auto-Approve + +## Overview + +Tests the Global Auto-Approve (YOLO) feature: enabling/disabling it via the +preference page and verifying that all tool confirmations are bypassed when +active. + +Entry points exercised: +- **Preferences → GitHub Copilot → Tool Auto Approve → Global Auto-Approve** — + the "Automatically approve ALL tool invocations" checkbox with its + confirmation dialog. +- **Agent Mode chat** — any tool call (terminal, file operation, MCP) to + observe confirmation bypass. + +--- + +## Prerequisites + +- Eclipse IDE with the GitHub Copilot for Eclipse plugin installed and + activated. +- A signed-in Copilot account on the host machine. +- Network access to `api.githubcopilot.com`. +- **Agent Mode** selected in the chat mode dropdown. +- Global Auto-Approve is **disabled** at the start of each scenario. + +--- + +## 1. Enable Global Auto-Approve — confirmation dialog required + +### TC-001: Enable Global Auto-Approve → confirmation dialog required +→ all tools skip confirmation + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Steps +1. Open **Preferences → Tool Auto Approve → Global Auto-Approve** section. +2. Click the **"Automatically approve ALL tool invocations"** checkbox. +3. Observe that a **confirmation dialog immediately appears** asking the user + to confirm this dangerous setting. +4. Verify the dialog title and message warn about the risk. +5. Click **Cancel** — verify the checkbox remains **unchecked**. +6. Click the checkbox again, then click **OK** in the confirmation dialog. +7. Verify the checkbox is now **checked**. +8. Click **"Apply and Close"**. +9. In Agent Mode, send a prompt that would normally trigger a confirmation + (e.g., an MCP tool call or a terminal command). +10. Observe that **no confirmation dialog appears** — all tools auto-approve. + +#### Expected Result +- Enabling YOLO mode requires an explicit confirmation dialog. +- Cancelling the dialog keeps the checkbox unchecked. +- When enabled, all tool confirmations (terminal, file operations, MCP) + are bypassed. + +#### 📸 Key Screenshots +- [ ] Confirmation dialog when enabling YOLO mode. +- [ ] Checkbox unchecked after Cancel. +- [ ] Checkbox checked after OK. +- [ ] Agent Mode: tool runs without any confirmation dialog. + +--- + +## 2. Disable Global Auto-Approve — no confirmation needed + +### TC-002: Disable Global Auto-Approve → no dialog → tools require +confirmation again + +**Type:** `Happy Path` +**Priority:** `P1` + +#### Preconditions +- Global Auto-Approve is **enabled**. + +#### Steps +1. Open **Preferences → Tool Auto Approve → Global Auto-Approve** section. +2. Click the **"Automatically approve ALL tool invocations"** checkbox to + uncheck it. +3. Observe that **no confirmation dialog appears** — turning it off is safe + and does not require confirmation. +4. Verify the checkbox is now **unchecked**. +5. Click **"Apply and Close"**. +6. In Agent Mode, trigger any tool. +7. Observe that the **confirmation dialog appears** — YOLO mode is off. + +#### Expected Result +- Disabling YOLO mode does not require a confirmation dialog. +- Tools require confirmation again after disabling. + +#### 📸 Key Screenshots +- [ ] Checkbox unchecked without any dialog. +- [ ] Tool shows confirmation dialog again. + +--- + +## 3. Global Auto-Approve overrides all tool categories + +### TC-003: Global Auto-Approve bypasses terminal deny rules, MCP +rules, and file operation rules + +**Type:** `Edge Case` +**Priority:** `P1` + +#### Preconditions +- Global Auto-Approve is **enabled**. +- Terminal has a custom **Deny** rule for `curl`. + +#### Steps +1. In Agent Mode, trigger a `curl` terminal command (normally blocked by the + deny rule). +2. Observe **auto-approved** — YOLO mode bypasses the deny rule. +3. Trigger an MCP tool call with no prior MCP approval. +4. Observe **auto-approved** — YOLO mode bypasses MCP confirmation. +5. Trigger a file operation on a file not in the attached context. +6. Observe **auto-approved** — YOLO mode bypasses file operation confirmation. + +#### Expected Result +- Global Auto-Approve bypasses ALL tool categories regardless of individual + rules or approval lists. + +#### 📸 Key Screenshots +- [ ] `curl` auto-approved despite deny rule. +- [ ] MCP tool auto-approved without prior approval. +- [ ] File operation auto-approved. diff --git a/com.microsoft.copilot.eclipse.swtbot.test/test-plans/mcp-auto-approve/mcp-auto-approve.md b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/mcp-auto-approve/mcp-auto-approve.md new file mode 100644 index 00000000..0659ec51 --- /dev/null +++ b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/mcp-auto-approve/mcp-auto-approve.md @@ -0,0 +1,265 @@ +# MCP Auto-Approve + +## Overview + +Tests the MCP tool auto-approve feature end-to-end: configuring rules in the +preference page, then triggering Agent Mode tool calls and observing whether +the confirmation dialog appears or the tool runs automatically. + +Each test case exercises the full stack: preference store → +`McpConfirmationHandler` → dialog (or auto-approve) → tool execution. This +mirrors the real user workflow: tweak settings, chat with Copilot via an MCP +tool, observe behavior. + +Entry points exercised: +- **Preferences → GitHub Copilot → Tool Auto Approve → MCP Configuration** — + the "Trust MCP tool annotations" checkbox and the server/tool tree. +- **Agent Mode chat** — sending prompts that trigger MCP tool calls. +- **Confirmation dialog** — the split-dropdown button with session/global + allow actions for tool and server scope. + +--- + +## Prerequisites + +- Eclipse IDE with the GitHub Copilot for Eclipse plugin installed and + activated. +- A signed-in Copilot account on the host machine. +- Network access to `api.githubcopilot.com`. +- **At least one MCP server configured** in the Copilot MCP settings, with + at least one tool available. Note the server name and a tool name for use + in the prompts below. +- **Agent Mode** selected in the chat mode dropdown. +- All MCP auto-approve preferences at their defaults before each scenario: + no globally approved servers/tools, "Trust MCP tool annotations" unchecked. + +--- + +## 1. Default behavior: confirmation dialog appears for MCP tools + +### TC-001: MCP tool call with no rules → confirmation dialog + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- No global approved servers or tools. +- "Trust MCP tool annotations" is **unchecked**. + +#### Steps +1. Open **Preferences → GitHub Copilot → Tool Auto Approve**. +2. Navigate to the **MCP Configuration** section. +3. Verify the server/tool tree shows no tools checked. +4. Confirm "Trust MCP tool annotations" is unchecked. +5. Close preferences. +6. Open the **Copilot Chat** view and select **Agent** mode. +7. Send a prompt that triggers the known MCP tool (e.g., `use to + `). +8. Wait for the Copilot turn — the agent should invoke the MCP tool. +9. Observe the **confirmation dialog** that appears in the chat panel. +10. Verify the dialog shows: + - Bold title: `Run '' tool from '' MCP server`. + - A description of the MCP tool call. + - A blue **"Allow Once ▾"** split-dropdown button and a **"Skip"** button. +11. Click the dropdown arrow on "Allow Once ▾". +12. Verify the dropdown contains: + - "Allow '' in this Session" + - "Always Allow ''" + - "Allow tools from '' in this Session" + - "Always Allow tools from ''" +13. Click **"Skip"**. +14. Verify the tool was **NOT** executed. + +#### Expected Result +- Confirmation dialog appears for MCP tools with no auto-approve rules. +- Dropdown shows tool-level and server-level scoped actions. +- Skipping prevents execution. + +#### 📸 Key Screenshots +- [ ] MCP preference section with no checked tools. +- [ ] Confirmation dialog with dropdown expanded showing all actions. +- [ ] Agent turn after skip — no tool output. + +--- + +## 2. Session allow for a specific tool + +### TC-002: "Allow tool in Session" → same tool auto-approves → new +conversation resets + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- No global approved servers or tools. +- "Trust MCP tool annotations" is **unchecked**. + +#### Steps +1. In Agent Mode, send a prompt that triggers the MCP tool. +2. Confirmation dialog appears. +3. Click the dropdown arrow and select **"Allow '' in this + Session"**. +4. The tool executes. +5. In the **same conversation**, send another prompt that triggers the same + tool. +6. Observe that **no confirmation dialog appears** — the tool is + session-approved. +7. Start a **new conversation** (click "New Chat" or equivalent). +8. Send a prompt that triggers the same MCP tool. +9. Observe that the **confirmation dialog appears again** — session approvals + do not carry over. + +#### Expected Result +- Session approval auto-approves the same tool within the conversation. +- New conversation resets session approvals. + +#### 📸 Key Screenshots +- [ ] First dialog: selecting "Allow '' in this Session". +- [ ] Second invocation (same conversation): auto-approved, no dialog. +- [ ] New conversation: dialog reappears. + +--- + +## 3. Session allow for an entire server + +### TC-003: "Allow all tools from server in Session" → all tools from +that server auto-approve + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- No global approved servers or tools. +- "Trust MCP tool annotations" is **unchecked**. + +#### Steps +1. In Agent Mode, send a prompt that triggers any tool from the target + MCP server. +2. Confirmation dialog appears. +3. Click the dropdown and select **"Allow all tools from '' + in this Session"**. +4. The tool executes. +5. In the **same conversation**, send prompts that trigger **different tools** + from the same server. +6. Observe that **none of them** show a confirmation dialog. +7. Start a **new conversation**. +8. Trigger any tool from the same server. +9. Observe that the **confirmation dialog appears again**. + +#### Expected Result +- Server-level session approval covers all tools from that server. +- New conversation resets the session approval. + +#### 📸 Key Screenshots +- [ ] Dropdown: selecting "Allow tools from '' in this Session". +- [ ] Second tool from same server: auto-approved. +- [ ] New conversation: dialog reappears. + +--- + +## 4. "Always Allow" for a specific tool — global persistence + +### TC-004: "Always Allow ''" → persists across conversations → +visible in preferences tree + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- No global approved servers or tools. +- "Trust MCP tool annotations" is **unchecked**. + +#### Steps +1. In Agent Mode, trigger the MCP tool. +2. Confirmation dialog appears. +3. Click the dropdown and select **"Always Allow ''"**. +4. The tool executes. +5. Open **Preferences → Tool Auto Approve → MCP Configuration**. +6. Verify the specific tool is **checked** in the server/tool tree. +7. Close preferences. +8. Start a **new conversation**. +9. Send a prompt that triggers the same MCP tool. +10. Observe that **no confirmation dialog appears** — the global rule persists. + +#### Expected Result +- "Always Allow" writes the tool key to the global preference store. +- The tool appears checked in the preference tree. +- The approval persists across conversations. + +#### 📸 Key Screenshots +- [ ] Dropdown: selecting "Always Allow ''". +- [ ] Preference tree: tool checked. +- [ ] New conversation: tool auto-approved without dialog. + +--- + +## 5. "Always Allow" for an entire server — global persistence + +### TC-005: "Always Allow all tools from ''" → server shown +checked in preferences + +**Type:** `Happy Path` +**Priority:** `P1` + +#### Preconditions +- No global approved servers or tools (clear any rules written by TC-004 + if running in sequence). +- "Trust MCP tool annotations" is **unchecked**. + +#### Steps +1. In Agent Mode, trigger any MCP tool. +2. Confirmation dialog appears. +3. Click the dropdown and select **"Always Allow all tools from + ''"**. +4. The tool executes. +5. Open **Preferences → Tool Auto Approve → MCP Configuration**. +6. Verify the server node is **checked** in the tree. +7. Close preferences. +8. Start a **new conversation** and trigger different tools from the same + server. +9. Observe all tools **auto-approve without dialog**. + +#### Expected Result +- "Always Allow" for server writes to the global servers list. +- The server row appears checked in the preference tree. +- All tools from the server auto-approve in new conversations. + +#### 📸 Key Screenshots +- [ ] Dropdown: "Always Allow all tools from ''". +- [ ] Preference tree: server node checked. +- [ ] New conversation: all server tools auto-approved. + +--- + +## 6. Trust MCP tool annotations — read-only tools auto-approve + +### TC-006: Enable "Trust MCP tool annotations" → tools with +readOnlyHint=true auto-approve + +**Type:** `Happy Path` +**Priority:** `P1` + +#### Preconditions +- An MCP tool is available with `readOnlyHint=true` and `openWorldHint=false` + in its annotations. + +#### Steps +1. Open **Preferences → Tool Auto Approve → MCP Configuration**. +2. Check **"Trust MCP tool annotations"**. +3. Click **"Apply and Close"**. +4. In Agent Mode, send a prompt that triggers the read-only MCP tool. +5. Observe that **no confirmation dialog appears** — the tool auto-approves + because it is annotated as read-only and closed-world. +6. Send a prompt that triggers an MCP tool that does NOT have + `readOnlyHint=true` (or has `openWorldHint=true`). +7. Observe that the **confirmation dialog appears** — only strictly + read-only + closed-world tools bypass confirmation. + +#### Expected Result +- Tools with `readOnlyHint=true` AND `openWorldHint=false` auto-approve. +- All other tools still show the confirmation dialog. + +#### 📸 Key Screenshots +- [ ] Preference: "Trust MCP tool annotations" checked. +- [ ] Read-only tool: auto-approved. +- [ ] Non-read-only tool: confirmation dialog shown. diff --git a/com.microsoft.copilot.eclipse.swtbot.test/test-plans/preference-pages/preference-pages.md b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/preference-pages/preference-pages.md new file mode 100644 index 00000000..08555695 --- /dev/null +++ b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/preference-pages/preference-pages.md @@ -0,0 +1,81 @@ +# GitHub Copilot Preference Pages + +## Overview +Covers behavior shared by **all** GitHub Copilot preference pages +(**Preferences → GitHub Copilot → …**), independent of any single feature. +Every Copilot page is hosted in the same JFace `PreferenceDialog`, so concerns +like dialog sizing, layout stability, and navigation are cross-cutting. + +JFace grows the shared dialog to the **tallest** page visited and never shrinks +it again. To keep the dialog a stable size, each Copilot page keeps its content +within a common target height — `PreferencePageUtils.STANDARD_CONTENT_HEIGHT`. +Pages whose natural content is taller (e.g. **Tool Auto Approve**, which stacks +four rule sections) scroll within a height-capped `ScrolledComposite` instead of +ballooning the dialog. The same constant drives `McpPreferencePage`'s two groups, +so the pages settle at a consistent size. + +Entry points exercised: +- **Preferences → GitHub Copilot** — the root category page (only hyperlinks; no + sign-in, always valid). A stable baseline for size comparisons. +- **Preferences → GitHub Copilot → Tool Auto Approve** — the tallest page; the + regression magnet for dialog ballooning. +- Other child pages (MCP, Completions, Chat, …) — for navigation stability. + +--- + +## Prerequisites +- Eclipse IDE with the GitHub Copilot for Eclipse plugin installed and activated. +- No sign-in required: the pages below render independently of language-server + data. + +--- + +## 1. Dialog size stability + +### TC-001: Opening a tall page does not balloon the Preferences dialog + +**Type:** `Regression` +**Priority:** `P1` + +#### Steps +1. Open **Window → Preferences** and select **GitHub Copilot** (root page). Note + the dialog's size. +2. In the tree, select **GitHub Copilot → Tool Auto Approve**. +3. Observe the dialog does **not** grow toward screen height — it stays close to + the root page's size. +4. Confirm all four sections (Terminal, File Operation, MCP, Global) are + reachable by scrolling **within the page** using a single page-level vertical + scrollbar. +5. Navigate to a couple of sibling pages (e.g. **MCP**, **Completions**) and back + to Tool Auto Approve; the dialog size stays stable throughout. +6. Close Preferences. + +#### Expected Result +- The Preferences dialog stays a normal, stable size as the selection moves + between Copilot pages; Tool Auto Approve does not balloon toward screen height. +- Tool Auto Approve content is reachable via the page's own single vertical + scrollbar; no second (dialog-level) scrollbar appears. + +#### Reference measurements (Eclipse 2025-03, macOS) +- Root **GitHub Copilot** page dialog height: **~551px**. +- **Tool Auto Approve** dialog height (fixed by the height cap): **~656px** — + deterministic and screen-independent. +- Pre-fix, Tool Auto Approve ballooned to ~screen height (≈986px or + screen-clamped). + +#### 📸 Key Screenshots +- [ ] Dialog on the root **GitHub Copilot** page. +- [ ] Dialog on **Tool Auto Approve** — only slightly taller, content scrolling + within the page (single page scrollbar). + +--- + +## Notes +- Page height is **data-independent** (table/tree height hints are fixed), so MCP + servers loading asynchronously does not change the page height. +- The height cap is unified via `PreferencePageUtils.STANDARD_CONTENT_HEIGHT`, + shared by `AutoApprovePreferencePage` (scroller cap) and `McpPreferencePage` + (two stacked groups). Keep the pages within this height when adding content. +- Use the root **GitHub Copilot** page as the size baseline — it is always valid + and needs no sign-in, whereas the MCP page can enter an invalid state in an + unauthenticated sandbox and pop a JFace validation dialog. diff --git a/com.microsoft.copilot.eclipse.swtbot.test/test-plans/run-in-terminal/run-in-terminal.md b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/run-in-terminal/run-in-terminal.md new file mode 100644 index 00000000..fb6de18c --- /dev/null +++ b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/run-in-terminal/run-in-terminal.md @@ -0,0 +1,112 @@ +# Run In Terminal Tool + +## Overview +Verify that Agent mode invokes `run_in_terminal` with commands that preserve multi-line shell syntax and execute +build commands from the correct imported project root. These cases guard against command flattening and wrong +working-directory selection in terminal tool calls. + +--- + +## Test Cases + +### TC-001: Multi-line PowerShell command executes correctly + +**Type:** `Regression` +**Priority:** `P0` + +#### Preconditions +- Eclipse IDE is open with the GitHub Copilot for Eclipse plugin installed and activated. +- The user is signed in to GitHub Copilot. +- Copilot Chat is open in Agent mode. +- The terminal shell used by `run_in_terminal` is PowerShell. +- Terminal tool confirmation is enabled, or the tester can inspect the generated command before allowing execution. + +#### Steps +1. Start a new Copilot Chat conversation in Agent mode. +2. Send a prompt that asks the agent to run this exact multi-line PowerShell command in the terminal and report the + output: + ```powershell + 1..3 | ForEach-Object { + Write-Output "item=$_" + } + ``` +3. When the `run_in_terminal` confirmation appears, verify that the displayed command keeps the pipeline and block + body as a multi-line command, including the opening `{`, the `Write-Output` line, and the closing `}`. +4. Allow the command to run. +5. Wait for the terminal tool call to complete and inspect the terminal output returned to the agent. + +#### Expected Result +- The command executes successfully without PowerShell parser errors caused by dropped newlines, missing braces, or + truncated block content. +- The output contains exactly these item lines, in order: + ```text + item=1 + item=2 + item=3 + ``` +- The agent response reports the same three output lines and does not claim the command failed. + +#### 📸 Key Screenshots +- [ ] **Multi-line command confirmation** — `run_in_terminal` confirmation showing the full multi-line PowerShell + command. +- [ ] **Multi-line command output** — Terminal or agent output showing `item=1`, `item=2`, and `item=3`. + +--- + +### TC-002: Maven verify command runs from imported project root + +**Type:** `Regression` +**Priority:** `P0` + +#### Preconditions +- Eclipse IDE is open with the GitHub Copilot for Eclipse plugin installed and activated. +- The user is signed in to GitHub Copilot. +- Copilot Chat is open in Agent mode. +- A Maven project is imported into the Eclipse workspace and visible in Project Explorer. +- The imported project root contains `pom.xml` and either a Maven wrapper (`mvnw` / `mvnw.cmd`) or uses a system + `mvn` installation. +- Terminal tool confirmation is enabled, or the tester can inspect the generated command before allowing execution. + +#### Steps +1. Import a Maven project into the Eclipse workspace if one is not already present. +2. Start a new Copilot Chat conversation in Agent mode. +3. Ask the agent to run Maven `verify` for the imported project. +4. When the `run_in_terminal` confirmation appears, inspect the generated command before allowing it. +5. Allow the command to run after confirming the tool will execute from the imported Maven project root. Valid evidence + includes either an explicit `cd ""` in the command or a terminal prompt/working directory + that already points at the imported project root. +6. Wait for the terminal tool call to complete or reach the normal build result for that project. + +#### Expected Result +- The terminal executes Maven `verify` from the imported Maven project root path. +- The execution directory is the project directory that contains the imported project's `pom.xml`, not the Eclipse + workspace root, a parent folder, or an unrelated project. +- The tool satisfies this either by starting the terminal with the imported project root as its working directory or by + using an equivalent explicit directory change before running `verify`, such as: + ```powershell + cd "" + .\mvnw.cmd verify + ``` + or: + ```powershell + cd "" + mvn verify + ``` +- The terminal starts Maven from that project root, so Maven resolves the expected `pom.xml`. + +#### 📸 Key Screenshots +- [ ] **Imported Maven project** — Project Explorer showing the selected/imported Maven project root with `pom.xml`. +- [ ] **Verify execution location** — `run_in_terminal` confirmation or terminal prompt showing the command will execute + from the imported Maven project root. +- [ ] **Verify command output** — Terminal output showing Maven started from the selected project root. + +--- + +## Screenshots Checklist +> Consolidated list of all key screenshot moments. + +- [ ] `TC-001` Multi-line command confirmation +- [ ] `TC-001` Multi-line command output +- [ ] `TC-002` Imported Maven project +- [ ] `TC-002` Verify execution location +- [ ] `TC-002` Verify command output diff --git a/com.microsoft.copilot.eclipse.swtbot.test/test-plans/subagent/subagent.md b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/subagent/subagent.md index ed950cc6..49b667ab 100644 --- a/com.microsoft.copilot.eclipse.swtbot.test/test-plans/subagent/subagent.md +++ b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/subagent/subagent.md @@ -15,6 +15,7 @@ Entry points exercised: - Agent mode with a prompt that triggers `run_subagent`. - Chat history panel: switching to a different conversation and back. - Cancel (stop) button during subagent execution. +- Cancel button on a subagent tool-confirmation dialog. - `conversation/destroy` LSP call on session switch. Not exercised: @@ -222,3 +223,47 @@ Not exercised: #### Key Screenshots - [ ] **After restore** — conversation unchanged, no extra messages. + +--- + +## 6. Tool-confirmation dialog cancel layout + +### TC-007: Subagent panel collapses after confirmation dialog is cancelled + +**Type:** `Regression` +**Priority:** `P1` + +#### Preconditions +- The Chat view is open in Agent mode. +- A new conversation (fresh session). +- The selected agent triggers a tool that requires confirmation + (e.g., a command that needs to run in the terminal). + +#### Steps +1. Send a prompt that triggers subagent execution where the subagent + wants to run a command (e.g., `scan for CVEs`, or + `run ls in the terminal`). +2. Wait for the subagent's tool **confirmation dialog** to appear inside + the subagent card (Allow / Skip buttons). +3. Click **Skip** on the confirmation dialog. +4. Observe the subagent card area after the dialog disposes. + +#### Expected Result +- The subagent panel resizes/collapses to fit its remaining content. +- **No empty/blank gap** is left at the bottom of the subagent area where + the confirmation dialog used to be (the bug in #169). +- A skip label/message is shown where appropriate, and the scroller + minimum height is recomputed in a single layout pass. +- The send button returns to the send state. + +#### Key Screenshots +- [ ] **Confirmation dialog visible** — Allow / Skip buttons shown + inside the subagent card. +- [ ] **After skip** — subagent panel collapsed with no empty area below. + +#### Notes on failure modes +- Empty area left below the subagent card → `cancelConfirmation()` did not + trigger `requestRefreshScrollerLayout()`; the `ScrolledComposite` + `setMinHeight()` was never recomputed after the dialog disposal. +- Verify the Allow path is unaffected: clicking **Allow** on a + separate invocation should still lay out correctly (no regression). diff --git a/com.microsoft.copilot.eclipse.swtbot.test/test-plans/terminal-auto-approve/terminal-auto-approve.md b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/terminal-auto-approve/terminal-auto-approve.md new file mode 100644 index 00000000..180783a4 --- /dev/null +++ b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/terminal-auto-approve/terminal-auto-approve.md @@ -0,0 +1,551 @@ +# Terminal Auto Approve + +## Overview +Tests the terminal command auto-approve feature end-to-end: configuring rules +in the preference page, then triggering Agent Mode tool calls and observing +whether the confirmation dialog appears or the command runs automatically. + +Each test case exercises the full stack: preference store → CLS sync → +Agent Mode prompt → tool confirmation request → `ConfirmationService` → +`TerminalConfirmationHandler` → dialog (or auto-approve) → terminal +execution. This mirrors the real user workflow: tweak settings, chat with +Copilot, observe behavior. + +Entry points exercised: +- **Preferences → GitHub Copilot → Tool Auto Approve** — the terminal + rule table (add / remove / toggle / reset). +- **Agent Mode chat** — sending prompts that trigger `run_in_terminal` + tool calls. +- **Confirmation dialog** — the split-dropdown button with session/global + allow actions. + +--- + +## Prerequisites + +- Eclipse IDE with the GitHub Copilot for Eclipse plugin installed and + activated. +- A signed-in Copilot account on the host machine. +- Network access to `api.githubcopilot.com`. +- **Agent Mode** selected in the chat mode dropdown. +- No previous auto-approve rules beyond the defaults (reset via + "Reset to Defaults" before each scenario). + +--- + +## 1. Default deny rules block dangerous commands + +### TC-001: Default deny rules + Agent Mode terminal call + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Preconditions +- Default rules are active (not modified). +- "Auto approve commands not covered by rules" is **unchecked**. + +#### Steps +1. Open **Preferences → GitHub Copilot → Tool Auto Approve**. +2. Verify the "Terminal Auto Approve" section is visible with a table + showing default deny rules (rm, rmdir, del, kill, curl, wget, eval, + chmod, chown, and the regex rules for subshells / backticks / braces). +3. Confirm "Auto approve commands not covered by rules" is unchecked. +4. Close preferences. +5. Open the **Copilot Chat** view and select **Agent** mode. +6. Wait for the model picker to resolve. +7. Type the prompt: `please run curl https://example.com`. +8. Wait for a Copilot turn to stream — the agent should invoke the + `run_in_terminal` tool with a `curl` command. +9. Observe the confirmation dialog that appears in the chat panel. +10. Verify the dialog shows: + - Bold title: **"Run command in terminal"** + - Message: *"The tool is about to run the following command in the + terminal."* + - The command text in a scrollable panel with `bg-command-panel` + background. + - A blue **"Allow Once ▾"** split-dropdown button and a **"Skip"** + button. +11. Click the dropdown arrow on "Allow Once ▾". +12. Verify the dropdown menu contains: + - "Allow 'curl' in this Session" + - "Always Allow 'curl'" + - "Allow this exact command in this Session" (if the full command + differs from "curl") + - "Always Allow this exact command" + - "Allow all commands in this Session" +13. Click **"Skip"**. +14. Verify the command was NOT executed — the agent receives a dismiss + result and continues without terminal output. + +#### Expected Result +- Default deny rule for `curl` causes the confirmation dialog to appear. +- The dialog renders correctly with split-dropdown actions. +- Skipping prevents execution. + +#### 📸 Key Screenshots +- [ ] Preference page with default rules visible. +- [ ] Confirmation dialog with dropdown expanded showing all actions. +- [ ] Agent turn after skip — no terminal output. + +--- + +## 2. Custom allow rule auto-approves matching commands + +### TC-002: Add allow rule → Agent auto-approves → verify execution + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Steps +1. Open **Preferences → GitHub Copilot → Tool Auto Approve**. +2. Click **"Add..."** in the Terminal Auto Approve section. +3. Enter `systeminfo` as command, select **"Allow"**, click OK. +4. Verify `systeminfo` appears in the table with "Allow" status. +5. Click **"Apply and Close"**. +6. In Agent Mode chat, type: `run systeminfo to show my computer info`. +7. Wait for the agent to invoke `run_in_terminal`. +8. Observe that **no confirmation dialog appears** — the command runs + directly. +9. Wait for the tool call to complete — the agent should report terminal + output containing system information. +10. Open preferences again and verify the rule is still present. + +#### Expected Result +- The custom allow rule causes the `systeminfo` command to auto-approve. +- No confirmation dialog is shown. +- The terminal runs the command and the agent receives output. + +#### 📸 Key Screenshots +- [ ] Preference page with `systeminfo` Allow rule added. +- [ ] Agent turn showing "✔ Ran run_in_terminal tool" without a + confirmation dialog in between. +- [ ] Agent response containing system information output. + +--- + +## 3. Session "Allow command name" persists within conversation + +### TC-003: Allow name in Session → same command auto-approves → new +conversation resets + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Steps +1. Ensure no custom rules for `echo` exist (only defaults). +2. In Agent Mode, type: `run echo hello world`. +3. Confirmation dialog appears (echo has no matching rule and unmatched + is disabled). +4. Click the dropdown arrow and select **"Allow 'echo' in this Session"**. +5. The command executes. +6. In the **same conversation**, type: `run echo second message`. +7. Observe that **no confirmation dialog appears** — the command + auto-approves because `echo` is session-approved. +8. Verify the agent shows terminal output for both commands. +9. Start a **new conversation** (click "New Chat" or equivalent). +10. Type: `run echo third message`. +11. Observe that the **confirmation dialog appears again** — session + approvals do not carry over to new conversations. + +#### Expected Result +- First invocation: dialog shown, user selects session allow. +- Second invocation (same conversation): auto-approved. +- Third invocation (new conversation): dialog shown again. + +#### 📸 Key Screenshots +- [ ] First dialog with dropdown showing "Allow 'echo' in this Session". +- [ ] Second invocation auto-approved — no dialog. +- [ ] New conversation — dialog reappears. + +--- + +## 4. "Always Allow" persists globally + +### TC-004: Always Allow command name → persists across conversations +and appears in preferences + +**Type:** `Happy Path` +**Priority:** `P0` + +#### Steps +1. Ensure no custom rules for `dir` exist. +2. In Agent Mode, type: `list files in current directory`. +3. Confirmation dialog appears for the `dir` (or `ls`) command. +4. Click the dropdown and select **"Always Allow 'dir'"**. +5. The command executes. +6. Open **Preferences → Tool Auto Approve**. +7. Verify `dir` appears in the rules table with **"Allow"** status. +8. Close preferences. +9. Start a **new conversation**. +10. Type: `show me what files are here` (triggers `dir` again). +11. Observe that **no confirmation dialog appears** — the global rule + persists. + +#### Expected Result +- The "Always Allow" action writes the command name to the preference + store. +- The rule appears in the preference page UI. +- The rule survives across conversations. + +#### 📸 Key Screenshots +- [ ] Dropdown selection: "Always Allow 'dir'". +- [ ] Preference page showing `dir` as Allow rule. +- [ ] New conversation: `dir` auto-approved. + +--- + +## 5. Exact command vs. command name distinction + +### TC-005: Exact command Session approval only matches the same +command line + +**Type:** `Edge Case` +**Priority:** `P1` + +#### Steps +1. In Agent Mode, type: `run echo hello world`. +2. Confirmation dialog appears. +3. Click dropdown and select **"Allow this exact command in this + Session"**. +4. The command executes. +5. In the same conversation, type: `run echo hello world` again. +6. Observe **auto-approved** — exact same command line. +7. In the same conversation, type: `run echo different text`. +8. Observe **confirmation dialog appears** — different command line, + even though command name `echo` is the same. + +#### Expected Result +- Exact command approval is strict: only the identical command line + is auto-approved. +- A different argument string requires separate confirmation. + +#### 📸 Key Screenshots +- [ ] First dialog: selecting "Allow this exact command in this Session". +- [ ] Same command: auto-approved. +- [ ] Different arguments: dialog appears again. + +--- + +## 6. Simple command hides redundant exact-command actions + +### TC-006: Single-word command shows minimal dropdown + +**Type:** `Edge Case` +**Priority:** `P1` + +#### Steps +1. In Agent Mode, trigger a single-word command like `ipconfig` + (or `hostname`). +2. Confirmation dialog appears. +3. Click the dropdown arrow. +4. Count the menu items. + +#### Expected Result +- "Allow 'ipconfig' in this Session" — present. +- "Always Allow 'ipconfig'" — present. +- "Allow this exact command in this Session" — **NOT present** + (redundant: exact command = command name for single-word commands). +- "Always Allow this exact command" — **NOT present**. +- "Allow all commands in this Session" — present. + +--- + +## 7. Unmatched auto-approve toggle + +### TC-007: Enable unmatched auto-approve → unknown commands pass +through → disable → they require confirmation again + +**Type:** `Happy Path` +**Priority:** `P1` + +#### Steps +1. Open **Preferences → Tool Auto Approve**. +2. Check **"Auto approve commands not covered by rules"**. +3. Click **"Apply and Close"**. +4. In Agent Mode, type: `run hostname`. +5. Observe **auto-approved** — `hostname` has no matching rule but + unmatched auto-approve is enabled. +6. Open preferences again. +7. **Uncheck** "Auto approve commands not covered by rules". +8. Click **"Apply and Close"**. +9. In the same or new conversation, type: `run hostname`. +10. Observe **confirmation dialog appears**. + +#### Expected Result +- With unmatched enabled: unknown commands auto-approve. +- With unmatched disabled: unknown commands require confirmation. + +#### 📸 Key Screenshots +- [ ] Preference: "Auto approve commands not covered by rules" checked. +- [ ] `hostname` auto-approved. +- [ ] Preference: unchecked. +- [ ] `hostname` shows confirmation dialog. + +--- + +## 8. Regex rule integration + +### TC-008: Add a case-insensitive regex allow rule → verify it +matches in Agent Mode + +**Type:** `Happy Path` +**Priority:** `P2` + +#### Steps +1. Open **Preferences → Tool Auto Approve**. +2. Click **"Add..."**, enter `/^npm\b/i`, select **"Allow"**, click OK. +3. Click **"Apply and Close"**. +4. In Agent Mode, type: `install lodash using npm`. +5. Agent invokes `npm install lodash`. +6. Observe **auto-approved** — regex `/^npm\b/i` matches. +7. Type: `run NPM run build` (uppercase). +8. Observe **auto-approved** — case-insensitive flag `/i` matches. + +#### Expected Result +- The regex allow rule auto-approves matching commands. +- Case-insensitive flag works correctly. + +--- + +## 9. "Allow all commands in this Session" — blanket approval + +### TC-009: Allow all → every subsequent terminal call auto-approves +in this conversation + +**Type:** `Happy Path` +**Priority:** `P1` + +#### Steps +1. In Agent Mode, trigger any terminal command. +2. Confirmation dialog appears. +3. Click dropdown and select **"Allow all commands in this Session"**. +4. The command executes. +5. In the same conversation, send multiple prompts that trigger + different terminal commands (e.g., "run dir", "run echo test", + "run ipconfig"). +6. Observe that **none of them** show a confirmation dialog. +7. Start a **new conversation**. +8. Trigger any terminal command. +9. Observe that the **confirmation dialog appears again**. + +#### Expected Result +- "Allow all" is a blanket session-scoped approval. +- Every terminal command in the same conversation auto-approves. +- New conversations start fresh. + +--- + +## 10. Reset to Defaults clears custom rules + +### TC-010: Add custom rules → Reset → verify Agent Mode behavior +reverts + +**Type:** `Happy Path` +**Priority:** `P2` + +#### Steps +1. Open preferences and add `echo` as Allow, `javac` as Allow. +2. Apply and close. +3. Verify in Agent Mode: `echo hello` auto-approves. +4. Open preferences again. +5. Click **"Reset to Defaults"** and confirm. +6. Verify only default deny rules remain — `echo` and `javac` are gone. +7. Apply and close. +8. In Agent Mode, trigger `echo hello`. +9. Observe **confirmation dialog appears** — the custom allow rule was + removed. + +#### Expected Result +- Reset removes all custom rules. +- Commands that were previously allowed now require confirmation. + +#### 📸 Key Screenshots +- [ ] Preference page after adding custom rules. +- [ ] Preference page after reset — only defaults. +- [ ] `echo hello` shows confirmation dialog post-reset. + +--- + +## 11. Already-approved names filtered from dropdown + +### TC-011: Session-approved command name hidden from dropdown +actions in multi-command scenario + +**Type:** `Edge Case` +**Priority:** `P1` + +#### Steps +1. In Agent Mode, trigger a command that includes `echo` + (e.g., "run echo hello"). +2. Confirmation dialog appears. +3. Select **"Allow 'echo' in this Session"** from the dropdown. +4. The command executes. +5. In the same conversation, send a prompt that triggers a + multi-command like `echo test && curl https://example.com`. +6. Confirmation dialog appears (because `curl` is a default deny + rule). +7. Click the dropdown arrow. + +#### Expected Result +- The dropdown shows **"Allow 'curl' in this Session"** and + **"Always Allow 'curl'"**. +- `echo` does **NOT** appear in the command-name actions — it was + already session-approved. +- "Allow all commands in this Session" is still shown. +- Exact command actions (if shown) refer to the full multi-command + string, not individual parts. + +#### 📸 Key Screenshots +- [ ] First dialog: approving `echo` in session. +- [ ] Second dialog: dropdown showing only `curl`, not `echo`. + +--- + +### TC-012: Global-approved command name hidden from dropdown + +**Type:** `Edge Case` +**Priority:** `P1` + +#### Steps +1. Open **Preferences → Tool Auto Approve**. +2. Add `echo` as **Allow** rule. Apply and close. +3. In Agent Mode, trigger `echo hello && hostname`. +4. Confirmation dialog appears (because `hostname` has no matching + rule and unmatched is disabled). +5. Click the dropdown arrow. + +#### Expected Result +- The dropdown shows **"Allow 'hostname' in this Session"** and + **"Always Allow 'hostname'"**. +- `echo` does **NOT** appear — it is globally allowed. +- "Allow all commands in this Session" is still shown. + +--- + +## 13. Subagent inherits parent session approvals + +### TC-013: Session approval in main agent applies to subagent calls + +**Type:** `Edge Case` +**Priority:** `P1` + +#### Preconditions +- No custom allow rules for `echo` or `cat` (only defaults). +- "Auto approve commands not covered by rules" is **unchecked**. + +#### Steps +1. In Agent Mode, send a prompt that triggers `echo hello`. +2. Confirmation dialog appears. +3. Click dropdown and select **"Allow 'echo' in this Session"**. +4. The command executes. +5. In the **same conversation**, send a complex prompt that causes the + agent to spawn a **subagent** (e.g., `use a subagent to run echo + from subagent`). +6. The subagent invokes `run_in_terminal` with an `echo` command. +7. Observe that **no confirmation dialog appears** — the session + approval from the main agent carries over to the subagent. +8. Still in the subagent context, the subagent invokes a different + command (e.g., `cat somefile.txt`). +9. Observe that a **confirmation dialog appears** — `cat` was not + session-approved. + +#### Expected Result +- Subagent tool calls use the parent conversation's session rules. +- Commands approved in the main agent conversation auto-approve in + subagent context. +- Commands NOT approved still require confirmation in subagent context. + +#### 📸 Key Screenshots +- [ ] Main agent: approving `echo` in session. +- [ ] Subagent: `echo` auto-approved — no dialog. +- [ ] Subagent: `cat` shows confirmation dialog. + +--- + +### TC-014: Session approval in subagent carries back to main agent + +**Type:** `Edge Case` +**Priority:** `P1` + +#### Preconditions +- No custom allow rules for `hostname`. +- "Auto approve commands not covered by rules" is **unchecked**. + +#### Steps +1. In Agent Mode, send a complex prompt that triggers a **subagent**. +2. The subagent invokes `run_in_terminal` with `hostname`. +3. Confirmation dialog appears. +4. Click dropdown and select **"Allow 'hostname' in this Session"**. +5. The command executes in the subagent context. +6. After the subagent completes, continue in the **same conversation** + with the main agent. +7. Send a prompt that triggers `hostname` again (e.g., `what is my + hostname?`). +8. Observe that **no confirmation dialog appears** — the session + approval made during the subagent call is shared with the main + conversation. + +#### Expected Result +- Session approvals made during subagent execution are stored under + the parent conversation's session scope. +- The main agent benefits from approvals granted in subagent context. + +#### 📸 Key Screenshots +- [ ] Subagent: approving `hostname` in session. +- [ ] Main agent: `hostname` auto-approved — no dialog. + +--- + +### TC-015: "Allow all commands in this Session" in main agent covers subagent + +**Type:** `Edge Case` +**Priority:** `P2` + +#### Steps +1. In Agent Mode, trigger any terminal command. +2. Confirmation dialog appears. +3. Select **"Allow all commands in this Session"** from the dropdown. +4. In the **same conversation**, send a prompt that spawns a subagent + which runs multiple different terminal commands. +5. Observe that **none of them** show a confirmation dialog — the + blanket session approval covers subagent calls too. + +#### Expected Result +- "Allow all commands in this Session" is a blanket approval that + applies to both main agent and subagent tool calls within the + same conversation. + +--- + +## 14. Edge Cases + +### TC-016: "Always Allow" overrides existing deny rule in preferences + +**Type:** `Edge Case` +**Priority:** `P1` + +#### Steps +1. Open **Preferences → Tool Auto Approve**. +2. Click **"Add..."**, enter `curl`, select **"Deny"**, click OK. +3. Click **"Apply and Close"**. +4. In Agent Mode, type a prompt that triggers `curl` (e.g., `fetch + https://example.com using curl`). +5. Confirmation dialog appears (deny rule blocks it). +6. Click dropdown and select **"Always Allow curl"**. +7. The command executes. +8. Open **Preferences → Tool Auto Approve** again. +9. Verify the `curl` rule has been changed from **Deny → Allow**. +10. Start a **new conversation**, trigger `curl` again. +11. Observe **auto-approved** — the global allow rule now applies. + +#### Expected Result +- Clicking "Always Allow" in the dialog overrides an existing deny + rule in preferences, changing it from deny to allow. +- The updated rule persists across conversations. +- The preferences table reflects the updated rule. + +#### 📸 Key Screenshots +- [ ] Preferences: `curl → Deny` rule before override. +- [ ] Confirmation dialog: showing "Always Allow curl" action. +- [ ] Preferences: `curl → Allow` rule after override. +- [ ] New conversation: `curl` auto-approved without dialog. diff --git a/com.microsoft.copilot.eclipse.swtbot.test/test-plans/thinking-effort/thinking-effort.md b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/thinking-effort/thinking-effort.md index 02f9e900..3eacc8d1 100644 --- a/com.microsoft.copilot.eclipse.swtbot.test/test-plans/thinking-effort/thinking-effort.md +++ b/com.microsoft.copilot.eclipse.swtbot.test/test-plans/thinking-effort/thinking-effort.md @@ -79,3 +79,48 @@ Entry points: - Model A still shows **`High`**; Model B still shows **`Low`**. - Each model's effort is independent — changing one did not affect the other. +--- + +## TC-003: Thinking effort descriptions are fully readable in the hover card + +**Type:** `Regression` +**Priority:** `P1` + +Regression guard for +[issue #233](https://github.com/microsoft/copilot-for-eclipse/issues/233) / +[PR #234](https://github.com/microsoft/copilot-for-eclipse/pull/234). The hover +card previously clamped its width to a fixed maximum (`LONG_POPUP_WIDTH = 300`), +which truncated the longer per-level description text in the **Thinking effort** +section. The fix removes that cap so the hover shell uses its natural packed +width (only enforcing a `250` px minimum), letting every description wrap and +render in full. + +#### Preconditions +- A reasoning-capable model (e.g. Claude Sonnet 4.6) advertising multiple + effort levels, each with a descriptive sub-label (e.g. + `Low — Faster responses, less reasoning`, + `Medium — Balanced reasoning and speed`, + `High — Deeper reasoning, slower responses`). + +#### Steps +1. Open the Copilot Chat view and click the model picker to open the dropdown. +2. Hover over the reasoning-capable model to open its hover card. +3. Locate the **Thinking effort** section and read each effort level's + description line in full. +4. Visually compare the right edge of the longest description against the hover card border. + +#### Expected Result +- The hover card is wide enough to display the full description for every effort + level — no text is clipped, cut off, or replaced with an ellipsis at the right + edge. +- Each description ends with its natural last word (or wraps onto a second line) + rather than being truncated mid-word against the card border. +- The hover card width is never narrower than the `250` px minimum, so short + content still renders cleanly. + +#### 📸 Key Screenshots +- [ ] **Hover card — full descriptions** — Thinking effort section showing each + level's complete, untruncated description text. +- [ ] **Right-edge close-up** — the longest description's final word fully + visible inside the card border (no clipping/ellipsis). + diff --git a/com.microsoft.copilot.eclipse.terminal.api/META-INF/MANIFEST.MF b/com.microsoft.copilot.eclipse.terminal.api/META-INF/MANIFEST.MF index b6fe125a..75b5a994 100644 --- a/com.microsoft.copilot.eclipse.terminal.api/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.terminal.api/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: com.microsoft.copilot.eclipse.terminal.api Bundle-SymbolicName: com.microsoft.copilot.eclipse.terminal.api;singleton:=true -Bundle-Version: 0.18.0.qualifier +Bundle-Version: 0.20.0.qualifier Bundle-Vendor: GitHub Copilot Export-Package: com.microsoft.copilot.eclipse.terminal.api Automatic-Module-Name: com.microsoft.copilot.eclipse.terminal.api @@ -10,7 +10,8 @@ Bundle-ActivationPolicy: lazy Bundle-RequiredExecutionEnvironment: JavaSE-17 Import-Package: org.osgi.framework;version="[1.10.0,2.0.0)" Require-Bundle: org.eclipse.core.runtime;bundle-version="[3.30.0,4.0.0)", - com.microsoft.copilot.eclipse.core;bundle-version="0.15.0", + com.microsoft.copilot.eclipse.core;bundle-version="0.20.0", org.eclipse.jface, org.eclipse.swt, - org.eclipse.ui.workbench + org.eclipse.ui.workbench, + org.apache.commons.lang3;bundle-version="3.13.0" diff --git a/com.microsoft.copilot.eclipse.terminal.api/scripts/copilot-bash-integration.sh b/com.microsoft.copilot.eclipse.terminal.api/scripts/copilot-bash-integration.sh new file mode 100644 index 00000000..b36076c7 --- /dev/null +++ b/com.microsoft.copilot.eclipse.terminal.api/scripts/copilot-bash-integration.sh @@ -0,0 +1,45 @@ +# Copilot Shell Integration for Bash +# This script is loaded with bash --init-file when starting a terminal. + +__copilot_bash_integration_main() { + [ -n "${COPILOT_BASH_INTEGRATION:-}" ] && return + COPILOT_BASH_INTEGRATION=1 + + bind 'set enable-bracketed-paste on' 2>/dev/null || true + __copilot_prompt_initialized=0 + + __copilot_precmd() { + __copilot_status=$? + if [ "${__copilot_prompt_initialized:-0}" = "1" ]; then + printf '\033]7775;C;%s\007' "$__copilot_status" + else + __copilot_prompt_initialized=1 + fi + printf '\033]7775;A\007' + return "$__copilot_status" + } + + __copilot_prompt_end() { + printf '\033]7775;B\007' + } + + if [ -z "${__copilot_original_ps1:-}" ]; then + __copilot_original_ps1=${PS1:-'\$ '} + fi + + case "$(declare -p PROMPT_COMMAND 2>/dev/null)" in + declare\ -a*|declare\ -A*) + PROMPT_COMMAND=(__copilot_precmd "${PROMPT_COMMAND[@]}") + ;; + *) + if [ -n "${PROMPT_COMMAND:-}" ]; then + PROMPT_COMMAND="__copilot_precmd; ${PROMPT_COMMAND}" + else + PROMPT_COMMAND=__copilot_precmd + fi + ;; + esac + PS1="${__copilot_original_ps1}"'\[$(__copilot_prompt_end)\]' +} + +__copilot_bash_integration_main \ No newline at end of file diff --git a/com.microsoft.copilot.eclipse.terminal.api/scripts/copilot-powershell-integration.ps1 b/com.microsoft.copilot.eclipse.terminal.api/scripts/copilot-powershell-integration.ps1 new file mode 100644 index 00000000..5cc0c77e --- /dev/null +++ b/com.microsoft.copilot.eclipse.terminal.api/scripts/copilot-powershell-integration.ps1 @@ -0,0 +1,56 @@ +# Copilot Shell Integration for Windows PowerShell +# This script is loaded when starting a Copilot terminal. + +try { + $global:OutputEncoding = New-Object System.Text.UTF8Encoding $false + [Console]::InputEncoding = $global:OutputEncoding + [Console]::OutputEncoding = $global:OutputEncoding +} catch { + # Some hosts do not expose console encodings during startup. +} + +if (-not $global:COPILOT_SHELL_INTEGRATION) { + $global:COPILOT_SHELL_INTEGRATION = $true + $global:__copilot_original_prompt = (Get-Command prompt -CommandType Function).ScriptBlock + $global:__copilot_last_history_id = -1 + + function global:prompt { + $lastSuccess = $? + $lastExitCode = $LASTEXITCODE + $esc = [char]27 + $bel = [char]7 + $lastHistoryEntry = Get-History -Count 1 + $result = "" + + if ($global:__copilot_last_history_id -ne -1) { + if ($null -ne $lastHistoryEntry -and $lastHistoryEntry.Id -eq $global:__copilot_last_history_id) { + $result += "$esc]7775;C$bel" + } else { + if ($lastSuccess) { + $exitCode = 0 + } elseif ($null -ne $lastExitCode -and $lastExitCode -ne 0) { + $exitCode = $lastExitCode + } else { + $exitCode = 1 + } + $result += "$esc]7775;C;$exitCode$bel" + } + } + + $result += "$esc]7775;A$bel" + + if ($global:__copilot_original_prompt) { + $result += $global:__copilot_original_prompt.Invoke() + } else { + $result += "PS $($executionContext.SessionState.Path.CurrentLocation)> " + } + + $result += "$esc]7775;B$bel" + if ($null -ne $lastHistoryEntry) { + $global:__copilot_last_history_id = $lastHistoryEntry.Id + } else { + $global:__copilot_last_history_id = 0 + } + $result + } +} \ No newline at end of file diff --git a/com.microsoft.copilot.eclipse.terminal.api/scripts/copilot-sh-integration.sh b/com.microsoft.copilot.eclipse.terminal.api/scripts/copilot-sh-integration.sh deleted file mode 100644 index 4b365b14..00000000 --- a/com.microsoft.copilot.eclipse.terminal.api/scripts/copilot-sh-integration.sh +++ /dev/null @@ -1,32 +0,0 @@ -# Copilot Shell Integration for POSIX sh -# This script is sourced via ENV when starting a terminal. - -__copilot_sh_integration_main() { - # Avoid multiple initialization - [ -n "$COPILOT_SHELL_INTEGRATION" ] && return - COPILOT_SHELL_INTEGRATION=1 - - # OSC escape sequence: ESC ] 7775 ; C BEL - # This is invisible in terminal but detectable programmatically - __COPILOT_MARKER=$(printf '\033]7775;C\007') - - # The function that prints the marker - __copilot_precmd() { - printf '%s' "$__COPILOT_MARKER" - } - - # Save original PS1 only if PS1 is already set and not empty - if [ -z "$__copilot_original_ps1" ] && [ -n "$PS1" ]; then - __copilot_original_ps1=$PS1 - fi - - # Ensure PS1 has a value (POSIX shells may start without PS1) - : "${__copilot_original_ps1:=$ }" - - # Assemble PS1: - # (invisible OSC sequence) - # - PS1="\$(__copilot_precmd)${__copilot_original_ps1}" -} - -__copilot_sh_integration_main \ No newline at end of file diff --git a/com.microsoft.copilot.eclipse.terminal.api/src/com/microsoft/copilot/eclipse/terminal/api/IRunInTerminalTool.java b/com.microsoft.copilot.eclipse.terminal.api/src/com/microsoft/copilot/eclipse/terminal/api/IRunInTerminalTool.java index b3773000..b91429e1 100644 --- a/com.microsoft.copilot.eclipse.terminal.api/src/com/microsoft/copilot/eclipse/terminal/api/IRunInTerminalTool.java +++ b/com.microsoft.copilot.eclipse.terminal.api/src/com/microsoft/copilot/eclipse/terminal/api/IRunInTerminalTool.java @@ -16,22 +16,25 @@ public interface IRunInTerminalTool { /** - * Executes a command in the terminal. + * Executes a command in the terminal with an initial working directory. * * @param command The command to execute. * @param isBackground Whether the command should run in the background. + * @param workingDirectory The terminal's initial working directory. * @return A CompletableFuture that resolves to the output of the command. */ - public CompletableFuture executeCommand(String command, boolean isBackground); + public CompletableFuture executeCommand(String command, boolean isBackground, String workingDirectory); /** - * Prepares terminal properties for the command execution. + * Prepares terminal properties for the command execution with an initial working directory. * * @param runInBackground Whether the command should run in the background. * @param executionId The unique identifier for the execution. + * @param workingDirectory The terminal's initial working directory. * @return A map containing terminal properties. */ - public Map prepareTerminalProperties(boolean runInBackground, String executionId); + public Map prepareTerminalProperties(boolean runInBackground, String executionId, + String workingDirectory); /** * Retrieves the output of a background command execution. @@ -41,6 +44,11 @@ public interface IRunInTerminalTool { */ public StringBuilder getBackgroundCommandOutput(String executionId); + /** + * Cancels the foreground terminal command if one is currently running. + */ + public void cancelCurrentCommand(); + /** * Sets the terminal icon descriptor for the tool. */ diff --git a/com.microsoft.copilot.eclipse.terminal.api/src/com/microsoft/copilot/eclipse/terminal/api/ShellIntegrationScripts.java b/com.microsoft.copilot.eclipse.terminal.api/src/com/microsoft/copilot/eclipse/terminal/api/ShellIntegrationScripts.java index cd527c3a..c2015f2c 100644 --- a/com.microsoft.copilot.eclipse.terminal.api/src/com/microsoft/copilot/eclipse/terminal/api/ShellIntegrationScripts.java +++ b/com.microsoft.copilot.eclipse.terminal.api/src/com/microsoft/copilot/eclipse/terminal/api/ShellIntegrationScripts.java @@ -19,33 +19,62 @@ */ public final class ShellIntegrationScripts { - /** - * The marker string output by the shell integration script after each command completes. - * Uses OSC (Operating System Command) escape sequence format: ESC ] 7775 ; marker BEL - * This is invisible in terminal output but can be detected programmatically. - */ - public static final String SHELL_MARKER = "\u001b]7775;C\u0007"; + /** OSC namespace used by Copilot shell integration markers. */ + public static final String OSC_NAMESPACE = "7775"; + + /** Marker emitted when the prompt starts. */ + public static final String PROMPT_START_MARKER = "\u001b]" + OSC_NAMESPACE + ";A\u0007"; + + /** Marker emitted when the prompt ends. */ + public static final String PROMPT_END_MARKER = "\u001b]" + OSC_NAMESPACE + ";B\u0007"; + + /** Marker emitted when a command finishes without an exit code. */ + public static final String COMMAND_FINISH_MARKER = "\u001b]" + OSC_NAMESPACE + ";C\u0007"; + + /** Marker prefix emitted when a command finishes with an exit code. */ + public static final String COMMAND_FINISH_MARKER_PREFIX = "\u001b]" + OSC_NAMESPACE + ";C;"; + + /** Pattern matching Copilot OSC markers, including markers that lost ESC/BEL during terminal processing. */ + public static final String OSC_MARKER_PATTERN = buildOscMarkerPattern(); private static final String SCRIPTS_PATH = "scripts/"; - private static final String SH_SCRIPT = "copilot-sh-integration.sh"; + private static final String BASH_SCRIPT = "copilot-bash-integration.sh"; + private static final String POWERSHELL_SCRIPT = "copilot-powershell-integration.ps1"; private ShellIntegrationScripts() { // Utility class } + private static String buildOscMarkerPattern() { + return "(?:\u001B)?\\]" + OSC_NAMESPACE + ";[ABC](?:;[-]?\\d+)?(?:\u0007|\u001B\\\\)?"; + } + + /** + * Gets the absolute file path to the Bash integration script. + * + * @return the absolute path to the Bash script, or null if not found + */ + public static String getBashScriptPath() { + return getScriptPath(BASH_SCRIPT); + } + /** - * Gets the absolute file path to the POSIX sh integration script. + * Gets the absolute file path to the PowerShell integration script. * - * @return the absolute path to the sh script, or null if not found + * @return the absolute path to the PowerShell script, or null if not found */ - public static String getShScriptPath() { + public static String getPowerShellScriptPath() { + return getScriptPath(POWERSHELL_SCRIPT); + } + + private static String getScriptPath(String scriptName) { try { Bundle bundle = FrameworkUtil.getBundle(ShellIntegrationScripts.class); if (bundle == null) { return null; } - URL scriptUrl = FileLocator.find(bundle, new Path(SCRIPTS_PATH + SH_SCRIPT)); + URL scriptUrl = FileLocator.find(bundle, new Path(SCRIPTS_PATH + scriptName)); if (scriptUrl == null) { return null; } @@ -60,7 +89,7 @@ public static String getShScriptPath() { return scriptFile.getAbsolutePath(); } } catch (IOException e) { - CopilotCore.LOGGER.error("Failed to locate shell integration script: " + SH_SCRIPT, e); + CopilotCore.LOGGER.error("Failed to locate shell integration script: " + scriptName, e); } return null; } diff --git a/com.microsoft.copilot.eclipse.terminal.api/src/com/microsoft/copilot/eclipse/terminal/api/TerminalCommandProcessor.java b/com.microsoft.copilot.eclipse.terminal.api/src/com/microsoft/copilot/eclipse/terminal/api/TerminalCommandProcessor.java new file mode 100644 index 00000000..92dbb93b --- /dev/null +++ b/com.microsoft.copilot.eclipse.terminal.api/src/com/microsoft/copilot/eclipse/terminal/api/TerminalCommandProcessor.java @@ -0,0 +1,254 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.terminal.api; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; + +/** + * Processes terminal command input and output buffers. + */ +public final class TerminalCommandProcessor { + private static final int MAX_OUTPUT_LINE_COUNT = 1000; + private static final String BRACKETED_PASTE_START = "\u001b[200~"; + private static final String BRACKETED_PASTE_END = "\u001b[201~"; + private static final String ANSI_CSI_SEQUENCE_PATTERN = "\u001B\\[(\\?)?[\\d;]*[a-zA-Z]"; + private static final String OSC_SEQUENCE_PATTERN = "\u001B\\][^\u0007\u001B]*(?:\u0007|\u001B\\\\)"; + private static final Pattern PROMPT_START_MARKER_PATTERN = buildMarkerPattern("A", false); + private static final Pattern PROMPT_END_MARKER_PATTERN = buildMarkerPattern("B", false); + private static final Pattern COMMAND_FINISH_MARKER_PATTERN = buildMarkerPattern("C", true); + + private TerminalCommandProcessor() { + // Utility class + } + + /** + * Formats a command for immediate terminal execution. + * + * @param command the command to send + * @return command text formatted for terminal input + */ + public static String formatForExecution(String command) { + return formatForExecution(command, true); + } + + /** + * Formats a command for immediate terminal execution. + * + * @param command the command to send + * @param useBracketedPaste whether multiline commands should be sent using bracketed paste + * @return command text formatted for terminal input + */ + public static String formatForExecution(String command, boolean useBracketedPaste) { + String normalizedCommand = StringUtils.stripEnd(normalizeLineEndings(command), "\n"); + String terminalInput = useBracketedPaste && isMultilineCommand(normalizedCommand) + ? BRACKETED_PASTE_START + normalizedCommand + BRACKETED_PASTE_END + : normalizedCommand; + terminalInput = terminalInput.replace('\n', '\r'); + if (!terminalInput.endsWith("\r")) { + terminalInput += "\r"; + } + return terminalInput; + } + + /** + * Truncates terminal output to the tail when it is too long for a tool result. + * + * @param output terminal output + * @return terminal output, truncated to the last lines when needed + */ + public static String truncateOutput(String output) { + if (output == null || output.isEmpty()) { + return output == null ? "" : output; + } + + String normalizedOutput = normalizeLineEndings(output); + int scanIndex = normalizedOutput.endsWith("\n") ? normalizedOutput.length() - 2 : normalizedOutput.length() - 1; + int keptLineCount = 1; + while (scanIndex >= 0) { + if (normalizedOutput.charAt(scanIndex) == '\n') { + if (keptLineCount == MAX_OUTPUT_LINE_COUNT) { + StringBuilder truncatedOutput = new StringBuilder(); + truncatedOutput.append("[Terminal output truncated: showing last ") + .append(MAX_OUTPUT_LINE_COUNT) + .append(" lines.]\n"); + truncatedOutput.append(normalizedOutput.substring(scanIndex + 1)); + return truncatedOutput.toString(); + } + keptLineCount++; + } + scanIndex--; + } + + return output; + } + + /** + * Cleans terminal output for model-visible tool results. + * + * @param output terminal output + * @return output with terminal control sequences removed and long output truncated + */ + public static String prepareOutputForModel(String output) { + return truncateOutput(cleanTerminalControlSequences(output)); + } + + /** + * Attempts to complete a command using shell integration markers. + * + * @param output terminal output buffer + * @return the completion check result + */ + public static CompletionCheckResult tryCompleteWithMarker(StringBuilder output) { + MarkerRange commandFinishMarkerRange = findMarker(output, COMMAND_FINISH_MARKER_PATTERN, 0); + if (commandFinishMarkerRange == null) { + // Startup or idle prompts can arrive before a command runs. Keep the visible prompt text, but remove marker + // bytes so later command output cleanup does not have to handle stale prompt boundaries. + removePromptMarkers(output); + return CompletionCheckResult.incomplete(); + } + + // A complete marker command is the command finish marker followed by the next prompt end. Waiting for B keeps the + // prompt line in the returned output, which gives the language model the terminal's current working directory. + MarkerRange promptEndMarkerRange = findMarker(output, PROMPT_END_MARKER_PATTERN, commandFinishMarkerRange.endIndex); + if (promptEndMarkerRange == null) { + return CompletionCheckResult.incomplete(); + } + + // Keep terminal output plus the next prompt, but exclude command finish markers. + String completedOutput = output.substring(0, commandFinishMarkerRange.startIndex) + + output.substring(commandFinishMarkerRange.endIndex, promptEndMarkerRange.endIndex); + return CompletionCheckResult.completed(cleanCommandOutput(completedOutput)); + } + + /** + * Attempts to complete a command by detecting a shell prompt. + * + * @param output terminal output buffer + * @return the completion check result + */ + public static CompletionCheckResult tryCompleteWithPrompt(StringBuilder output) { + String terminalOutput = output.toString().trim(); + int lastNewLineIndex = terminalOutput.lastIndexOf('\n'); + if (lastNewLineIndex <= 0) { + return CompletionCheckResult.incomplete(); + } + + String lastLine = terminalOutput.substring(lastNewLineIndex).trim(); + if (lastLine.isBlank() || lastLine.length() == 1) { + return CompletionCheckResult.incomplete(); + } + + char lastChar = lastLine.charAt(lastLine.length() - 1); + boolean isPromptChar = lastChar == '>' || lastChar == '#' || lastChar == '$' || lastChar == '%'; + if (!isPromptChar) { + return CompletionCheckResult.incomplete(); + } + + String contentWithoutLastPrompt = terminalOutput.substring(0, lastNewLineIndex); + int promptStartIndex = contentWithoutLastPrompt.indexOf(lastLine); + if (promptStartIndex == -1) { + promptStartIndex = 0; + } else { + promptStartIndex += lastLine.length(); + } + + if (contentWithoutLastPrompt.isBlank()) { + return CompletionCheckResult.incomplete(); + } + return CompletionCheckResult.completed(contentWithoutLastPrompt.substring(promptStartIndex).trim()); + } + + private static String removeBracketedPasteMarkers(String output) { + return output.replace(BRACKETED_PASTE_START, "").replace(BRACKETED_PASTE_END, ""); + } + + private static boolean isMultilineCommand(String command) { + int newlineIndex = command.indexOf('\n'); + while (newlineIndex >= 0) { + if (newlineIndex == 0 || command.charAt(newlineIndex - 1) != '\\') { + return true; + } + newlineIndex = command.indexOf('\n', newlineIndex + 1); + } + return false; + } + + private static MarkerRange findMarker(StringBuilder output, Pattern markerPattern, int startIndex) { + Matcher matcher = markerPattern.matcher(output); + if (!matcher.find(startIndex)) { + return null; + } + return new MarkerRange(matcher.start(), matcher.end()); + } + + private static void removePromptMarkers(StringBuilder output) { + removeAll(output, PROMPT_START_MARKER_PATTERN); + removeAll(output, PROMPT_END_MARKER_PATTERN); + } + + private static void removeAll(StringBuilder output, Pattern markerPattern) { + Matcher matcher = markerPattern.matcher(output); + while (matcher.find()) { + output.delete(matcher.start(), matcher.end()); + matcher.reset(output); + } + } + + private static Pattern buildMarkerPattern(String markerKind, boolean includeExitCode) { + String exitCodePattern = includeExitCode ? "(?:;[-]?\\d+)?" : ""; + return Pattern.compile("(?:\u001B)?\\]" + ShellIntegrationScripts.OSC_NAMESPACE + ";" + markerKind + + exitCodePattern + "(?:\u0007|\u001B\\\\)?"); + } + + private static String cleanCommandOutput(String output) { + String normalizedOutput = normalizeLineEndings(output); + normalizedOutput = removeShellIntegrationMarkers(normalizedOutput); + normalizedOutput = removeBracketedPasteMarkers(normalizedOutput); + return normalizedOutput.trim(); + } + + private static String removeShellIntegrationMarkers(String output) { + return output.replaceAll(ShellIntegrationScripts.OSC_MARKER_PATTERN, ""); + } + + private static String cleanTerminalControlSequences(String output) { + if (output == null || output.isEmpty()) { + return output == null ? "" : output; + } + return removeShellIntegrationMarkers(output) + .replaceAll(ANSI_CSI_SEQUENCE_PATTERN, "") + .replaceAll(OSC_SEQUENCE_PATTERN, ""); + } + + private static String normalizeLineEndings(String value) { + return value.replace("\r\n", "\n").replace('\r', '\n'); + } + + private record MarkerRange(int startIndex, int endIndex) { + } + + /** + * Result of checking a terminal output buffer for command completion. + */ + public record CompletionCheckResult(CompletionCheckState state, String output) { + private static CompletionCheckResult incomplete() { + return new CompletionCheckResult(CompletionCheckState.INCOMPLETE, ""); + } + + private static CompletionCheckResult completed(String output) { + return new CompletionCheckResult(CompletionCheckState.COMPLETED, output); + } + } + + /** + * Terminal output completion states. + */ + public enum CompletionCheckState { + INCOMPLETE, + COMPLETED + } +} diff --git a/com.microsoft.copilot.eclipse.ui.jobs/META-INF/MANIFEST.MF b/com.microsoft.copilot.eclipse.ui.jobs/META-INF/MANIFEST.MF index c9af90e7..7c499bb2 100644 --- a/com.microsoft.copilot.eclipse.ui.jobs/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.ui.jobs/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: GitHub Copilot Jobs Bundle-SymbolicName: com.microsoft.copilot.eclipse.ui.jobs;singleton:=true -Bundle-Version: 0.18.0.qualifier +Bundle-Version: 0.20.0.qualifier Bundle-Vendor: GitHub Copilot Bundle-Activator: com.microsoft.copilot.eclipse.ui.jobs.CopilotJobs Bundle-RequiredExecutionEnvironment: JavaSE-17 @@ -10,8 +10,8 @@ Bundle-Localization: plugin Automatic-Module-Name: com.microsoft.copilot.eclipse.ui.jobs Bundle-ActivationPolicy: lazy Import-Package: org.osgi.framework;version="[1.10.0,2.0.0)" -Require-Bundle: com.microsoft.copilot.eclipse.core;bundle-version="0.15.0", - com.microsoft.copilot.eclipse.ui;bundle-version="0.15.0", +Require-Bundle: com.microsoft.copilot.eclipse.core;bundle-version="0.20.0", + com.microsoft.copilot.eclipse.ui;bundle-version="0.20.0", jakarta.annotation-api, jakarta.inject.jakarta.inject-api, org.apache.commons.lang3;bundle-version="3.13.0", diff --git a/com.microsoft.copilot.eclipse.ui.terminal.tm/META-INF/MANIFEST.MF b/com.microsoft.copilot.eclipse.ui.terminal.tm/META-INF/MANIFEST.MF index 76d94d69..0dd06aa3 100644 --- a/com.microsoft.copilot.eclipse.ui.terminal.tm/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.ui.terminal.tm/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: com.microsoft.copilot.eclipse.ui.terminal.tm Bundle-SymbolicName: com.microsoft.copilot.eclipse.ui.terminal.tm;singleton:=true -Bundle-Version: 0.18.0.qualifier +Bundle-Version: 0.20.0.qualifier Bundle-Vendor: GitHub Copilot Bundle-RequiredExecutionEnvironment: JavaSE-17 Automatic-Module-Name: com.microsoft.copilot.eclipse.ui.terminal.tm @@ -10,7 +10,7 @@ Bundle-ActivationPolicy: lazy Service-Component: OSGI-INF/component.xml Import-Package: org.osgi.framework;version="[1.10.0,2.0.0)", org.osgi.service.component -Require-Bundle: com.microsoft.copilot.eclipse.terminal.api;bundle-version="0.15.0", +Require-Bundle: com.microsoft.copilot.eclipse.terminal.api;bundle-version="0.20.0", org.eclipse.tm.terminal.view.core, org.eclipse.tm.terminal.view.ui, org.eclipse.tm.terminal.control, diff --git a/com.microsoft.copilot.eclipse.ui.terminal.tm/src/com/microsoft/copilot/eclipse/ui/terminal/tm/RunInTerminalTool.java b/com.microsoft.copilot.eclipse.ui.terminal.tm/src/com/microsoft/copilot/eclipse/ui/terminal/tm/RunInTerminalTool.java index 78f12c39..28849b6e 100644 --- a/com.microsoft.copilot.eclipse.ui.terminal.tm/src/com/microsoft/copilot/eclipse/ui/terminal/tm/RunInTerminalTool.java +++ b/com.microsoft.copilot.eclipse.ui.terminal.tm/src/com/microsoft/copilot/eclipse/ui/terminal/tm/RunInTerminalTool.java @@ -3,6 +3,7 @@ package com.microsoft.copilot.eclipse.ui.terminal.tm; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.UUID; @@ -36,6 +37,9 @@ import com.microsoft.copilot.eclipse.terminal.api.IRunInTerminalTool; import com.microsoft.copilot.eclipse.terminal.api.ShellIntegrationScripts; +import com.microsoft.copilot.eclipse.terminal.api.TerminalCommandProcessor; +import com.microsoft.copilot.eclipse.terminal.api.TerminalCommandProcessor.CompletionCheckResult; +import com.microsoft.copilot.eclipse.terminal.api.TerminalCommandProcessor.CompletionCheckState; /** * terminal tool implementation for older Eclipse versions. @@ -46,6 +50,9 @@ public class RunInTerminalTool implements IRunInTerminalTool { private static final Object lock = new Object(); private static final Map backgroundCommandOutputs = new HashMap<>(); private static final String BACKGROUND_TERMINAL_PREFIX = "Copilot-"; + private static final String POWERSHELL_SCRIPT_ENV = "COPILOT_POWERSHELL_INTEGRATION_SCRIPT"; + private static final String COMMAND_CANCELLED_MESSAGE = "Terminal command cancelled."; + private static final String COMMAND_INTERRUPTED_MESSAGE = "Terminal command interrupted by a new command."; // Non-background terminal field private ITerminalViewControl persistentTerminalViewControl; @@ -59,9 +66,7 @@ public class RunInTerminalTool implements IRunInTerminalTool { // Output and command state private StringBuilder sb; - private CompletableFuture resultFuture; - private volatile boolean useMarker; - private volatile boolean isInitialMarkerHandled; + private volatile ForegroundCommand foregroundCommand; /** * Constructor for RunInTerminalTool. @@ -71,52 +76,60 @@ public RunInTerminalTool() { } @Override - public CompletableFuture executeCommand(String command, boolean isBackground) { + public CompletableFuture executeCommand(String command, boolean isBackground, String workingDirectory) { if (StringUtils.isBlank(command)) { return CompletableFuture.completedFuture("The command is null or empty."); } - resultFuture = new CompletableFuture<>(); - useMarker = Platform.getOS().equals(Platform.OS_LINUX); + if (!isBackground) { + closeRunningForegroundTerminal(COMMAND_INTERRUPTED_MESSAGE); + } - if (!useMarker) { - // Retain only the last line (prompt) in the output buffer - if (!sb.isEmpty()) { - int lastLineStart = sb.lastIndexOf(StringUtils.LF); - if (lastLineStart > 0) { - sb.delete(0, lastLineStart); + CompletableFuture commandFuture = new CompletableFuture<>(); + ForegroundCommand commandState = isBackground ? null + : new ForegroundCommand(commandFuture, hasShellIntegrationMarker()); + + if (commandState != null) { + foregroundCommand = commandState; + if (!commandState.useMarker()) { + // Retain only the last line (prompt) in the output buffer + if (!sb.isEmpty()) { + int lastLineStart = sb.lastIndexOf(StringUtils.LF); + if (lastLineStart > 0) { + sb.delete(0, lastLineStart); + } } + } else { + // For marker-based detection, clear the buffer + sb.setLength(0); } - } else { - // For marker-based detection, clear the buffer - sb.setLength(0); } String executionId = UUID.randomUUID().toString(); - final String finalCommand = command + System.lineSeparator(); + final String finalCommand = TerminalCommandProcessor.formatForExecution(command, useBracketedPaste()); synchronized (lock) { if (!isBackground && this.persistentTerminalViewControl != null) { revealTerminal(); - this.persistentTerminalViewControl.pasteString(finalCommand); - return this.resultFuture; + sendCommand(this.persistentTerminalViewControl, finalCommand); + return commandFuture; } ITerminalService service = TerminalServiceFactory.getService(); if (service == null) { + clearForegroundCommand(commandState); return CompletableFuture.completedFuture("Failed to open terminal console due to terminal service is null."); } - // New non-background terminal will have an initial marker from shell startup; need to handle it - if (useMarker && !isBackground) { - isInitialMarkerHandled = false; - } - - service.openConsole(prepareTerminalProperties(isBackground, executionId), status -> { + service.openConsole(prepareTerminalProperties(isBackground, executionId, workingDirectory), status -> { if (status.isOK()) { + if (commandFuture.isDone()) { + return; + } ITerminalViewControl terminalViewControl = finalizeTerminalSetup(executionId, isBackground); if (terminalViewControl == null) { - resultFuture.complete("Terminal view control cannot be setup for RunInTerminalTool."); + clearForegroundCommand(commandState); + commandFuture.complete("Terminal view control cannot be setup for RunInTerminalTool."); return; } @@ -124,9 +137,10 @@ public CompletableFuture executeCommand(String command, boolean isBackgr this.persistentTerminalViewControl = terminalViewControl; revealTerminal(); } - terminalViewControl.pasteString(finalCommand); + sendCommand(terminalViewControl, finalCommand); } else { - resultFuture.complete("Failed to open terminal console: " + status.getException()); + clearForegroundCommand(commandState); + commandFuture.complete("Failed to open terminal console: " + status.getException()); } }); } @@ -135,25 +149,35 @@ public CompletableFuture executeCommand(String command, boolean isBackgr return CompletableFuture.completedFuture("Command is running in terminal with ID=" + executionId); } - return resultFuture; + return commandFuture; } @Override - public Map prepareTerminalProperties(boolean runInBackground, String executionId) { + public Map prepareTerminalProperties(boolean runInBackground, String executionId, + String workingDirectory) { Map properties = new HashMap<>(); properties.put(ITerminalsConnectorConstants.PROP_ENCODING, "UTF-8"); properties.put(ITerminalsConnectorConstants.PROP_TITLE_DISABLE_ANSI_TITLE, true); + if (StringUtils.isNotBlank(workingDirectory)) { + properties.put(ITerminalsConnectorConstants.PROP_PROCESS_WORKING_DIR, workingDirectory); + } if (Platform.getOS().equals(Platform.OS_WIN32)) { - properties.put(ITerminalsConnectorConstants.PROP_PROCESS_PATH, "cmd.exe"); - } else if (Platform.getOS().equals(Platform.OS_LINUX)) { - properties.put(ITerminalsConnectorConstants.PROP_PROCESS_PATH, "/bin/sh"); - // Use ENV to load shell integration script at startup - String scriptPath = ShellIntegrationScripts.getShScriptPath(); + properties.put(ITerminalsConnectorConstants.PROP_PROCESS_PATH, "powershell.exe"); + String scriptPath = ShellIntegrationScripts.getPowerShellScriptPath(); if (scriptPath != null) { - properties.put(ITerminalsConnectorConstants.PROP_PROCESS_ENVIRONMENT, new String[] { "ENV=" + scriptPath }); + String[] environment = new String[] { POWERSHELL_SCRIPT_ENV + "=" + scriptPath }; + String args = "-NoExit -ExecutionPolicy Bypass -Command \". $env:" + POWERSHELL_SCRIPT_ENV + "\""; + properties.put(ITerminalsConnectorConstants.PROP_PROCESS_ENVIRONMENT, environment); properties.put(ITerminalsConnectorConstants.PROP_PROCESS_MERGE_ENVIRONMENT, true); + properties.put(ITerminalsConnectorConstants.PROP_PROCESS_ARGS, args); + } + } else if (Platform.getOS().equals(Platform.OS_LINUX)) { + properties.put(ITerminalsConnectorConstants.PROP_PROCESS_PATH, "/bin/bash"); + String scriptPath = ShellIntegrationScripts.getBashScriptPath(); + if (scriptPath != null) { + properties.put(ITerminalsConnectorConstants.PROP_PROCESS_ARGS, "--init-file \"" + scriptPath + "\" -i"); } } else { // macOS or other Unix-like: keep existing behavior, only set args if empty @@ -187,6 +211,69 @@ public StringBuilder getBackgroundCommandOutput(String executionId) { return output; } + @Override + public void cancelCurrentCommand() { + closeRunningForegroundTerminal(COMMAND_CANCELLED_MESSAGE); + } + + private void closeRunningForegroundTerminal(String completionMessage) { + ForegroundCommand commandState = foregroundCommand; + if (commandState != null && !commandState.future().isDone()) { + closeCurrentForegroundTerminal(completionMessage); + } + } + + private void closeCurrentForegroundTerminal(String completionMessage) { + ForegroundCommand commandState = null; + CTabItem tabItem = null; + synchronized (lock) { + commandState = foregroundCommand; + foregroundCommand = null; + persistentTerminalViewControl = null; + tabItem = copilotTabItem; + copilotTabItem = null; + sb.setLength(0); + } + + if (tabItem != null) { + final CTabItem tabItemToDispose = tabItem; + // Keep this synchronous so a new foreground command cannot open before the old terminal tab is disposed. + Display.getDefault().syncExec(() -> { + if (!tabItemToDispose.isDisposed()) { + tabItemToDispose.dispose(); + } + }); + } + if (commandState != null && !commandState.future().isDone()) { + commandState.future().complete(completionMessage); + } + } + + private void clearForegroundCommand(ForegroundCommand commandState) { + if (commandState != null && foregroundCommand == commandState) { + foregroundCommand = null; + } + } + + private void sendCommand(ITerminalViewControl terminalViewControl, String command) { + terminalViewControl.pasteString(command); + } + + private boolean hasShellIntegrationMarker() { + if (Platform.getOS().equals(Platform.OS_WIN32)) { + return ShellIntegrationScripts.getPowerShellScriptPath() != null; + } + if (Platform.getOS().equals(Platform.OS_LINUX)) { + return ShellIntegrationScripts.getBashScriptPath() != null; + } + return false; + } + + private boolean useBracketedPaste() { + // macOS terminal multiline handling differs from PowerShell/Bash integration, so keep its existing plain input. + return Platform.getOS().equals(Platform.OS_WIN32) || Platform.getOS().equals(Platform.OS_LINUX); + } + private ITerminalViewControl finalizeTerminalSetup(String executionId, boolean isBackground) { String title = isBackground ? buildBackgroundTerminalTitle(executionId) : "Copilot"; synchronized (lock) { @@ -246,12 +333,9 @@ private ITerminalServiceOutputStreamMonitorListener buildOutputStreamMonitorList } return (byteBuffer, bytesRead) -> { - String content = new String(byteBuffer, 0, bytesRead); - // Remove ANSI escape sequences - // Sometimes it also removes the linebreaks. But we need the last prompt line to - // be a separate line later. So we - // add line separator back to the content. - content = content.replaceAll("\u001B\\[(\\?)?[\\d;]*[a-zA-Z]", StringUtils.LF); + String content = new String(byteBuffer, 0, bytesRead, StandardCharsets.UTF_8); + // Remove ANSI escape sequences while preserving only real line breaks from the terminal output. + content = content.replaceAll("\u001B\\[(\\?)?[\\d;]*[a-zA-Z]", ""); // Handle Windows terminal title sequences - using Platform instead of // PlatformUtils @@ -265,80 +349,25 @@ private ITerminalServiceOutputStreamMonitorListener buildOutputStreamMonitorList output.append(content); // Detect completion based on platform strategy - if (!isBackground && resultFuture != null && !resultFuture.isDone()) { - if (useMarker) { - tryCompleteWithMarker(output); - } else { - tryCompleteWithPrompt(output); - } + ForegroundCommand commandState = foregroundCommand; + if (!isBackground && commandState != null && !commandState.future().isDone()) { + CompletionCheckResult completionResult = commandState.useMarker() + ? TerminalCommandProcessor.tryCompleteWithMarker(output) + : TerminalCommandProcessor.tryCompleteWithPrompt(output); + handleCompletionResult(commandState, completionResult); } }; } - /** - * Attempts to complete the command by detecting the shell marker in output. - * Used on Linux where shell integration script outputs a marker after each command. - */ - private void tryCompleteWithMarker(StringBuilder output) { - int markerIndex = output.indexOf(ShellIntegrationScripts.SHELL_MARKER); - if (markerIndex < 0) { + private void handleCompletionResult(ForegroundCommand commandState, CompletionCheckResult completionResult) { + if (completionResult.state() == CompletionCheckState.INCOMPLETE) { return; } - - // Remove marker from output - output.delete(markerIndex, markerIndex + ShellIntegrationScripts.SHELL_MARKER.length()); - - // Skip the initial marker that appears when terminal starts (before any command is run) - if (!isInitialMarkerHandled) { - isInitialMarkerHandled = true; - return; + if (foregroundCommand == commandState) { + foregroundCommand = null; } - - String cleaned = output.toString().trim(); - resultFuture.complete(cleaned); - } - - /** - * Attempts to complete the command by detecting a shell prompt in output. - * Used on Windows and macOS where prompt characters indicate command completion. - */ - private void tryCompleteWithPrompt(StringBuilder output) { - String terminalOutput = output.toString().trim(); - int lastNewLineIndex = terminalOutput.lastIndexOf(StringUtils.LF); - if (lastNewLineIndex <= 0) { - return; - } - - String lastLine = terminalOutput.substring(lastNewLineIndex).trim(); - - // Check if last line is a prompt line - // Mac always has single '%' as last line, that's not what we want. - if (StringUtils.isBlank(lastLine) || lastLine.length() == 1) { - return; - } - - char lastChar = lastLine.charAt(lastLine.length() - 1); - boolean isPromptChar = lastChar == '>' || lastChar == '#' || lastChar == '$' || lastChar == '%'; - if (!isPromptChar) { - return; - } - - // Extract result text between prompts - String contentWithoutLastPrompt = terminalOutput.substring(0, lastNewLineIndex); - int promptStartIndex = contentWithoutLastPrompt.indexOf(lastLine); - // If the prompt line is not found, set start index to 0. Sometimes it starts - // with the commandResult. - if (promptStartIndex == -1) { - promptStartIndex = 0; - } else { - promptStartIndex += lastLine.length(); - } - - if (!contentWithoutLastPrompt.isBlank()) { - String commandResult = contentWithoutLastPrompt.substring(promptStartIndex).trim(); - if (resultFuture != null && !resultFuture.isDone()) { - resultFuture.complete(commandResult); - } + if (!commandState.future().isDone()) { + commandState.future().complete(completionResult.output()); } } @@ -385,6 +414,9 @@ private String buildBackgroundTerminalTitle(String executionId) { return BACKGROUND_TERMINAL_PREFIX + executionId; } + private record ForegroundCommand(CompletableFuture future, boolean useMarker) { + } + /** * Get active workbench page without UiUtils dependency. */ diff --git a/com.microsoft.copilot.eclipse.ui.terminal/META-INF/MANIFEST.MF b/com.microsoft.copilot.eclipse.ui.terminal/META-INF/MANIFEST.MF index bca04bbc..5fdd2792 100644 --- a/com.microsoft.copilot.eclipse.ui.terminal/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.ui.terminal/META-INF/MANIFEST.MF @@ -1,7 +1,7 @@ Bundle-ManifestVersion: 2 Bundle-Name: com.microsoft.copilot.eclipse.ui.terminal Bundle-SymbolicName: com.microsoft.copilot.eclipse.ui.terminal;singleton:=true -Bundle-Version: 0.18.0.qualifier +Bundle-Version: 0.20.0.qualifier Bundle-Vendor: GitHub Copilot Bundle-RequiredExecutionEnvironment: JavaSE-17 Automatic-Module-Name: com.microsoft.copilot.eclipse.ui.terminal @@ -9,7 +9,7 @@ Bundle-ActivationPolicy: lazy Service-Component: OSGI-INF/component.xml Import-Package: org.osgi.framework;version="[1.10.0,2.0.0)", org.osgi.service.component -Require-Bundle: com.microsoft.copilot.eclipse.terminal.api;bundle-version="0.15.0", +Require-Bundle: com.microsoft.copilot.eclipse.terminal.api;bundle-version="0.20.0", org.eclipse.terminal.view.core, org.eclipse.terminal.view.ui, org.eclipse.terminal.control, diff --git a/com.microsoft.copilot.eclipse.ui.terminal/src/com/microsoft/copilot/eclipse/ui/terminal/RunInTerminalTool.java b/com.microsoft.copilot.eclipse.ui.terminal/src/com/microsoft/copilot/eclipse/ui/terminal/RunInTerminalTool.java index 721dc954..dfe44701 100644 --- a/com.microsoft.copilot.eclipse.ui.terminal/src/com/microsoft/copilot/eclipse/ui/terminal/RunInTerminalTool.java +++ b/com.microsoft.copilot.eclipse.ui.terminal/src/com/microsoft/copilot/eclipse/ui/terminal/RunInTerminalTool.java @@ -3,6 +3,7 @@ package com.microsoft.copilot.eclipse.ui.terminal; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.UUID; @@ -36,6 +37,9 @@ import com.microsoft.copilot.eclipse.terminal.api.IRunInTerminalTool; import com.microsoft.copilot.eclipse.terminal.api.ShellIntegrationScripts; +import com.microsoft.copilot.eclipse.terminal.api.TerminalCommandProcessor; +import com.microsoft.copilot.eclipse.terminal.api.TerminalCommandProcessor.CompletionCheckResult; +import com.microsoft.copilot.eclipse.terminal.api.TerminalCommandProcessor.CompletionCheckState; /** * Modern terminal tool implementation for newer Eclipse versions. @@ -46,6 +50,9 @@ public class RunInTerminalTool implements IRunInTerminalTool { private static final Object lock = new Object(); private static final Map backgroundCommandOutputs = new HashMap<>(); private static final String BACKGROUND_TERMINAL_PREFIX = "Copilot-"; + private static final String POWERSHELL_SCRIPT_ENV = "COPILOT_POWERSHELL_INTEGRATION_SCRIPT"; + private static final String COMMAND_CANCELLED_MESSAGE = "Terminal command cancelled."; + private static final String COMMAND_INTERRUPTED_MESSAGE = "Terminal command interrupted by a new command."; // Non-background terminal field private ITerminalViewControl persistentTerminalViewControl; @@ -59,9 +66,7 @@ public class RunInTerminalTool implements IRunInTerminalTool { // Output and command state private StringBuilder sb; - private CompletableFuture resultFuture; - private volatile boolean useMarker; - private volatile boolean isInitialMarkerHandled; + private volatile ForegroundCommand foregroundCommand; /** * Constructor for RunInTerminalTool. @@ -71,54 +76,60 @@ public RunInTerminalTool() { } @Override - public CompletableFuture executeCommand(String command, boolean isBackground) { + public CompletableFuture executeCommand(String command, boolean isBackground, String workingDirectory) { if (StringUtils.isBlank(command)) { return CompletableFuture.completedFuture("The command is null or empty."); } - resultFuture = new CompletableFuture<>(); - - // Linux uses shell-integration marker lines; others rely on prompt detection - useMarker = Platform.getOS().equals(Platform.OS_LINUX); + if (!isBackground) { + closeRunningForegroundTerminal(COMMAND_INTERRUPTED_MESSAGE); + } - if (!useMarker) { - // Retain only the last line (prompt) in the output buffer - if (!sb.isEmpty()) { - int lastLineStart = sb.lastIndexOf(StringUtils.LF); - if (lastLineStart > 0) { - sb.delete(0, lastLineStart); + CompletableFuture commandFuture = new CompletableFuture<>(); + ForegroundCommand commandState = isBackground ? null + : new ForegroundCommand(commandFuture, hasShellIntegrationMarker()); + + if (commandState != null) { + foregroundCommand = commandState; + if (!commandState.useMarker()) { + // Retain only the last line (prompt) in the output buffer + if (!sb.isEmpty()) { + int lastLineStart = sb.lastIndexOf(StringUtils.LF); + if (lastLineStart > 0) { + sb.delete(0, lastLineStart); + } } + } else { + // For marker-based detection, clear the buffer + sb.setLength(0); } - } else { - // For marker-based detection, clear the buffer - sb.setLength(0); } String executionId = UUID.randomUUID().toString(); - final String finalCommand = command + System.lineSeparator(); + final String finalCommand = TerminalCommandProcessor.formatForExecution(command, useBracketedPaste()); synchronized (lock) { if (!isBackground && this.persistentTerminalViewControl != null) { revealTerminal(); - this.persistentTerminalViewControl.pasteString(finalCommand); - return this.resultFuture; + sendCommand(this.persistentTerminalViewControl, finalCommand); + return commandFuture; } ITerminalService service = CoreBundleActivator.getTerminalService(); if (service == null) { + clearForegroundCommand(commandState); return CompletableFuture.completedFuture("Failed to open terminal console due to terminal service is null."); } - // New non-background terminal will have an initial marker from shell startup; need to handle it - if (useMarker && !isBackground) { - isInitialMarkerHandled = false; - } - - service.openConsole(prepareTerminalProperties(isBackground, executionId)).handle((o, e) -> { + service.openConsole(prepareTerminalProperties(isBackground, executionId, workingDirectory)).handle((o, e) -> { if (e == null) { + if (commandFuture.isDone()) { + return null; + } ITerminalViewControl terminalViewControl = finalizeTerminalSetup(executionId, isBackground); if (terminalViewControl == null) { - resultFuture.complete("Terminal view control cannot be setup for RunInTerminalTool."); + clearForegroundCommand(commandState); + commandFuture.complete("Terminal view control cannot be setup for RunInTerminalTool."); return null; } @@ -126,9 +137,10 @@ public CompletableFuture executeCommand(String command, boolean isBackgr this.persistentTerminalViewControl = terminalViewControl; revealTerminal(); } - terminalViewControl.pasteString(finalCommand); + sendCommand(terminalViewControl, finalCommand); } else { - resultFuture.complete("Failed to open terminal console: " + e.getMessage()); + clearForegroundCommand(commandState); + commandFuture.complete("Failed to open terminal console: " + e.getMessage()); } return null; }); @@ -138,25 +150,35 @@ public CompletableFuture executeCommand(String command, boolean isBackgr return CompletableFuture.completedFuture("Command is running in terminal with ID=" + executionId); } - return resultFuture; + return commandFuture; } @Override - public Map prepareTerminalProperties(boolean runInBackground, String executionId) { + public Map prepareTerminalProperties(boolean runInBackground, String executionId, + String workingDirectory) { Map properties = new HashMap<>(); properties.put(ITerminalsConnectorConstants.PROP_ENCODING, "UTF-8"); properties.put(ITerminalsConnectorConstants.PROP_TITLE_DISABLE_ANSI_TITLE, true); + if (StringUtils.isNotBlank(workingDirectory)) { + properties.put(ITerminalsConnectorConstants.PROP_PROCESS_WORKING_DIR, workingDirectory); + } if (Platform.getOS().equals(Platform.OS_WIN32)) { - properties.put(ITerminalsConnectorConstants.PROP_PROCESS_PATH, "cmd.exe"); - } else if (Platform.getOS().equals(Platform.OS_LINUX)) { - properties.put(ITerminalsConnectorConstants.PROP_PROCESS_PATH, "/bin/sh"); - // Use ENV to load shell integration script at startup - String scriptPath = ShellIntegrationScripts.getShScriptPath(); + properties.put(ITerminalsConnectorConstants.PROP_PROCESS_PATH, "powershell.exe"); + String scriptPath = ShellIntegrationScripts.getPowerShellScriptPath(); if (scriptPath != null) { - properties.put(ITerminalsConnectorConstants.PROP_PROCESS_ENVIRONMENT, new String[] { "ENV=" + scriptPath }); + String[] environment = new String[] { POWERSHELL_SCRIPT_ENV + "=" + scriptPath }; + String args = "-NoExit -ExecutionPolicy Bypass -Command \". $env:" + POWERSHELL_SCRIPT_ENV + "\""; + properties.put(ITerminalsConnectorConstants.PROP_PROCESS_ENVIRONMENT, environment); properties.put(ITerminalsConnectorConstants.PROP_PROCESS_MERGE_ENVIRONMENT, true); + properties.put(ITerminalsConnectorConstants.PROP_PROCESS_ARGS, args); + } + } else if (Platform.getOS().equals(Platform.OS_LINUX)) { + properties.put(ITerminalsConnectorConstants.PROP_PROCESS_PATH, "/bin/bash"); + String scriptPath = ShellIntegrationScripts.getBashScriptPath(); + if (scriptPath != null) { + properties.put(ITerminalsConnectorConstants.PROP_PROCESS_ARGS, "--init-file \"" + scriptPath + "\" -i"); } } else { // macOS or other Unix-like: keep existing behavior, only set args if empty @@ -190,6 +212,69 @@ public StringBuilder getBackgroundCommandOutput(String executionId) { return output; } + @Override + public void cancelCurrentCommand() { + closeRunningForegroundTerminal(COMMAND_CANCELLED_MESSAGE); + } + + private void closeRunningForegroundTerminal(String completionMessage) { + ForegroundCommand commandState = foregroundCommand; + if (commandState != null && !commandState.future().isDone()) { + closeCurrentForegroundTerminal(completionMessage); + } + } + + private void closeCurrentForegroundTerminal(String completionMessage) { + ForegroundCommand commandState = null; + CTabItem tabItem = null; + synchronized (lock) { + commandState = foregroundCommand; + foregroundCommand = null; + persistentTerminalViewControl = null; + tabItem = copilotTabItem; + copilotTabItem = null; + sb.setLength(0); + } + + if (tabItem != null) { + final CTabItem tabItemToDispose = tabItem; + // Keep this synchronous so a new foreground command cannot open before the old terminal tab is disposed. + Display.getDefault().syncExec(() -> { + if (!tabItemToDispose.isDisposed()) { + tabItemToDispose.dispose(); + } + }); + } + if (commandState != null && !commandState.future().isDone()) { + commandState.future().complete(completionMessage); + } + } + + private void clearForegroundCommand(ForegroundCommand commandState) { + if (commandState != null && foregroundCommand == commandState) { + foregroundCommand = null; + } + } + + private void sendCommand(ITerminalViewControl terminalViewControl, String command) { + terminalViewControl.pasteString(command); + } + + private boolean hasShellIntegrationMarker() { + if (Platform.getOS().equals(Platform.OS_WIN32)) { + return ShellIntegrationScripts.getPowerShellScriptPath() != null; + } + if (Platform.getOS().equals(Platform.OS_LINUX)) { + return ShellIntegrationScripts.getBashScriptPath() != null; + } + return false; + } + + private boolean useBracketedPaste() { + // macOS terminal multiline handling differs from PowerShell/Bash integration, so keep its existing plain input. + return Platform.getOS().equals(Platform.OS_WIN32) || Platform.getOS().equals(Platform.OS_LINUX); + } + private ITerminalViewControl finalizeTerminalSetup(String executionId, boolean isBackground) { String title = isBackground ? buildBackgroundTerminalTitle(executionId) : "Copilot"; synchronized (lock) { @@ -234,7 +319,7 @@ private ITerminalControl getTerminalControl(String terminalTitle, boolean isBack } } } catch (PartInitException e) { - //skip exception + // Skip exception } }); @@ -249,11 +334,9 @@ private ITerminalServiceOutputStreamMonitorListener buildOutputStreamMonitorList } return (byteBuffer, bytesRead) -> { - String content = new String(byteBuffer, 0, bytesRead); - // Remove ANSI escape sequences - // Sometimes it also removes the linebreaks. But we need the last prompt line to be a separate line later. So we - // add line separator back to the content. - content = content.replaceAll("\u001B\\[(\\?)?[\\d;]*[a-zA-Z]", StringUtils.LF); + String content = new String(byteBuffer, 0, bytesRead, StandardCharsets.UTF_8); + // Remove ANSI escape sequences while preserving only real line breaks from the terminal output. + content = content.replaceAll("\u001B\\[(\\?)?[\\d;]*[a-zA-Z]", ""); // Handle Windows terminal title sequences - using Platform instead of PlatformUtils if (Platform.getOS().equals(Platform.OS_WIN32)) { @@ -265,80 +348,25 @@ private ITerminalServiceOutputStreamMonitorListener buildOutputStreamMonitorList output.append(content); // Detect completion based on platform strategy - if (!isBackground && resultFuture != null && !resultFuture.isDone()) { - if (useMarker) { - tryCompleteWithMarker(output); - } else { - tryCompleteWithPrompt(output); - } + ForegroundCommand commandState = foregroundCommand; + if (!isBackground && commandState != null && !commandState.future().isDone()) { + CompletionCheckResult completionResult = commandState.useMarker() + ? TerminalCommandProcessor.tryCompleteWithMarker(output) + : TerminalCommandProcessor.tryCompleteWithPrompt(output); + handleCompletionResult(commandState, completionResult); } }; } - /** - * Attempts to complete the command by detecting the shell marker in output. - * Used on Linux where shell integration script outputs a marker after each command. - */ - private void tryCompleteWithMarker(StringBuilder output) { - int markerIndex = output.indexOf(ShellIntegrationScripts.SHELL_MARKER); - if (markerIndex < 0) { - return; - } - - // Remove marker from output - output.delete(markerIndex, markerIndex + ShellIntegrationScripts.SHELL_MARKER.length()); - - // Skip the initial marker that appears when terminal starts (before any command is run) - if (!isInitialMarkerHandled) { - isInitialMarkerHandled = true; - return; - } - - String cleaned = output.toString().trim(); - resultFuture.complete(cleaned); - } - - /** - * Attempts to complete the command by detecting a shell prompt in output. - * Used on Windows and macOS where prompt characters indicate command completion. - */ - private void tryCompleteWithPrompt(StringBuilder output) { - String terminalOutput = output.toString().trim(); - int lastNewLineIndex = terminalOutput.lastIndexOf(StringUtils.LF); - if (lastNewLineIndex <= 0) { - return; - } - - String lastLine = terminalOutput.substring(lastNewLineIndex).trim(); - - // Check if last line is a prompt line - // Mac always has single '%' as last line, that's not what we want. - if (StringUtils.isBlank(lastLine) || lastLine.length() == 1) { + private void handleCompletionResult(ForegroundCommand commandState, CompletionCheckResult completionResult) { + if (completionResult.state() == CompletionCheckState.INCOMPLETE) { return; } - - char lastChar = lastLine.charAt(lastLine.length() - 1); - boolean isPromptChar = lastChar == '>' || lastChar == '#' || lastChar == '$' || lastChar == '%'; - if (!isPromptChar) { - return; + if (foregroundCommand == commandState) { + foregroundCommand = null; } - - // Extract result text between prompts - String contentWithoutLastPrompt = terminalOutput.substring(0, lastNewLineIndex); - int promptStartIndex = contentWithoutLastPrompt.indexOf(lastLine); - // If the prompt line is not found, set start index to 0. Sometimes it starts - // with the commandResult. - if (promptStartIndex == -1) { - promptStartIndex = 0; - } else { - promptStartIndex += lastLine.length(); - } - - if (!contentWithoutLastPrompt.isBlank()) { - String commandResult = contentWithoutLastPrompt.substring(promptStartIndex).trim(); - if (resultFuture != null && !resultFuture.isDone()) { - resultFuture.complete(commandResult); - } + if (!commandState.future().isDone()) { + commandState.future().complete(completionResult.output()); } } @@ -385,6 +413,9 @@ private String buildBackgroundTerminalTitle(String executionId) { return BACKGROUND_TERMINAL_PREFIX + executionId; } + private record ForegroundCommand(CompletableFuture future, boolean useMarker) { + } + /** * Get active workbench page without UiUtils dependency. */ diff --git a/com.microsoft.copilot.eclipse.ui.test/META-INF/MANIFEST.MF b/com.microsoft.copilot.eclipse.ui.test/META-INF/MANIFEST.MF index 763af993..9d33676c 100644 --- a/com.microsoft.copilot.eclipse.ui.test/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.ui.test/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: com.microsoft.copilot.eclipse.ui.test Bundle-SymbolicName: com.microsoft.copilot.eclipse.ui.test;singleton:=true -Bundle-Version: 0.18.0.qualifier +Bundle-Version: 0.20.0.qualifier Bundle-Vendor: GitHub Copilot Bundle-RequiredExecutionEnvironment: JavaSE-17 Automatic-Module-Name: com.microsoft.copilot.eclipse.ui.test @@ -14,8 +14,8 @@ Require-Bundle: org.mockito.mockito-core;bundle-version="5.14.2", junit-jupiter-api;bundle-version="5.10.1", junit-jupiter-params;bundle-version="5.10.1", org.mockito.junit-jupiter;bundle-version="5.10.2", - com.microsoft.copilot.eclipse.core;bundle-version="0.15.0", - com.microsoft.copilot.eclipse.ui;bundle-version="0.15.0", + com.microsoft.copilot.eclipse.core;bundle-version="0.20.0", + com.microsoft.copilot.eclipse.ui;bundle-version="0.20.0", org.eclipse.ui;bundle-version="3.205.0", org.eclipse.ui.ide, org.eclipse.ui.workbench.texteditor, @@ -29,4 +29,4 @@ Require-Bundle: org.mockito.mockito-core;bundle-version="5.14.2", org.eclipse.e4.core.services;bundle-version="2.4.200", org.osgi.service.event, com.google.gson, - com.microsoft.copilot.eclipse.terminal.api;bundle-version="0.15.0" + com.microsoft.copilot.eclipse.terminal.api;bundle-version="0.20.0" diff --git a/com.microsoft.copilot.eclipse.ui.test/pom.xml b/com.microsoft.copilot.eclipse.ui.test/pom.xml index 2514c9b6..d6296186 100644 --- a/com.microsoft.copilot.eclipse.ui.test/pom.xml +++ b/com.microsoft.copilot.eclipse.ui.test/pom.xml @@ -15,6 +15,29 @@ true + + + skip-tests-during-ui-probe + + + probe.script + + + + + + org.eclipse.tycho + tycho-surefire-plugin + ${tycho-version} + + true + + + + + + + diff --git a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/terminal/api/TerminalCommandProcessorTest.java b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/terminal/api/TerminalCommandProcessorTest.java new file mode 100644 index 00000000..67e4607e --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/terminal/api/TerminalCommandProcessorTest.java @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.terminal.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +import com.microsoft.copilot.eclipse.terminal.api.TerminalCommandProcessor.CompletionCheckState; + +class TerminalCommandProcessorTest { + @Test + void testFormatForExecution_singleLine_appendsCarriageReturn() { + assertEquals("echo hello\r", TerminalCommandProcessor.formatForExecution("echo hello")); + } + + @Test + void testFormatForExecution_multiline_wrapsWithBracketedPaste() { + assertEquals("\u001b[200~echo first\recho second\u001b[201~\r", + TerminalCommandProcessor.formatForExecution("echo first\necho second")); + } + + @Test + void testFormatForExecution_multilineWithCrlf_normalizesLineEndings() { + assertEquals("\u001b[200~echo first\recho second\u001b[201~\r", + TerminalCommandProcessor.formatForExecution("echo first\r\necho second")); + } + + @Test + void testFormatForExecution_multilineWithTrailingNewline_doesNotSubmitEmptyCommand() { + assertEquals("\u001b[200~echo first\recho second\u001b[201~\r", + TerminalCommandProcessor.formatForExecution("echo first\necho second\n")); + } + + @Test + void testFormatForExecution_multilineWithoutBracketedPaste_submitsPlainLines() { + assertEquals("echo first\recho second\r", + TerminalCommandProcessor.formatForExecution("echo first\necho second", false)); + } + + @Test + void testFormatForExecution_singleLineWithTrailingNewline_doesNotUseBracketedPaste() { + assertEquals("echo hello\r", TerminalCommandProcessor.formatForExecution("echo hello\n")); + } + + @Test + void testFormatForExecution_backslashContinuation_doesNotUseBracketedPaste() { + assertEquals("echo hello \\" + "\r world\r", + TerminalCommandProcessor.formatForExecution("echo hello \\\n world")); + } + + @Test + void testTryCompleteWithMarker_completed_keepsNextPrompt() { + StringBuilder output = new StringBuilder("echo hi\r\n") + .append("hi\r\n") + .append(ShellIntegrationScripts.COMMAND_FINISH_MARKER_PREFIX).append("0\u0007") + .append(ShellIntegrationScripts.PROMPT_START_MARKER) + .append("PS C:\\projects\\copilot-eclipse> ") + .append(ShellIntegrationScripts.PROMPT_END_MARKER); + + var result = TerminalCommandProcessor.tryCompleteWithMarker(output); + + assertEquals(CompletionCheckState.COMPLETED, result.state()); + assertEquals("echo hi\nhi\nPS C:\\projects\\copilot-eclipse>", result.output()); + } + + @Test + void testTryCompleteWithMarker_completedWithBareMarker() { + StringBuilder output = new StringBuilder("echo hi\r\nhi\r\n]7775;C;0]7775;A$ ]7775;B"); + + var result = TerminalCommandProcessor.tryCompleteWithMarker(output); + + assertEquals(CompletionCheckState.COMPLETED, result.state()); + assertEquals("echo hi\nhi\n$", result.output()); + } + + @Test + void testTryCompleteWithMarker_incomplete_removesPromptMarkers() { + StringBuilder output = new StringBuilder() + .append(ShellIntegrationScripts.PROMPT_START_MARKER) + .append("PS C:\\projects\\copilot-eclipse> ") + .append(ShellIntegrationScripts.PROMPT_END_MARKER); + + var result = TerminalCommandProcessor.tryCompleteWithMarker(output); + + assertEquals(CompletionCheckState.INCOMPLETE, result.state()); + assertEquals("PS C:\\projects\\copilot-eclipse> ", output.toString()); + } + + @Test + void testTryCompleteWithMarker_completedPreservesOutputContainingCommandText() { + StringBuilder output = new StringBuilder("echo hi\r\n") + .append("before\r\necho hi\r\nafter\r\n") + .append(ShellIntegrationScripts.COMMAND_FINISH_MARKER_PREFIX).append("0\u0007") + .append(ShellIntegrationScripts.PROMPT_START_MARKER) + .append("$ ") + .append(ShellIntegrationScripts.PROMPT_END_MARKER); + + var result = TerminalCommandProcessor.tryCompleteWithMarker(output); + + assertEquals(CompletionCheckState.COMPLETED, result.state()); + assertEquals("echo hi\nbefore\necho hi\nafter\n$", result.output()); + } + + @Test + void testTryCompleteWithPrompt_completed_extractsOutputBetweenPrompts() { + StringBuilder output = new StringBuilder("PS C:\\repo> echo hi\nhi\nPS C:\\repo> "); + + var result = TerminalCommandProcessor.tryCompleteWithPrompt(output); + + assertEquals(CompletionCheckState.COMPLETED, result.state()); + assertEquals("echo hi\nhi", result.output()); + } + + @Test + void testTruncateOutput_shortOutput_returnsOriginalOutput() { + String output = "line 1\r\nline 2"; + + assertEquals(output, TerminalCommandProcessor.truncateOutput(output)); + } + + @Test + void testTruncateOutput_longOutput_keepsTailLines() { + StringBuilder output = new StringBuilder(); + for (int lineIndex = 1; lineIndex <= 1005; lineIndex++) { + output.append("line ").append(lineIndex).append('\n'); + } + + String result = TerminalCommandProcessor.truncateOutput(output.toString()); + + assertTrue(result.startsWith("[Terminal output truncated: showing last 1000 lines.]\n")); + assertFalse(result.contains("line 5\n")); + assertTrue(result.contains("line 6\n")); + assertTrue(result.endsWith("line 1005\n")); + } + + @Test + void testPrepareOutputForModel_removesCopilotShellMarkers() { + String output = "start\n" + ShellIntegrationScripts.PROMPT_START_MARKER + + "]7775;B\nbody\n]7775;C\nliteral 7775;A remains\n" + + ShellIntegrationScripts.COMMAND_FINISH_MARKER_PREFIX + "1\u0007end"; + + String result = TerminalCommandProcessor.prepareOutputForModel(output); + + assertEquals("start\n\nbody\n\nliteral 7775;A remains\nend", result); + } +} \ No newline at end of file diff --git a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/BaseTurnWidgetPartialRenderTest.java b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/BaseTurnWidgetPartialRenderTest.java new file mode 100644 index 00000000..b2e0df9b --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/BaseTurnWidgetPartialRenderTest.java @@ -0,0 +1,276 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.chat; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; + +import java.lang.reflect.Field; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.microsoft.copilot.eclipse.ui.CopilotUi; +import com.microsoft.copilot.eclipse.ui.chat.services.AvatarService; +import com.microsoft.copilot.eclipse.ui.chat.services.ChatFontService; +import com.microsoft.copilot.eclipse.ui.chat.services.ChatServiceManager; +import com.microsoft.copilot.eclipse.ui.utils.SwtUtils; + +/** + * Verifies that {@link BaseTurnWidget#appendMessage} eagerly renders trailing partial lines via + * {@code renderPartialBuffer}, while deferring rendering for code-fence prefixes and inside code + * blocks where fence detection requires a complete line. + */ +@ExtendWith(MockitoExtension.class) +class BaseTurnWidgetPartialRenderTest { + + private static final String TURN_ID = "turn-1"; + + private Shell shell; + private MockedStatic copilotUiMock; + private CopilotUi mockPlugin; + + @Mock + private ChatServiceManager mockChatServiceManager; + @Mock + private AvatarService mockAvatarService; + @Mock + private ChatFontService mockChatFontService; + + @BeforeEach + void setUp() { + lenient().when(mockChatServiceManager.getAvatarService()).thenReturn(mockAvatarService); + lenient().when(mockChatServiceManager.getChatFontService()).thenReturn(mockChatFontService); + lenient().when(mockAvatarService.getAvatarForCopilot()).thenReturn(null); + + SwtUtils.invokeOnDisplayThread(() -> { + shell = new Shell(Display.getDefault()); + copilotUiMock = mockStatic(CopilotUi.class); + mockPlugin = mock(CopilotUi.class); + copilotUiMock.when(CopilotUi::getPlugin).thenReturn(mockPlugin); + lenient().when(mockPlugin.getChatServiceManager()).thenReturn(mockChatServiceManager); + }); + } + + @AfterEach + void tearDown() { + SwtUtils.invokeOnDisplayThread(() -> { + if (copilotUiMock != null) { + copilotUiMock.close(); + copilotUiMock = null; + } + if (shell != null && !shell.isDisposed()) { + shell.dispose(); + } + }); + } + + @Test + void appendMessage_partialLineWithoutNewline_rendersImmediately() { + SwtUtils.invokeOnDisplayThread(() -> { + CopilotTurnWidget widget = new CopilotTurnWidget(shell, SWT.NONE, mockChatServiceManager, TURN_ID); + + widget.appendMessage("Hello world"); + + ChatMarkupViewer viewer = getMarkupViewer(widget); + assertNotNull(viewer, "Partial text without newline should be rendered eagerly to a text block"); + assertTrue(viewer.getTextWidget().getText().contains("Hello world"), + "Expected partial text to be visible, got: '" + viewer.getTextWidget().getText() + "'"); + }); + } + + @Test + void appendMessage_partialAfterCompleteLine_rendersBothCommittedAndPartial() { + SwtUtils.invokeOnDisplayThread(() -> { + CopilotTurnWidget widget = new CopilotTurnWidget(shell, SWT.NONE, mockChatServiceManager, TURN_ID); + + // First chunk: a complete line plus a trailing partial fragment without a newline. + widget.appendMessage("First line\nSecond "); + + ChatMarkupViewer viewer = getMarkupViewer(widget); + assertNotNull(viewer, "Text block should be created"); + String rendered = viewer.getTextWidget().getText(); + assertTrue(rendered.contains("First line"), + "Committed line should be rendered, got: '" + rendered + "'"); + assertTrue(rendered.contains("Second"), + "Trailing partial fragment should be rendered eagerly, got: '" + rendered + "'"); + + // Append more text completing the partial line — final render must show full content. + widget.appendMessage("line\n"); + rendered = viewer.getTextWidget().getText(); + assertTrue(rendered.contains("First line"), + "First line should still be present after appending more text, got: '" + rendered + "'"); + assertTrue(rendered.contains("Second line"), + "Completed second line should be rendered, got: '" + rendered + "'"); + }); + } + + @Test + void appendMessage_partialIsTripleBacktickFence_defersRendering() { + SwtUtils.invokeOnDisplayThread(() -> { + CopilotTurnWidget widget = new CopilotTurnWidget(shell, SWT.NONE, mockChatServiceManager, TURN_ID); + + // A confirmed code-fence prefix — must wait for the newline before deciding whether + // to render markup or open a code block. Otherwise the literal backticks would flash + // into the markup viewer. + widget.appendMessage("```"); + + assertNull(getField(widget, "currentTextBlock"), + "Text block must not be created for a confirmed fence prefix"); + assertNull(getField(widget, "currentCodeBlock"), + "Code block must not be created until the fence newline is received"); + }); + } + + @Test + void appendMessage_partialIsTripleBacktickWithLanguage_defersRendering() { + SwtUtils.invokeOnDisplayThread(() -> { + CopilotTurnWidget widget = new CopilotTurnWidget(shell, SWT.NONE, mockChatServiceManager, TURN_ID); + + widget.appendMessage("```java"); + + assertNull(getField(widget, "currentTextBlock"), + "Text block must not be created while a fence-with-language is still being streamed"); + assertNull(getField(widget, "currentCodeBlock"), + "Code block must not be created until the fence newline is received"); + }); + } + + @Test + void appendMessage_partialIsSingleBacktick_defersRendering() { + SwtUtils.invokeOnDisplayThread(() -> { + CopilotTurnWidget widget = new CopilotTurnWidget(shell, SWT.NONE, mockChatServiceManager, TURN_ID); + + // A lone backtick could grow into ``` on the next chunk — defer rendering. + widget.appendMessage("`"); + + assertNull(getField(widget, "currentTextBlock"), + "Text block must not be created for an ambiguous single backtick"); + }); + } + + @Test + void appendMessage_partialIsDoubleBacktick_defersRendering() { + SwtUtils.invokeOnDisplayThread(() -> { + CopilotTurnWidget widget = new CopilotTurnWidget(shell, SWT.NONE, mockChatServiceManager, TURN_ID); + + widget.appendMessage("``"); + + assertNull(getField(widget, "currentTextBlock"), + "Text block must not be created for an ambiguous double backtick"); + }); + } + + @Test + void appendMessage_partialBacktickFollowedByText_rendersImmediately() { + SwtUtils.invokeOnDisplayThread(() -> { + CopilotTurnWidget widget = new CopilotTurnWidget(shell, SWT.NONE, mockChatServiceManager, TURN_ID); + + // A single backtick followed by non-backtick content is inline code, not a fence — + // render eagerly so the user sees the streamed token immediately. + widget.appendMessage("`code"); + + ChatMarkupViewer viewer = getMarkupViewer(widget); + assertNotNull(viewer, "Inline-code partial should be rendered eagerly"); + assertTrue(viewer.getTextWidget().getText().contains("code"), + "Inline-code content should be visible, got: '" + viewer.getTextWidget().getText() + "'"); + }); + } + + @Test + void appendMessage_partialResolvesIntoFence_doesNotLeaveStaleText() { + SwtUtils.invokeOnDisplayThread(() -> { + CopilotTurnWidget widget = new CopilotTurnWidget(shell, SWT.NONE, mockChatServiceManager, TURN_ID); + + // First send some markdown so a text block exists. + widget.appendMessage("intro text\n"); + ChatMarkupViewer viewer = getMarkupViewer(widget); + assertNotNull(viewer); + assertTrue(viewer.getTextWidget().getText().contains("intro text")); + + // Then start streaming a fence — must NOT append "```" into the markup viewer. + widget.appendMessage("```"); + assertTrue(!viewer.getTextWidget().getText().contains("```"), + "Fence prefix must not leak into the markup viewer, got: '" + viewer.getTextWidget().getText() + "'"); + + // Complete the fence: the code block should open and the markup viewer should not gain + // the fence characters. + widget.appendMessage("java\n"); + assertNotNull(getField(widget, "currentCodeBlock"), + "Code block must open once the fence newline is received"); + assertTrue(!viewer.getTextWidget().getText().contains("```"), + "Fence characters must never appear in the markup viewer"); + }); + } + + @Test + void appendMessage_partialInsideCodeBlock_isNotRenderedAsMarkup() { + SwtUtils.invokeOnDisplayThread(() -> { + CopilotTurnWidget widget = new CopilotTurnWidget(shell, SWT.NONE, mockChatServiceManager, TURN_ID); + + // Open a code block. + widget.appendMessage("```java\n"); + assertNotNull(getField(widget, "currentCodeBlock"), + "Code block should be open after the opening fence line"); + assertNull(getField(widget, "currentTextBlock"), + "Text block should not exist while we are inside a code block"); + + // Stream a partial code line without a newline — the partial must NOT be rendered + // to the markup viewer, since partial code text has to go through the source viewer + // once a complete line arrives. + widget.appendMessage("int x = 1;"); + + assertNull(getField(widget, "currentTextBlock"), + "Partial text inside a code block must not create a markup text block"); + }); + } + + @Test + void appendMessage_emptyString_doesNotRender() { + SwtUtils.invokeOnDisplayThread(() -> { + CopilotTurnWidget widget = new CopilotTurnWidget(shell, SWT.NONE, mockChatServiceManager, TURN_ID); + + widget.appendMessage(""); + + assertNull(getField(widget, "currentTextBlock"), + "Empty message must be a no-op and must not create a text block"); + StringBuilder buffer = (StringBuilder) getField(widget, "messageBuffer"); + assertEquals(0, buffer.length(), "Empty message must not accumulate into the buffer"); + }); + } + + private static ChatMarkupViewer getMarkupViewer(BaseTurnWidget widget) { + Object textBlock = getField(widget, "currentTextBlock"); + return textBlock instanceof ChatMarkupViewer markup ? markup : null; + } + + private static Object getField(Object target, String name) { + Class cls = target.getClass(); + while (cls != null) { + try { + Field f = cls.getDeclaredField(name); + f.setAccessible(true); + return f.get(target); + } catch (NoSuchFieldException e) { + cls = cls.getSuperclass(); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + throw new RuntimeException("Field '" + name + "' not found on " + target.getClass()); + } +} diff --git a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/ChatContentViewerTest.java b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/ChatContentViewerTest.java index b181bd9a..16595f17 100644 --- a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/ChatContentViewerTest.java +++ b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/ChatContentViewerTest.java @@ -9,14 +9,17 @@ import static org.mockito.Mockito.when; import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.util.List; import java.util.Map; import org.eclipse.lsp4j.WorkDoneProgressKind; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.Shell; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -104,6 +107,118 @@ private Map getTurnsMap(ChatContentViewer viewer) { return (Map) getFieldValue(viewer, "turns"); } + @Test + void testClampOffset_clampsToScrollableRange() { + SwtUtils.invokeOnDisplayThread(() -> { + sizeViewer(400, 300); + setFieldValue(viewer, "totalHeight", 1000); + int maxOffset = invokeIntMethod(viewer, "maxOffset"); + + Assertions.assertTrue(maxOffset > 0, "content taller than the viewport should be scrollable"); + Assertions.assertEquals(0, invokeIntMethod(viewer, "clampOffset", -50), + "negative offset should clamp to 0"); + Assertions.assertEquals(maxOffset, invokeIntMethod(viewer, "clampOffset", 5000), + "offset past the end should clamp to maxOffset"); + Assertions.assertEquals(200, invokeIntMethod(viewer, "clampOffset", 200), + "in-range offset should be left unchanged"); + }); + } + + @Test + void testMaxOffset_isZeroWhenContentFitsViewport() { + SwtUtils.invokeOnDisplayThread(() -> { + sizeViewer(400, 300); + setFieldValue(viewer, "totalHeight", 200); + + Assertions.assertEquals(0, invokeIntMethod(viewer, "maxOffset"), + "content shorter than the viewport should not be scrollable"); + }); + } + + @Test + void testUpdateScrollBar_rangeMatchesTotalHeight() { + SwtUtils.invokeOnDisplayThread(() -> { + sizeViewer(400, 300); + setFieldValue(viewer, "totalHeight", 1000); + setFieldValue(viewer, "scrollOffset", 120); + + invokeVoidMethod(viewer, "updateScrollBar", 300); + + ScrollBar bar = viewer.getVerticalBar(); + Assertions.assertTrue(bar.getEnabled(), "scrollbar should be enabled when content overflows"); + Assertions.assertEquals(1000, bar.getMaximum(), "scrollbar maximum should equal totalHeight"); + Assertions.assertEquals(300, bar.getThumb(), "scrollbar thumb should equal the viewport height"); + Assertions.assertEquals(120, bar.getSelection(), "scrollbar selection should equal scrollOffset"); + }); + } + + @Test + void testUpdateScrollBar_disabledWhenContentFits() { + SwtUtils.invokeOnDisplayThread(() -> { + sizeViewer(400, 300); + setFieldValue(viewer, "totalHeight", 200); + + invokeVoidMethod(viewer, "updateScrollBar", 300); + + Assertions.assertFalse(viewer.getVerticalBar().getEnabled(), + "scrollbar should be disabled when all content fits"); + }); + } + + @Test + void testIsViewportAtBottom_togglesWhenLeavingAndReturning() { + SwtUtils.invokeOnDisplayThread(() -> { + sizeViewer(400, 300); + setFieldValue(viewer, "totalHeight", 1000); + int maxOffset = invokeIntMethod(viewer, "maxOffset"); + + setFieldValue(viewer, "scrollOffset", maxOffset); + Assertions.assertTrue(invokeBooleanMethod(viewer, "isViewportAtBottom"), + "pinned to the very bottom should report at-bottom"); + + setFieldValue(viewer, "scrollOffset", 0); + Assertions.assertFalse(invokeBooleanMethod(viewer, "isViewportAtBottom"), + "scrolled up to the top should report not-at-bottom"); + + // Just inside the bottom threshold (SCROLL_THRESHOLD = 100) should count as at-bottom again. + setFieldValue(viewer, "scrollOffset", maxOffset - 50); + Assertions.assertTrue(invokeBooleanMethod(viewer, "isViewportAtBottom"), + "back within the bottom threshold should report at-bottom again"); + }); + } + + /** Gives the viewer (and its content child) a deterministic client area for scroll-model math. */ + private void sizeViewer(int width, int height) { + viewer.setSize(width, height); + viewer.layout(true, true); + } + + private int invokeIntMethod(Object target, String name, int arg) { + return (int) invokeMethod(target, name, new Class[] {int.class}, arg); + } + + private int invokeIntMethod(Object target, String name) { + return (int) invokeMethod(target, name, new Class[] {}); + } + + private boolean invokeBooleanMethod(Object target, String name) { + return (boolean) invokeMethod(target, name, new Class[] {}); + } + + private void invokeVoidMethod(Object target, String name, int arg) { + invokeMethod(target, name, new Class[] {int.class}, arg); + } + + private Object invokeMethod(Object target, String name, Class[] paramTypes, Object... args) { + try { + Method method = target.getClass().getDeclaredMethod(name, paramTypes); + method.setAccessible(true); + return method.invoke(target, args); + } catch (Exception e) { + throw new RuntimeException("Failed to invoke method " + name, e); + } + } + private Object getFieldValue(Object target, String fieldName) { try { Field field = target.getClass().getDeclaredField(fieldName); diff --git a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/WorkingSetBarTest.java b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/WorkingSetBarTest.java index d44508a3..3f5a288c 100644 --- a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/WorkingSetBarTest.java +++ b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/WorkingSetBarTest.java @@ -38,6 +38,7 @@ import com.microsoft.copilot.eclipse.ui.CopilotUi; import com.microsoft.copilot.eclipse.ui.chat.services.ChatServiceManager; +import com.microsoft.copilot.eclipse.ui.chat.tools.ChangedFile; import com.microsoft.copilot.eclipse.ui.chat.tools.FileToolService; import com.microsoft.copilot.eclipse.ui.chat.tools.FileToolService.FileChangeProperty; import com.microsoft.copilot.eclipse.ui.utils.SwtUtils; @@ -103,7 +104,7 @@ private void setupMocks() { void testNoScrollForFewFiles() { SwtUtils.invokeOnDisplayThread(() -> { workingSetBar = new WorkingSetBar(parent, SWT.NONE); - Map filesMap = createMockFilesMap(3, false); + Map filesMap = createMockFilesMap(3); workingSetBar.buildSummaryBarFor(filesMap); @@ -122,7 +123,7 @@ void testNoScrollForFewFiles() { void testNoScrollForExactlyMaxFiles() { SwtUtils.invokeOnDisplayThread(() -> { workingSetBar = new WorkingSetBar(parent, SWT.NONE); - Map filesMap = createMockFilesMap(5, false); + Map filesMap = createMockFilesMap(5); workingSetBar.buildSummaryBarFor(filesMap); @@ -141,7 +142,7 @@ void testNoScrollForExactlyMaxFiles() { void testScrollCreatedForManyFiles() { SwtUtils.invokeOnDisplayThread(() -> { workingSetBar = new WorkingSetBar(parent, SWT.NONE); - Map filesMap = createMockFilesMap(10, false); + Map filesMap = createMockFilesMap(10); workingSetBar.buildSummaryBarFor(filesMap); @@ -164,7 +165,7 @@ void testScrollCreatedForManyFiles() { void testScrollHeightHintForManyFiles() { SwtUtils.invokeOnDisplayThread(() -> { workingSetBar = new WorkingSetBar(parent, SWT.NONE); - Map filesMap = createMockFilesMap(8, false); + Map filesMap = createMockFilesMap(8); workingSetBar.buildSummaryBarFor(filesMap); @@ -190,7 +191,7 @@ void testAllFileRowsRenderedWithScroll() { SwtUtils.invokeOnDisplayThread(() -> { workingSetBar = new WorkingSetBar(parent, SWT.NONE); int fileCount = 7; - Map filesMap = createMockFilesMap(fileCount, false); + Map filesMap = createMockFilesMap(fileCount); workingSetBar.buildSummaryBarFor(filesMap); @@ -215,7 +216,7 @@ void testAllFileRowsRenderedWithScroll() { void testContentAreaSetInScrolledComposite() { SwtUtils.invokeOnDisplayThread(() -> { workingSetBar = new WorkingSetBar(parent, SWT.NONE); - Map filesMap = createMockFilesMap(8, false); + Map filesMap = createMockFilesMap(8); workingSetBar.buildSummaryBarFor(filesMap); @@ -242,7 +243,7 @@ void testContentAreaSetInScrolledComposite() { void testMinHeightSetForScrolledComposite() { SwtUtils.invokeOnDisplayThread(() -> { workingSetBar = new WorkingSetBar(parent, SWT.NONE); - Map filesMap = createMockFilesMap(10, false); + Map filesMap = createMockFilesMap(10); workingSetBar.buildSummaryBarFor(filesMap); @@ -266,7 +267,7 @@ void testRebuildSummaryBarChangesScrollBehavior() { workingSetBar = new WorkingSetBar(parent, SWT.NONE); // First build with few files (no scroll) - Map fewFiles = createMockFilesMap(3, false); + Map fewFiles = createMockFilesMap(3); workingSetBar.buildSummaryBarFor(fewFiles); Object changedFiles1 = getFieldValue(workingSetBar, "changedFiles"); @@ -275,7 +276,7 @@ void testRebuildSummaryBarChangesScrollBehavior() { assertNull(scroll1, "No scroll should exist for 3 files"); // Rebuild with many files (should have scroll) - Map manyFiles = createMockFilesMap(10, false); + Map manyFiles = createMockFilesMap(10); workingSetBar.buildSummaryBarFor(manyFiles); Object changedFiles2 = getFieldValue(workingSetBar, "changedFiles"); @@ -294,7 +295,7 @@ void testRebuildSummaryBarChangesScrollBehavior() { void testExpandIconImageWhenExpanded() { SwtUtils.invokeOnDisplayThread(() -> { workingSetBar = new WorkingSetBar(parent, SWT.NONE); - Map filesMap = createMockFilesMap(3, false); + Map filesMap = createMockFilesMap(3); workingSetBar.buildSummaryBarFor(filesMap); @@ -322,7 +323,7 @@ void testExpandIconImageWhenExpanded() { void testExpandIconImageWhenCollapsed() { SwtUtils.invokeOnDisplayThread(() -> { workingSetBar = new WorkingSetBar(parent, SWT.NONE); - Map filesMap = createMockFilesMap(3, false); + Map filesMap = createMockFilesMap(3); workingSetBar.buildSummaryBarFor(filesMap); @@ -354,7 +355,7 @@ void testExpandIconImageWhenCollapsed() { void testTooltipTextWhenExpanded() { SwtUtils.invokeOnDisplayThread(() -> { workingSetBar = new WorkingSetBar(parent, SWT.NONE); - Map filesMap = createMockFilesMap(3, false); + Map filesMap = createMockFilesMap(3); workingSetBar.buildSummaryBarFor(filesMap); @@ -395,7 +396,7 @@ void testTooltipTextWhenExpanded() { void testTooltipTextWhenCollapsed() { SwtUtils.invokeOnDisplayThread(() -> { workingSetBar = new WorkingSetBar(parent, SWT.NONE); - Map filesMap = createMockFilesMap(5, false); + Map filesMap = createMockFilesMap(5); workingSetBar.buildSummaryBarFor(filesMap); @@ -436,7 +437,7 @@ void testTooltipTextWhenCollapsed() { void testTooltipAndImageToggleBehavior() { SwtUtils.invokeOnDisplayThread(() -> { workingSetBar = new WorkingSetBar(parent, SWT.NONE); - Map filesMap = createMockFilesMap(4, false); + Map filesMap = createMockFilesMap(4); workingSetBar.buildSummaryBarFor(filesMap); @@ -476,7 +477,7 @@ void testTooltipContainsCorrectFileCount() { workingSetBar = new WorkingSetBar(parent, SWT.NONE); // Test with 1 file - Map oneFile = createMockFilesMap(1, false); + Map oneFile = createMockFilesMap(1); workingSetBar.buildSummaryBarFor(oneFile); Object titleBar = getFieldValue(workingSetBar, "titleBar"); @@ -488,7 +489,7 @@ void testTooltipContainsCorrectFileCount() { "Tooltip should contain 'file' (singular)"); // Test with 10 files - Map tenFiles = createMockFilesMap(10, false); + Map tenFiles = createMockFilesMap(10); workingSetBar.buildSummaryBarFor(tenFiles); titleBar = getFieldValue(workingSetBar, "titleBar"); @@ -508,7 +509,7 @@ void testTooltipContainsCorrectFileCount() { void testEmptyFilesMapDoesNotCreateChangedFiles() { SwtUtils.invokeOnDisplayThread(() -> { workingSetBar = new WorkingSetBar(parent, SWT.NONE); - Map emptyMap = new LinkedHashMap<>(); + Map emptyMap = new LinkedHashMap<>(); workingSetBar.buildSummaryBarFor(emptyMap); @@ -524,11 +525,11 @@ void testEmptyFilesMapDoesNotCreateChangedFiles() { /** * Creates a map of mock files with the specified count. */ - private Map createMockFilesMap(int count, boolean isHandled) { - Map filesMap = new LinkedHashMap<>(); + private Map createMockFilesMap(int count) { + Map filesMap = new LinkedHashMap<>(); for (int i = 0; i < count; i++) { IFile mockFile = createMockFile("TestFile" + i + ".java"); - filesMap.put(mockFile, new FileChangeProperty(FileChangeType.Created)); + filesMap.put(ChangedFile.workspace(mockFile), new FileChangeProperty(FileChangeType.Created)); } return filesMap; } diff --git a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/FileOperationConfirmationHandlerTests.java b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/FileOperationConfirmationHandlerTests.java new file mode 100644 index 00000000..ba60a62e --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/FileOperationConfirmationHandlerTests.java @@ -0,0 +1,827 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.chat.confirmation; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import org.eclipse.jface.preference.IPreferenceStore; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import com.microsoft.copilot.eclipse.core.Constants; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationAction; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationActionScope; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationContent; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationResult; +import com.microsoft.copilot.eclipse.core.chat.FileOperationAutoApproveRule; +import com.microsoft.copilot.eclipse.core.lsp.protocol.InvokeClientToolConfirmationParams; +import com.microsoft.copilot.eclipse.core.lsp.protocol.ToolMetadata; +import com.microsoft.copilot.eclipse.core.lsp.protocol.ToolMetadata.SensitiveFileData; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class FileOperationConfirmationHandlerTests { + + private static final String CONV_ID = "conv-1"; + private static final Gson GSON = new Gson(); + + @Mock + private IPreferenceStore preferenceStore; + + private AttachedFileRegistry attachedFileRegistry; + private FileOperationConfirmationHandler handler; + + @TempDir + private Path customizationBase; + + @BeforeEach + void setUp() { + attachedFileRegistry = new AttachedFileRegistry(); + handler = new FileOperationConfirmationHandler( + preferenceStore, attachedFileRegistry); + } + + // --- glob matching behavior (tested via evaluate + rules) --- + + @Test + void evaluate_globExactPathMatchCaseInsensitive() { + // Rule uses forward slash + lowercase; evaluate uses backslash + uppercase + stubRules(List.of( + new FileOperationAutoApproveRule("C:/Users/test.java", "", true))); + stubUnmatched(false); + + assertTrue(evaluate( + buildParams("C:\\Users\\test.java", false), CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_globStarStarPatternMatches() { + stubRules(List.of( + new FileOperationAutoApproveRule("**/*.java", "", true))); + stubUnmatched(false); + + assertTrue(evaluate( + buildParams("/workspace/src/Main.java", false), CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_globPatternNoMatch() { + stubRules(List.of( + new FileOperationAutoApproveRule("**/*.py", "", true))); + stubUnmatched(false); + + assertFalse(evaluate( + buildParams("/workspace/src/Main.java", false), CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_globBackslashPathNormalized() { + // Rule uses forward slashes; file path uses backslashes + stubRules(List.of( + new FileOperationAutoApproveRule("**/.github/instructions/*", "", true))); + stubUnmatched(false); + + assertTrue(evaluate( + buildParams("C:\\project\\.github\\instructions\\file.md", false), + CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_invalidGlobRuleFallsThrough() { + // Invalid glob should not match; falls through to unmatched setting + stubRules(List.of( + new FileOperationAutoApproveRule("[invalid", "", true))); + stubUnmatched(true); + + assertTrue(evaluate( + buildParams("/a/b.java", false), CONV_ID).isAutoApproved()); + } + + // --- evaluate: attached files --- + + @Test + void evaluate_autoApprovedWhenFileAttachedViaPending() { + attachedFileRegistry.addPending(List.of("/workspace/src/Main.java")); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_autoApprovedWhenFileAttachedToConversation() { + attachedFileRegistry.addAttachedFiles(CONV_ID, + List.of("/workspace/src/Main.java")); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_attachedFilePathNormalized() { + // Attached with backslashes + uppercase + attachedFileRegistry.addPending( + List.of("C:\\Workspace\\Src\\Main.java")); + + // Evaluate with forward slashes + lowercase + InvokeClientToolConfirmationParams params = + buildParams("c:/workspace/src/Main.java", false); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + // --- evaluate: session overrides --- + + @Test + void evaluate_autoApprovedBySessionFileApproval() { + // Cache a file-level session approval + ConfirmationAction action = buildAction( + FileOperationConfirmationHandler.Action.ACCEPT_FILE_SESSION, + Map.of(FileOperationConfirmationHandler.META_FILE_PATH, + "/workspace/src/Main.java")); + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + handler.cacheDecision(action, params, CONV_ID); + + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_sessionFileApprovalNormalizesPath() { + // Cache with backslash + uppercase + ConfirmationAction action = buildAction( + FileOperationConfirmationHandler.Action.ACCEPT_FILE_SESSION, + Map.of(FileOperationConfirmationHandler.META_FILE_PATH, + "C:\\Workspace\\Main.java")); + handler.cacheDecision(action, + buildParams("C:\\Workspace\\Main.java", false), CONV_ID); + + // Evaluate with forward slash + lowercase + InvokeClientToolConfirmationParams params = + buildParams("c:/workspace/Main.java", false); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_autoApprovedBySessionFolderApproval() { + ConfirmationAction action = buildAction( + FileOperationConfirmationHandler.Action.ACCEPT_FOLDER_SESSION, + Map.of(FileOperationConfirmationHandler.META_FOLDER_PATH, + "/home/user/external")); + handler.cacheDecision(action, + buildParams("/home/user/external/file.txt", true), CONV_ID); + + InvokeClientToolConfirmationParams params = + buildParams("/home/user/external/data.csv", false); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_sessionFolderDoesNotMatchParentPath() { + stubRules(List.of()); + stubUnmatched(false); + + ConfirmationAction action = buildAction( + FileOperationConfirmationHandler.Action.ACCEPT_FOLDER_SESSION, + Map.of(FileOperationConfirmationHandler.META_FOLDER_PATH, + "/home/user/external")); + handler.cacheDecision(action, + buildParams("/home/user/external/file.txt", true), CONV_ID); + + // File in a different folder (prefix but not under the folder) + InvokeClientToolConfirmationParams params = + buildParams("/home/user/external-other/file.txt", false); + assertFalse(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_sessionApprovalDoesNotAffectOtherConversation() { + stubRules(List.of()); + stubUnmatched(false); + + ConfirmationAction action = buildAction( + FileOperationConfirmationHandler.Action.ACCEPT_FILE_SESSION, + Map.of(FileOperationConfirmationHandler.META_FILE_PATH, + "/workspace/src/Main.java")); + handler.cacheDecision(action, + buildParams("/workspace/src/Main.java", false), CONV_ID); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + assertFalse(evaluate(params, "other-conv").isAutoApproved()); + } + + // --- evaluate: outside workspace --- + + @Test + void evaluate_outsideWorkspaceAlwaysRequiresConfirmation() { + InvokeClientToolConfirmationParams params = + buildParams("/tmp/secret.txt", true); + assertFalse(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_outsideWorkspaceStillAutoApprovedBySessionFolder() { + // Session folder approval overrides the outside-workspace check + ConfirmationAction action = buildAction( + FileOperationConfirmationHandler.Action.ACCEPT_FOLDER_SESSION, + Map.of(FileOperationConfirmationHandler.META_FOLDER_PATH, + "/tmp")); + handler.cacheDecision(action, + buildParams("/tmp/file.txt", true), CONV_ID); + + InvokeClientToolConfirmationParams params = + buildParams("/tmp/other.txt", true); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + // --- evaluate: rule matching --- + + @Test + void evaluate_autoApprovedByAllowRule() { + stubRules(List.of( + new FileOperationAutoApproveRule("**/*.java", "", true))); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_needsConfirmationByDenyRule() { + stubRules(List.of( + new FileOperationAutoApproveRule("**/.github/**/*", "", false))); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/.github/instructions/rules.md", false); + ConfirmationResult result = evaluate(params, CONV_ID); + + assertFalse(result.isAutoApproved()); + assertNotNull(result.getContent()); + } + + @Test + void evaluate_firstMatchingRuleWins() { + stubRules(List.of( + new FileOperationAutoApproveRule("**/*.java", "", false), + new FileOperationAutoApproveRule("**/*", "", true))); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + // The first rule (deny .java) should win + assertFalse(evaluate(params, CONV_ID).isAutoApproved()); + } + + // --- evaluate: unmatched fallback --- + + @Test + void evaluate_unmatchedAutoApprovedWhenCheckboxTrue() { + stubRules(List.of( + new FileOperationAutoApproveRule("**/*.py", "", true))); + stubUnmatched(true); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_unmatchedNeedsConfirmationWhenCheckboxFalse() { + stubRules(List.of( + new FileOperationAutoApproveRule("**/*.py", "", true))); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + assertFalse(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_emptyRulesUsesUnmatchedSetting() { + stubRules(List.of()); + stubUnmatched(true); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + // --- evaluate: blank file path --- + + @Test + void evaluate_blankFilePathNeedsConfirmation() { + stubRules(List.of()); + stubUnmatched(true); + + InvokeClientToolConfirmationParams params = + buildParams(null, false); + assertFalse(evaluate(params, CONV_ID).isAutoApproved()); + } + + // --- evaluate: file path extraction --- + + @Test + void evaluate_extractsFilePathFromSensitiveFileData() { + stubRules(List.of( + new FileOperationAutoApproveRule("**/*.java", "", true))); + stubUnmatched(false); + + // Path set via sensitiveFileData (toolMetadata), not input map + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_extractsFilePathFromInputMapFallback() { + stubRules(List.of( + new FileOperationAutoApproveRule("**/*.java", "", true))); + stubUnmatched(false); + + // No toolMetadata, only input map with "filePath" + InvokeClientToolConfirmationParams params = + new InvokeClientToolConfirmationParams(); + params.setConversationId(CONV_ID); + Map input = new HashMap<>(); + input.put("filePath", "/workspace/src/Main.java"); + input.put("toolType", "file_write"); + params.setInput(input); + + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_extractsPathKeyFromInputMapFallback() { + stubRules(List.of( + new FileOperationAutoApproveRule("**/*.java", "", true))); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + new InvokeClientToolConfirmationParams(); + params.setConversationId(CONV_ID); + Map input = new HashMap<>(); + input.put("path", "/workspace/src/Main.java"); + input.put("toolType", "file_write"); + params.setInput(input); + + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + // --- cacheDecision: global rule --- + + @Test + void cacheDecision_globalAddsRuleToPreferenceStore() { + stubRules(List.of()); + + ConfirmationAction action = buildAction( + FileOperationConfirmationHandler.Action.ACCEPT_FILE_GLOBAL, + Map.of(FileOperationConfirmationHandler.META_FILE_PATH, + "/workspace/src/Main.java")); + + handler.cacheDecision(action, + buildParams("/workspace/src/Main.java", false), CONV_ID); + + // The handler should have called setValue on the preference store. + // We verify by loading rules from the same store (which requires + // the mock to return the updated value). Instead, verify the + // store was called with the right key. + org.mockito.Mockito.verify(preferenceStore).setValue( + org.mockito.ArgumentMatchers.eq(Constants.AUTO_APPROVE_FILE_OP_RULES), + org.mockito.ArgumentMatchers.anyString()); + } + + @Test + void cacheDecision_globalUpdatesExistingRuleCaseInsensitive() { + // Start with a deny rule + stubRules(List.of( + new FileOperationAutoApproveRule( + "C:/workspace/Main.java", "", false))); + + ConfirmationAction action = buildAction( + FileOperationConfirmationHandler.Action.ACCEPT_FILE_GLOBAL, + Map.of(FileOperationConfirmationHandler.META_FILE_PATH, + "c:/workspace/Main.java")); + + handler.cacheDecision(action, + buildParams("c:/workspace/Main.java", false), CONV_ID); + + // Verify setValue was called (updated existing rule to autoApprove) + org.mockito.Mockito.verify(preferenceStore).setValue( + org.mockito.ArgumentMatchers.eq(Constants.AUTO_APPROVE_FILE_OP_RULES), + org.mockito.ArgumentMatchers.anyString()); + } + + @Test + void cacheDecision_ignoresUnknownAction() { + Map meta = Map.of( + ConfirmationAction.META_ACTION, "UNKNOWN_ACTION"); + ConfirmationAction action = new ConfirmationAction( + "test", true, ConfirmationActionScope.SESSION, meta, false); + + // Should not throw + handler.cacheDecision(action, + buildParams("/workspace/src/Main.java", false), CONV_ID); + } + + @Test + void cacheDecision_ignoresNullActionMetadata() { + ConfirmationAction action = new ConfirmationAction( + "test", true, ConfirmationActionScope.SESSION, Map.of(), false); + + // Should not throw + handler.cacheDecision(action, + buildParams("/workspace/src/Main.java", false), CONV_ID); + } + + // --- clearSession --- + + @Test + void clearSession_removesFileAndFolderApprovals() { + stubRules(List.of()); + stubUnmatched(false); + + ConfirmationAction fileAction = buildAction( + FileOperationConfirmationHandler.Action.ACCEPT_FILE_SESSION, + Map.of(FileOperationConfirmationHandler.META_FILE_PATH, + "/workspace/src/Main.java")); + handler.cacheDecision(fileAction, + buildParams("/workspace/src/Main.java", false), CONV_ID); + + handler.clearSession(CONV_ID); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + assertFalse(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void clearSession_doesNotAffectOtherConversation() { + stubRules(List.of()); + stubUnmatched(false); + + ConfirmationAction action = buildAction( + FileOperationConfirmationHandler.Action.ACCEPT_FILE_SESSION, + Map.of(FileOperationConfirmationHandler.META_FILE_PATH, + "/workspace/src/Main.java")); + handler.cacheDecision(action, + buildParams("/workspace/src/Main.java", false), CONV_ID); + + handler.clearSession("other-conv"); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void clearSession_clearsAttachedFileRegistry() { + stubRules(List.of()); + stubUnmatched(false); + + attachedFileRegistry.addAttachedFiles(CONV_ID, + List.of("/workspace/src/Main.java")); + + handler.clearSession(CONV_ID); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + assertFalse(evaluate(params, CONV_ID).isAutoApproved()); + } + + // --- buildContent: in-workspace actions --- + + @Test + void buildContent_inWorkspaceHasAllowOnceAsPrimary() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + ConfirmationResult result = evaluate(params, CONV_ID); + + ConfirmationContent content = result.getContent(); + assertNotNull(content); + List actions = content.getActions(); + ConfirmationAction first = actions.get(0); + assertTrue(first.isPrimary()); + assertTrue(first.isAccept()); + assertEquals(ConfirmationActionScope.ONCE, first.getScope()); + } + + @Test + void buildContent_inWorkspaceHasSkipAsDismiss() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + ConfirmationResult result = evaluate(params, CONV_ID); + + List actions = result.getContent().getActions(); + ConfirmationAction last = actions.get(actions.size() - 1); + assertFalse(last.isAccept()); + } + + @Test + void buildContent_inWorkspaceHasFileSessionAndGlobalActions() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + ConfirmationResult result = evaluate(params, CONV_ID); + + List actions = result.getContent().getActions(); + boolean hasFileSession = actions.stream().anyMatch(a -> + hasActionType(a, + FileOperationConfirmationHandler.Action.ACCEPT_FILE_SESSION)); + boolean hasFileGlobal = actions.stream().anyMatch(a -> + hasActionType(a, + FileOperationConfirmationHandler.Action.ACCEPT_FILE_GLOBAL)); + assertTrue(hasFileSession); + assertTrue(hasFileGlobal); + } + + @Test + void buildContent_inWorkspaceNoFolderAction() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + ConfirmationResult result = evaluate(params, CONV_ID); + + List actions = result.getContent().getActions(); + boolean hasFolderSession = actions.stream().anyMatch(a -> + hasActionType(a, + FileOperationConfirmationHandler.Action.ACCEPT_FOLDER_SESSION)); + assertFalse(hasFolderSession); + } + + // --- buildContent: outside-workspace actions --- + + @Test + void buildContent_outsideWorkspaceHasFolderSessionAction() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams("/tmp/data/file.txt", true); + ConfirmationResult result = evaluate(params, CONV_ID); + + List actions = result.getContent().getActions(); + boolean hasFolderSession = actions.stream().anyMatch(a -> + hasActionType(a, + FileOperationConfirmationHandler.Action.ACCEPT_FOLDER_SESSION)); + assertTrue(hasFolderSession); + } + + @Test + void buildContent_outsideWorkspaceNoFileGlobalAction() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams("/tmp/data/file.txt", true); + ConfirmationResult result = evaluate(params, CONV_ID); + + List actions = result.getContent().getActions(); + boolean hasFileGlobal = actions.stream().anyMatch(a -> + hasActionType(a, + FileOperationConfirmationHandler.Action.ACCEPT_FILE_GLOBAL)); + assertFalse(hasFileGlobal); + } + + // --- buildContent: action scopes --- + + @Test + void buildContent_actionScopesAreCorrect() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + ConfirmationResult result = evaluate(params, CONV_ID); + + List actions = result.getContent().getActions(); + + // Session actions have SESSION scope + actions.stream() + .filter(a -> hasActionType(a, + FileOperationConfirmationHandler.Action.ACCEPT_FILE_SESSION)) + .forEach(a -> assertEquals( + ConfirmationActionScope.SESSION, a.getScope())); + + // Global actions have GLOBAL scope + actions.stream() + .filter(a -> hasActionType(a, + FileOperationConfirmationHandler.Action.ACCEPT_FILE_GLOBAL)) + .forEach(a -> assertEquals( + ConfirmationActionScope.GLOBAL, a.getScope())); + } + + // --- evaluate priority order --- + + @Test + void evaluate_priorityOrder_attachedFileBeatsGlobalDenyRule() { + // Attached file auto-approves even when a deny rule would otherwise apply + attachedFileRegistry.addPending( + List.of("/workspace/src/Main.java")); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_priorityOrder_sessionApprovalBeatsGlobalDenyRule() { + // Session-level approval auto-approves even when a deny rule would otherwise apply + ConfirmationAction action = buildAction( + FileOperationConfirmationHandler.Action.ACCEPT_FILE_SESSION, + Map.of(FileOperationConfirmationHandler.META_FILE_PATH, + "/workspace/src/Main.java")); + handler.cacheDecision(action, + buildParams("/workspace/src/Main.java", false), CONV_ID); + + InvokeClientToolConfirmationParams params = + buildParams("/workspace/src/Main.java", false); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void evaluate_priorityOrder_sessionFolderBeatsOutsideWorkspace() { + // Session folder approval auto-approves even for outside-workspace files + ConfirmationAction action = buildAction( + FileOperationConfirmationHandler.Action.ACCEPT_FOLDER_SESSION, + Map.of(FileOperationConfirmationHandler.META_FOLDER_PATH, + "/external/dir")); + handler.cacheDecision(action, + buildParams("/external/dir/file.txt", true), CONV_ID); + + InvokeClientToolConfirmationParams params = + buildParams("/external/dir/another.txt", true); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + // --- customization file read recognition (isCustomizationRead) --- + + private Set customizationFiles() { + return Set.of( + customizationBase.resolve(".github/prompts/example.prompt.md"), + customizationBase.resolve(".github/instructions/coding.instructions.md"), + customizationBase.resolve(".github/agents/my.agent.md")); + } + + private Set skillFolders() { + return Set.of(customizationBase.resolve(".github/skills/demo")); + } + + @Test + void isCustomizationRead_promptFileExactMatch_isTrue() { + Path prompt = customizationBase.resolve(".github/prompts/example.prompt.md"); + assertTrue(FileOperationConfirmationHandler.isCustomizationRead( + prompt, customizationFiles(), skillFolders())); + } + + @Test + void isCustomizationRead_instructionFileExactMatch_isTrue() { + Path instruction = customizationBase.resolve(".github/instructions/coding.instructions.md"); + assertTrue(FileOperationConfirmationHandler.isCustomizationRead( + instruction, customizationFiles(), skillFolders())); + } + + @Test + void isCustomizationRead_agentFileExactMatch_isTrue() { + Path agent = customizationBase.resolve(".github/agents/my.agent.md"); + assertTrue(FileOperationConfirmationHandler.isCustomizationRead( + agent, customizationFiles(), skillFolders())); + } + + @Test + void isCustomizationRead_skillMarkdownInsideFolder_isTrue() { + Path skill = customizationBase.resolve(".github/skills/demo/SKILL.md"); + assertTrue(FileOperationConfirmationHandler.isCustomizationRead( + skill, customizationFiles(), skillFolders())); + } + + @Test + void isCustomizationRead_skillHelperFileInsideFolder_isTrue() { + Path helper = customizationBase.resolve(".github/skills/demo/notes.md"); + assertTrue(FileOperationConfirmationHandler.isCustomizationRead( + helper, customizationFiles(), skillFolders())); + } + + @Test + void isCustomizationRead_nestedSkillHelperFile_isTrue() { + Path helper = customizationBase.resolve(".github/skills/demo/scripts/run.py"); + assertTrue(FileOperationConfirmationHandler.isCustomizationRead( + helper, customizationFiles(), skillFolders())); + } + + @Test + void isCustomizationRead_unrelatedFile_isFalse() { + Path other = customizationBase.resolve("src/Main.java"); + assertFalse(FileOperationConfirmationHandler.isCustomizationRead( + other, customizationFiles(), skillFolders())); + } + + @Test + void isCustomizationRead_promptOutsideReportedSet_isFalse() { + // A *.prompt.md the language server did not report must not be auto-approved. + Path loose = customizationBase.resolve("docs/other.prompt.md"); + assertFalse(FileOperationConfirmationHandler.isCustomizationRead( + loose, customizationFiles(), skillFolders())); + } + + @Test + void isCustomizationRead_fileInUnreportedSkillFolder_isFalse() { + Path other = customizationBase.resolve(".github/skills/other/SKILL.md"); + assertFalse(FileOperationConfirmationHandler.isCustomizationRead( + other, customizationFiles(), skillFolders())); + } + + @Test + void isCustomizationRead_emptyInputs_isFalse() { + Path prompt = customizationBase.resolve(".github/prompts/example.prompt.md"); + assertFalse(FileOperationConfirmationHandler.isCustomizationRead( + prompt, Set.of(), Set.of())); + } + + // --- Helpers --- + + private void stubRules(List rules) { + when(preferenceStore.getString(Constants.AUTO_APPROVE_FILE_OP_RULES)) + .thenReturn(GSON.toJson(rules)); + } + + private void stubUnmatched(boolean value) { + when(preferenceStore.getBoolean( + Constants.AUTO_APPROVE_UNMATCHED_FILE_OP)).thenReturn(value); + } + + private ConfirmationResult evaluate( + InvokeClientToolConfirmationParams params, String conversationId) { + return handler.evaluate(params, conversationId, true); + } + + private static InvokeClientToolConfirmationParams buildParams( + String filePath, boolean isGlobal) { + InvokeClientToolConfirmationParams params = + new InvokeClientToolConfirmationParams(); + params.setConversationId(CONV_ID); + + if (filePath != null) { + SensitiveFileData sfd = new SensitiveFileData(); + sfd.setFilePath(filePath); + sfd.setGlobal(isGlobal); + + ToolMetadata meta = new ToolMetadata(); + meta.setSensitiveFileData(sfd); + params.setToolMetadata(meta); + } + + Map input = new HashMap<>(); + input.put("toolType", "file_write"); + if (filePath != null) { + input.put("filePath", filePath); + } + params.setInput(input); + return params; + } + + private static ConfirmationAction buildAction( + FileOperationConfirmationHandler.Action actionType, + Map extra) { + Map meta = new HashMap<>(extra); + meta.put(ConfirmationAction.META_ACTION, actionType.name()); + return new ConfirmationAction( + "test", true, ConfirmationActionScope.SESSION, meta, false); + } + + private static boolean hasActionType(ConfirmationAction action, + FileOperationConfirmationHandler.Action type) { + return action.getMetadata().containsKey(ConfirmationAction.META_ACTION) + && action.getMetadata().get(ConfirmationAction.META_ACTION) + .equals(type.name()); + } +} diff --git a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/McpConfirmationHandlerTests.java b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/McpConfirmationHandlerTests.java new file mode 100644 index 00000000..4380439b --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/McpConfirmationHandlerTests.java @@ -0,0 +1,460 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.chat.confirmation; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import org.eclipse.jface.preference.IPreferenceStore; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import com.microsoft.copilot.eclipse.core.Constants; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationAction; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationActionScope; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationContent; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationResult; +import com.microsoft.copilot.eclipse.core.lsp.protocol.InvokeClientToolConfirmationParams; +import com.microsoft.copilot.eclipse.core.lsp.protocol.ToolAnnotations; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class McpConfirmationHandlerTests { + + private static final String CONV_ID = "conv-mcp-1"; + private static final String SERVER = "myServer"; + private static final String TOOL = "myTool"; + private static final Gson GSON = new Gson(); + + @Mock + private IPreferenceStore preferenceStore; + + private McpConfirmationHandler handler; + + @BeforeEach + void setUp() { + handler = new McpConfirmationHandler(preferenceStore); + stubGlobalServers(List.of()); + stubGlobalTools(List.of()); + stubTrustAnnotations(false); + } + + // --- evaluate: global server list --- + + @Test + void evaluate_autoApprovedWhenServerInGlobalList() { + stubGlobalServers(List.of(SERVER)); + + ConfirmationResult result = evaluate( + buildParams(SERVER, TOOL), CONV_ID); + + assertTrue(result.isAutoApproved()); + } + + @Test + void evaluate_autoApprovedWhenServerInGlobalListCaseInsensitive() { + stubGlobalServers(List.of(SERVER.toUpperCase())); + + ConfirmationResult result = evaluate( + buildParams(SERVER.toLowerCase(), TOOL), CONV_ID); + + assertTrue(result.isAutoApproved()); + } + + @Test + void evaluate_notAutoApprovedWhenServerNotInGlobalList() { + stubGlobalServers(List.of("otherServer")); + + ConfirmationResult result = evaluate( + buildParams(SERVER, TOOL), CONV_ID); + + assertFalse(result.isAutoApproved()); + } + + // --- evaluate: global tool list --- + + @Test + void evaluate_autoApprovedWhenToolInGlobalList() { + String toolKey = SERVER.toLowerCase() + "::" + TOOL.toLowerCase(); + stubGlobalTools(List.of(toolKey)); + + ConfirmationResult result = evaluate( + buildParams(SERVER, TOOL), CONV_ID); + + assertTrue(result.isAutoApproved()); + } + + @Test + void evaluate_autoApprovedWhenToolInGlobalListCaseInsensitive() { + String toolKey = SERVER.toUpperCase() + "::" + TOOL.toUpperCase(); + stubGlobalTools(List.of(toolKey)); + + ConfirmationResult result = evaluate( + buildParams(SERVER.toLowerCase(), TOOL.toLowerCase()), CONV_ID); + + assertTrue(result.isAutoApproved()); + } + + @Test + void evaluate_notAutoApprovedWhenOnlyOtherToolInGlobalList() { + String otherKey = SERVER.toLowerCase() + "::otherTool"; + stubGlobalTools(List.of(otherKey)); + + ConfirmationResult result = evaluate( + buildParams(SERVER, TOOL), CONV_ID); + + assertFalse(result.isAutoApproved()); + } + + // --- evaluate: trust annotations --- + + @Test + void evaluate_autoApprovedWhenReadOnlyAndTrustAnnotationsEnabled() { + stubTrustAnnotations(true); + ToolAnnotations annotations = new ToolAnnotations(); + annotations.setReadOnlyHint(true); + annotations.setOpenWorldHint(false); + + InvokeClientToolConfirmationParams params = buildParams(SERVER, TOOL); + params.setAnnotations(annotations); + + ConfirmationResult result = evaluate(params, CONV_ID); + + assertTrue(result.isAutoApproved()); + } + + @Test + void evaluate_notAutoApprovedWhenReadOnlyButOpenWorldHint() { + stubTrustAnnotations(true); + ToolAnnotations annotations = new ToolAnnotations(); + annotations.setReadOnlyHint(true); + annotations.setOpenWorldHint(true); + + InvokeClientToolConfirmationParams params = buildParams(SERVER, TOOL); + params.setAnnotations(annotations); + + ConfirmationResult result = evaluate(params, CONV_ID); + + assertFalse(result.isAutoApproved()); + } + + @Test + void evaluate_notAutoApprovedWhenAnnotationsTrustedButNotReadOnly() { + stubTrustAnnotations(true); + ToolAnnotations annotations = new ToolAnnotations(); + annotations.setReadOnlyHint(false); + annotations.setOpenWorldHint(false); + + InvokeClientToolConfirmationParams params = buildParams(SERVER, TOOL); + params.setAnnotations(annotations); + + ConfirmationResult result = evaluate(params, CONV_ID); + + assertFalse(result.isAutoApproved()); + } + + @Test + void evaluate_notAutoApprovedWhenReadOnlyButTrustAnnotationsDisabled() { + stubTrustAnnotations(false); + ToolAnnotations annotations = new ToolAnnotations(); + annotations.setReadOnlyHint(true); + annotations.setOpenWorldHint(false); + + InvokeClientToolConfirmationParams params = buildParams(SERVER, TOOL); + params.setAnnotations(annotations); + + ConfirmationResult result = evaluate(params, CONV_ID); + + assertFalse(result.isAutoApproved()); + } + + // --- evaluate: session approvals --- + + @Test + void evaluate_autoApprovedWhenToolApprovedForSession() { + InvokeClientToolConfirmationParams params = buildParams(SERVER, TOOL); + ConfirmationAction action = buildAction( + McpConfirmationHandler.Action.ACCEPT_TOOL_SESSION, + Map.of(McpConfirmationHandler.META_TOOL_KEY, + SERVER.toLowerCase() + "::" + TOOL.toLowerCase())); + handler.cacheDecision(action, params, CONV_ID); + + ConfirmationResult result = evaluate(params, CONV_ID); + + assertTrue(result.isAutoApproved()); + } + + @Test + void evaluate_notAutoApprovedWhenToolApprovedForDifferentSession() { + InvokeClientToolConfirmationParams params = buildParams(SERVER, TOOL); + ConfirmationAction action = buildAction( + McpConfirmationHandler.Action.ACCEPT_TOOL_SESSION, + Map.of(McpConfirmationHandler.META_TOOL_KEY, + SERVER.toLowerCase() + "::" + TOOL.toLowerCase())); + handler.cacheDecision(action, params, "other-conv"); + + ConfirmationResult result = evaluate(params, CONV_ID); + + assertFalse(result.isAutoApproved()); + } + + @Test + void evaluate_autoApprovedWhenServerApprovedForSession() { + InvokeClientToolConfirmationParams params = buildParams(SERVER, TOOL); + ConfirmationAction action = buildAction( + McpConfirmationHandler.Action.ACCEPT_SERVER_SESSION, + Map.of(McpConfirmationHandler.META_SERVER_NAME, SERVER)); + handler.cacheDecision(action, params, CONV_ID); + + ConfirmationResult result = evaluate(params, CONV_ID); + + assertTrue(result.isAutoApproved()); + } + + // --- cacheDecision: global persistence --- + + @Test + void cacheDecision_acceptToolGlobal_writesToPreferenceStore() { + String toolKey = SERVER.toLowerCase() + "::" + TOOL.toLowerCase(); + stubGlobalTools(List.of()); + + ConfirmationAction action = buildAction( + McpConfirmationHandler.Action.ACCEPT_TOOL_GLOBAL, + Map.of(McpConfirmationHandler.META_TOOL_KEY, toolKey)); + handler.cacheDecision(action, buildParams(SERVER, TOOL), CONV_ID); + + ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); + verify(preferenceStore).setValue( + org.mockito.ArgumentMatchers.eq(Constants.AUTO_APPROVE_MCP_TOOLS), + captor.capture()); + assertTrue(captor.getValue().contains(toolKey)); + } + + @Test + void cacheDecision_acceptServerGlobal_writesToPreferenceStore() { + stubGlobalServers(List.of()); + + ConfirmationAction action = buildAction( + McpConfirmationHandler.Action.ACCEPT_SERVER_GLOBAL, + Map.of(McpConfirmationHandler.META_SERVER_NAME, SERVER)); + handler.cacheDecision(action, buildParams(SERVER, TOOL), CONV_ID); + + ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); + verify(preferenceStore).setValue( + org.mockito.ArgumentMatchers.eq( + Constants.AUTO_APPROVE_MCP_SERVERS), + captor.capture()); + assertTrue(captor.getValue().contains(SERVER)); + } + + @Test + void cacheDecision_acceptToolGlobal_noDuplicateWrite() { + String toolKey = SERVER.toLowerCase() + "::" + TOOL.toLowerCase(); + stubGlobalTools(List.of(toolKey)); + + ConfirmationAction action = buildAction( + McpConfirmationHandler.Action.ACCEPT_TOOL_GLOBAL, + Map.of(McpConfirmationHandler.META_TOOL_KEY, toolKey)); + handler.cacheDecision(action, buildParams(SERVER, TOOL), CONV_ID); + + // setValue should NOT be called — key already present + verify(preferenceStore, org.mockito.Mockito.never()) + .setValue(org.mockito.ArgumentMatchers.eq( + Constants.AUTO_APPROVE_MCP_TOOLS), + org.mockito.ArgumentMatchers.anyString()); + } + + // --- clearSession --- + + @Test + void clearSession_removesSessionApprovalsForConversation() { + InvokeClientToolConfirmationParams params = buildParams(SERVER, TOOL); + ConfirmationAction action = buildAction( + McpConfirmationHandler.Action.ACCEPT_TOOL_SESSION, + Map.of(McpConfirmationHandler.META_TOOL_KEY, + SERVER.toLowerCase() + "::" + TOOL.toLowerCase())); + handler.cacheDecision(action, params, CONV_ID); + + handler.clearSession(CONV_ID); + + ConfirmationResult result = evaluate(params, CONV_ID); + assertFalse(result.isAutoApproved()); + } + + @Test + void clearSession_doesNotAffectOtherConversation() { + InvokeClientToolConfirmationParams params = buildParams(SERVER, TOOL); + ConfirmationAction action = buildAction( + McpConfirmationHandler.Action.ACCEPT_TOOL_SESSION, + Map.of(McpConfirmationHandler.META_TOOL_KEY, + SERVER.toLowerCase() + "::" + TOOL.toLowerCase())); + handler.cacheDecision(action, params, CONV_ID); + + handler.clearSession("other-conv"); + + ConfirmationResult result = evaluate(params, CONV_ID); + assertTrue(result.isAutoApproved()); + } + + // --- buildContent (actions) --- + + @Test + void buildContent_hasAllowOnceAsFirstAction() { + ConfirmationResult result = evaluate( + buildParams(SERVER, TOOL), CONV_ID); + + List actions = result.getContent().getActions(); + assertTrue(actions.get(0).isPrimary()); + assertTrue(actions.get(0).isAccept()); + assertEquals(ConfirmationActionScope.ONCE, actions.get(0).getScope()); + } + + @Test + void buildContent_hasSkipAsLastAction() { + ConfirmationResult result = evaluate( + buildParams(SERVER, TOOL), CONV_ID); + + List actions = result.getContent().getActions(); + assertFalse(actions.get(actions.size() - 1).isAccept()); + } + + @Test + void buildContent_hasAllFourScopedActions() { + ConfirmationResult result = evaluate( + buildParams(SERVER, TOOL), CONV_ID); + + List actions = result.getContent().getActions(); + assertTrue(hasAction(actions, + McpConfirmationHandler.Action.ACCEPT_TOOL_SESSION)); + assertTrue(hasAction(actions, + McpConfirmationHandler.Action.ACCEPT_TOOL_GLOBAL)); + assertTrue(hasAction(actions, + McpConfirmationHandler.Action.ACCEPT_SERVER_SESSION)); + assertTrue(hasAction(actions, + McpConfirmationHandler.Action.ACCEPT_SERVER_GLOBAL)); + } + + @Test + void buildContent_toolAndServerActionsHaveCorrectScopes() { + ConfirmationResult result = evaluate( + buildParams(SERVER, TOOL), CONV_ID); + + List actions = result.getContent().getActions(); + actions.stream() + .filter(a -> hasAction(a, + McpConfirmationHandler.Action.ACCEPT_TOOL_SESSION) + || hasAction(a, + McpConfirmationHandler.Action.ACCEPT_SERVER_SESSION)) + .forEach(a -> assertEquals( + ConfirmationActionScope.SESSION, a.getScope())); + actions.stream() + .filter(a -> hasAction(a, + McpConfirmationHandler.Action.ACCEPT_TOOL_GLOBAL) + || hasAction(a, + McpConfirmationHandler.Action.ACCEPT_SERVER_GLOBAL)) + .forEach(a -> assertEquals( + ConfirmationActionScope.GLOBAL, a.getScope())); + } + + @Test + void buildContent_contentHasTitleWithToolAndServer() { + ConfirmationResult result = evaluate( + buildParams(SERVER, TOOL), CONV_ID); + + ConfirmationContent content = result.getContent(); + assertNotNull(content); + assertNotNull(content.getTitle()); + assertTrue(content.getTitle().contains(TOOL)); + assertTrue(content.getTitle().contains(SERVER)); + } + + @Test + void buildContent_noActionsWhenServerAndToolNull() { + InvokeClientToolConfirmationParams params = + buildParams(null, null); + + ConfirmationResult result = evaluate(params, CONV_ID); + + assertFalse(result.isAutoApproved()); + List actions = result.getContent().getActions(); + assertFalse(hasAction(actions, + McpConfirmationHandler.Action.ACCEPT_TOOL_SESSION)); + assertFalse(hasAction(actions, + McpConfirmationHandler.Action.ACCEPT_SERVER_SESSION)); + } + + // --- Helpers --- + + private void stubGlobalServers(List servers) { + when(preferenceStore.getString(Constants.AUTO_APPROVE_MCP_SERVERS)) + .thenReturn(GSON.toJson(servers)); + } + + private void stubGlobalTools(List tools) { + when(preferenceStore.getString(Constants.AUTO_APPROVE_MCP_TOOLS)) + .thenReturn(GSON.toJson(tools)); + } + + private void stubTrustAnnotations(boolean value) { + when(preferenceStore.getBoolean( + Constants.AUTO_APPROVE_TRUST_TOOL_ANNOTATIONS)) + .thenReturn(value); + } + + private ConfirmationResult evaluate( + InvokeClientToolConfirmationParams params, String conversationId) { + return handler.evaluate(params, conversationId, true); + } + + private static InvokeClientToolConfirmationParams buildParams( + String serverName, String toolName) { + InvokeClientToolConfirmationParams params = + new InvokeClientToolConfirmationParams(); + params.setConversationId(CONV_ID); + Map input = new java.util.HashMap<>(); + input.put("toolType", "mcp_tool"); + if (serverName != null) { + input.put("mcpServerName", serverName); + } + if (toolName != null) { + input.put("mcpToolName", toolName); + } + params.setInput(input); + return params; + } + + private static ConfirmationAction buildAction( + McpConfirmationHandler.Action type, Map extra) { + Map meta = new java.util.HashMap<>(extra); + meta.put(ConfirmationAction.META_ACTION, type.name()); + return new ConfirmationAction( + "test", true, ConfirmationActionScope.SESSION, meta, false); + } + + private static boolean hasAction(List actions, + McpConfirmationHandler.Action type) { + return actions.stream().anyMatch(a -> hasAction(a, type)); + } + + private static boolean hasAction(ConfirmationAction action, + McpConfirmationHandler.Action type) { + return action.getMetadata().containsKey(ConfirmationAction.META_ACTION) + && action.getMetadata().get(ConfirmationAction.META_ACTION) + .equals(type.name()); + } +} diff --git a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/TerminalConfirmationHandlerTests.java b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/TerminalConfirmationHandlerTests.java new file mode 100644 index 00000000..5cb11e3e --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/TerminalConfirmationHandlerTests.java @@ -0,0 +1,650 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.chat.confirmation; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import org.eclipse.jface.preference.IPreferenceStore; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import com.microsoft.copilot.eclipse.core.Constants; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationAction; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationActionScope; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationContent; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationResult; +import com.microsoft.copilot.eclipse.core.chat.TerminalAutoApproveRule; +import com.microsoft.copilot.eclipse.core.lsp.protocol.InvokeClientToolConfirmationParams; +import com.microsoft.copilot.eclipse.core.lsp.protocol.ToolMetadata; +import com.microsoft.copilot.eclipse.core.lsp.protocol.ToolMetadata.TerminalCommandData; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class TerminalConfirmationHandlerTests { + + private static final String CONV_ID = "conv-1"; + private static final Gson GSON = new Gson(); + + @Mock + private IPreferenceStore preferenceStore; + + private TerminalConfirmationHandler handler; + + @BeforeEach + void setUp() { + handler = new TerminalConfirmationHandler(preferenceStore); + } + + // --- rule matching (tested through evaluate) --- + + @Test + void ruleMatching_simpleRuleMatchesCommandAtStart() { + stubRules(List.of(new TerminalAutoApproveRule("rm", true))); + stubUnmatched(false); + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"rm -rf /tmp"}, new String[]{"rm"}, + "rm -rf /tmp"); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void ruleMatching_simpleRuleDoesNotMatchMiddleOfWord() { + stubRules(List.of(new TerminalAutoApproveRule("rm", true))); + stubUnmatched(false); + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"remove something"}, + new String[]{"remove"}, "remove something"); + assertFalse(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void ruleMatching_regexCaseInsensitive() { + stubRules(List.of(new TerminalAutoApproveRule("/^git\\b/i", true))); + stubUnmatched(false); + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"Git status"}, new String[]{"Git"}, + "Git status"); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void ruleMatching_regexDotallMatchesSubshell() { + stubRules(List.of( + new TerminalAutoApproveRule("/(\\(.+\\))/s", true))); + stubUnmatched(false); + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"(echo hello)"}, + new String[]{"(echo"}, "(echo hello)"); + assertTrue(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void ruleMatching_noMatchWhenSubCommandsNull() { + stubRules(List.of(new TerminalAutoApproveRule("rm", true))); + stubUnmatched(false); + InvokeClientToolConfirmationParams params = + buildParams(null, null, "rm -rf"); + assertFalse(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void ruleMatching_noMatchWhenSubCommandsEmpty() { + stubRules(List.of(new TerminalAutoApproveRule("rm", true))); + stubUnmatched(false); + InvokeClientToolConfirmationParams params = + buildParams(new String[]{}, new String[]{}, "rm -rf"); + assertFalse(evaluate(params, CONV_ID).isAutoApproved()); + } + + @Test + void ruleMatching_noMatchWhenSubCommandBlank() { + stubRules(List.of(new TerminalAutoApproveRule("rm", true))); + stubUnmatched(false); + InvokeClientToolConfirmationParams params = + buildParams(new String[]{" "}, new String[]{" "}, " "); + assertFalse(evaluate(params, CONV_ID).isAutoApproved()); + } + + // --- evaluate --- + + @Test + void evaluate_autoApprovedWhenAllSubCommandsMatchAllowRules() { + stubRules(List.of(new TerminalAutoApproveRule("echo", true))); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"echo hello"}, new String[]{"echo"}, + "echo hello"); + ConfirmationResult result = evaluate(params, CONV_ID); + + assertTrue(result.isAutoApproved()); + } + + @Test + void evaluate_needsConfirmationWhenDenyRuleMatches() { + stubRules(List.of(new TerminalAutoApproveRule("rm", false))); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"rm -rf /"}, new String[]{"rm"}, + "rm -rf /"); + ConfirmationResult result = evaluate(params, CONV_ID); + + assertFalse(result.isAutoApproved()); + assertNotNull(result.getContent()); + } + + @Test + void evaluate_needsConfirmationWhenNoRulesMatchAndUnmatchedFalse() { + stubRules(List.of(new TerminalAutoApproveRule("echo", true))); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"ls -la"}, new String[]{"ls"}, + "ls -la"); + ConfirmationResult result = evaluate(params, CONV_ID); + + assertFalse(result.isAutoApproved()); + } + + @Test + void evaluate_autoApprovedWhenNoRulesMatchAndUnmatchedTrue() { + stubRules(List.of(new TerminalAutoApproveRule("echo", true))); + stubUnmatched(true); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"ls -la"}, new String[]{"ls"}, + "ls -la"); + ConfirmationResult result = evaluate(params, CONV_ID); + + assertTrue(result.isAutoApproved()); + } + + @Test + void evaluate_needsConfirmationWhenSubCommandsNull() { + stubRules(List.of()); + + InvokeClientToolConfirmationParams params = + buildParams(null, null, "echo hello"); + ConfirmationResult result = evaluate(params, CONV_ID); + + assertFalse(result.isAutoApproved()); + } + + @Test + void evaluate_needsConfirmationWhenSubCommandsEmpty() { + stubRules(List.of()); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{}, null, "echo hello"); + ConfirmationResult result = evaluate(params, CONV_ID); + + assertFalse(result.isAutoApproved()); + } + + @Test + void evaluate_emptyRulesUsesUnmatchedSetting() { + stubRules(List.of()); + stubUnmatched(true); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"ls"}, new String[]{"ls"}, "ls"); + ConfirmationResult result = evaluate(params, CONV_ID); + + assertTrue(result.isAutoApproved()); + } + + // --- Session memory via cacheDecision --- + + @Test + void cacheDecision_acceptAllSession_autoApprovesSubsequent() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"echo"}, new String[]{"echo"}, + "echo hello"); + + ConfirmationAction allSession = buildSessionAction( + TerminalConfirmationHandler.Action.ACCEPT_ALL_SESSION); + handler.cacheDecision(allSession, params, CONV_ID); + + ConfirmationResult result = evaluate(params, CONV_ID); + assertTrue(result.isAutoApproved()); + } + + @Test + void cacheDecision_acceptNamesSession_autoApprovesMatchingNames() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"echo"}, new String[]{"echo"}, + "echo hello"); + + ConfirmationAction namesSession = buildSessionAction( + TerminalConfirmationHandler.Action.ACCEPT_NAMES_SESSION); + handler.cacheDecision(namesSession, params, CONV_ID); + + ConfirmationResult result = evaluate(params, CONV_ID); + assertTrue(result.isAutoApproved()); + } + + @Test + void cacheDecision_acceptExactSession_autoApprovesMatchingCommand() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"echo"}, new String[]{"echo"}, + "echo hello"); + + ConfirmationAction exactSession = buildSessionAction( + TerminalConfirmationHandler.Action.ACCEPT_EXACT_SESSION); + handler.cacheDecision(exactSession, params, CONV_ID); + + ConfirmationResult result = evaluate(params, CONV_ID); + assertTrue(result.isAutoApproved()); + } + + @Test + void clearSession_removesApprovalsForConversation() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"echo"}, new String[]{"echo"}, + "echo hello"); + + ConfirmationAction allSession = buildSessionAction( + TerminalConfirmationHandler.Action.ACCEPT_ALL_SESSION); + handler.cacheDecision(allSession, params, CONV_ID); + + handler.clearSession(CONV_ID); + + ConfirmationResult result = evaluate(params, CONV_ID); + assertFalse(result.isAutoApproved()); + } + + @Test + void clearSession_doesNotAffectOtherConversation() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"echo"}, new String[]{"echo"}, + "echo hello"); + + ConfirmationAction allSession = buildSessionAction( + TerminalConfirmationHandler.Action.ACCEPT_ALL_SESSION); + handler.cacheDecision(allSession, params, CONV_ID); + + handler.clearSession("other-conv"); + + ConfirmationResult result = evaluate(params, CONV_ID); + assertTrue(result.isAutoApproved()); + } + + // --- buildContent actions --- + + @Test + void buildContent_alwaysHasAllowOnceAsPrimary() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"echo"}, new String[]{"echo"}, + "echo hello"); + ConfirmationResult result = evaluate(params, CONV_ID); + + ConfirmationContent content = result.getContent(); + assertNotNull(content); + List actions = content.getActions(); + ConfirmationAction first = actions.get(0); + assertTrue(first.isPrimary()); + assertTrue(first.isAccept()); + } + + @Test + void buildContent_alwaysHasSkipAsDismiss() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"echo"}, new String[]{"echo"}, + "echo hello"); + ConfirmationResult result = evaluate(params, CONV_ID); + + List actions = result.getContent().getActions(); + ConfirmationAction last = actions.get(actions.size() - 1); + assertFalse(last.isAccept()); + } + + @Test + void buildContent_hasAllowAllSessionAction() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"echo"}, new String[]{"echo"}, + "echo hello"); + ConfirmationResult result = evaluate(params, CONV_ID); + + List actions = result.getContent().getActions(); + boolean hasAllSession = actions.stream().anyMatch(a -> + a.getMetadata().containsKey(ConfirmationAction.META_ACTION) + && a.getMetadata().get(ConfirmationAction.META_ACTION) + .equals( + TerminalConfirmationHandler.Action.ACCEPT_ALL_SESSION + .name())); + assertTrue(hasAllSession); + } + + @Test + void buildContent_hasCommandNameActionsWhenNamesPresent() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"echo"}, new String[]{"echo"}, + "echo hello"); + ConfirmationResult result = evaluate(params, CONV_ID); + + List actions = result.getContent().getActions(); + boolean hasNamesSession = actions.stream().anyMatch(a -> + hasActionType(a, + TerminalConfirmationHandler.Action.ACCEPT_NAMES_SESSION)); + boolean hasNamesGlobal = actions.stream().anyMatch(a -> + hasActionType(a, + TerminalConfirmationHandler.Action.ACCEPT_NAMES_GLOBAL)); + assertTrue(hasNamesSession); + assertTrue(hasNamesGlobal); + } + + @Test + void buildContent_hasExactCommandActionsWhenDifferentFromName() { + stubRules(List.of()); + stubUnmatched(false); + + // commandLine "echo hello" differs from single commandName "echo" + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"echo"}, new String[]{"echo"}, + "echo hello"); + ConfirmationResult result = evaluate(params, CONV_ID); + + List actions = result.getContent().getActions(); + boolean hasExactSession = actions.stream().anyMatch(a -> + hasActionType(a, + TerminalConfirmationHandler.Action.ACCEPT_EXACT_SESSION)); + boolean hasExactGlobal = actions.stream().anyMatch(a -> + hasActionType(a, + TerminalConfirmationHandler.Action.ACCEPT_EXACT_GLOBAL)); + assertTrue(hasExactSession); + assertTrue(hasExactGlobal); + } + + @Test + void buildContent_noExactActionsWhenSingleSubCommandEqualsName() { + stubRules(List.of()); + stubUnmatched(false); + + // commandLine equals the single commandName + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"echo"}, new String[]{"echo"}, "echo"); + ConfirmationResult result = evaluate(params, CONV_ID); + + List actions = result.getContent().getActions(); + boolean hasExact = actions.stream().anyMatch(a -> + hasActionType(a, + TerminalConfirmationHandler.Action.ACCEPT_EXACT_SESSION) + || hasActionType(a, + TerminalConfirmationHandler.Action.ACCEPT_EXACT_GLOBAL)); + assertFalse(hasExact); + } + + @Test + void buildContent_actionScopesAreCorrect() { + stubRules(List.of()); + stubUnmatched(false); + + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"echo"}, new String[]{"echo"}, + "echo hello"); + ConfirmationResult result = evaluate(params, CONV_ID); + + List actions = result.getContent().getActions(); + + // Allow Once → ONCE scope + assertEquals(ConfirmationActionScope.ONCE, actions.get(0).getScope()); + + // Session actions have SESSION scope + actions.stream() + .filter(a -> hasActionType(a, + TerminalConfirmationHandler.Action.ACCEPT_NAMES_SESSION) + || hasActionType(a, + TerminalConfirmationHandler.Action.ACCEPT_EXACT_SESSION) + || hasActionType(a, + TerminalConfirmationHandler.Action.ACCEPT_ALL_SESSION)) + .forEach(a -> assertEquals(ConfirmationActionScope.SESSION, + a.getScope())); + + // Global actions have GLOBAL scope + actions.stream() + .filter(a -> hasActionType(a, + TerminalConfirmationHandler.Action.ACCEPT_NAMES_GLOBAL) + || hasActionType(a, + TerminalConfirmationHandler.Action.ACCEPT_EXACT_GLOBAL)) + .forEach(a -> assertEquals(ConfirmationActionScope.GLOBAL, + a.getScope())); + } + + // --- Helpers --- + + private void stubRules(List rules) { + when(preferenceStore.getString(Constants.AUTO_APPROVE_TERMINAL_RULES)) + .thenReturn(GSON.toJson(rules)); + } + + private void stubUnmatched(boolean value) { + when(preferenceStore.getBoolean( + Constants.AUTO_APPROVE_UNMATCHED_TERMINAL)).thenReturn(value); + } + + private ConfirmationResult evaluate( + InvokeClientToolConfirmationParams params, String conversationId) { + return handler.evaluate(params, conversationId, true); + } + + private static InvokeClientToolConfirmationParams buildParams( + String[] subCommands, String[] commandNames, String commandLine) { + TerminalCommandData tcd = new TerminalCommandData(); + tcd.setSubCommands(subCommands); + tcd.setCommandNames(commandNames); + + ToolMetadata meta = new ToolMetadata(); + meta.setTerminalCommandData(tcd); + + InvokeClientToolConfirmationParams params = + new InvokeClientToolConfirmationParams(); + params.setConversationId(CONV_ID); + params.setToolMetadata(meta); + params.setInput(Map.of("toolType", "terminal", "command", + commandLine != null ? commandLine : "")); + return params; + } + + private static ConfirmationAction buildSessionAction( + TerminalConfirmationHandler.Action actionType) { + Map meta = Map.of( + ConfirmationAction.META_ACTION, actionType.name()); + return new ConfirmationAction( + "test", true, ConfirmationActionScope.SESSION, meta, false); + } + + private static boolean hasActionType(ConfirmationAction action, + TerminalConfirmationHandler.Action type) { + return action.getMetadata().containsKey(ConfirmationAction.META_ACTION) + && action.getMetadata().get(ConfirmationAction.META_ACTION) + .equals(type.name()); + } + + // --- Unapproved filtering tests --- + + @Test + void buildContent_filtersSessionApprovedNamesFromActions() { + stubRules(List.of()); + stubUnmatched(false); + + // "echo && curl" — approve echo in session first + InvokeClientToolConfirmationParams approveParams = + buildParams(new String[]{"echo hello"}, new String[]{"echo"}, + "echo hello"); + handler.cacheDecision( + buildSessionAction( + TerminalConfirmationHandler.Action.ACCEPT_NAMES_SESSION), + approveParams, CONV_ID); + + // Now evaluate "echo hello && curl example.com" + InvokeClientToolConfirmationParams params = + buildParams( + new String[]{"echo hello", "curl example.com"}, + new String[]{"echo", "curl"}, + "echo hello && curl example.com"); + ConfirmationResult result = evaluate(params, CONV_ID); + + assertFalse(result.isAutoApproved()); + List actions = result.getContent().getActions(); + + // Command-name actions should only mention "curl", not "echo" + ConfirmationAction namesAction = actions.stream() + .filter(a -> hasActionType(a, + TerminalConfirmationHandler.Action.ACCEPT_NAMES_SESSION)) + .findFirst().orElse(null); + assertNotNull(namesAction); + assertTrue(namesAction.getLabel().contains("curl")); + assertFalse(namesAction.getLabel().contains("echo")); + } + + @Test + void buildContent_filtersGlobalApprovedNamesFromActions() { + // Global allow rule for "echo" + stubRules(List.of(new TerminalAutoApproveRule("echo", true))); + stubUnmatched(false); + + // Evaluate "echo hello && hostname" + InvokeClientToolConfirmationParams params = + buildParams( + new String[]{"echo hello", "hostname"}, + new String[]{"echo", "hostname"}, + "echo hello && hostname"); + ConfirmationResult result = evaluate(params, CONV_ID); + + assertFalse(result.isAutoApproved()); + List actions = result.getContent().getActions(); + + // "echo" is globally allowed — only "hostname" in actions + ConfirmationAction namesAction = actions.stream() + .filter(a -> hasActionType(a, + TerminalConfirmationHandler.Action.ACCEPT_NAMES_SESSION)) + .findFirst().orElse(null); + assertNotNull(namesAction); + assertTrue(namesAction.getLabel().contains("hostname")); + assertFalse(namesAction.getLabel().contains("echo")); + } + + @Test + void buildContent_allNamesApproved_autoApproves() { + stubRules(List.of(new TerminalAutoApproveRule("echo", true))); + stubUnmatched(false); + + // Session-approve "curl" + InvokeClientToolConfirmationParams approveParams = + buildParams(new String[]{"curl x"}, new String[]{"curl"}, + "curl x"); + handler.cacheDecision( + buildSessionAction( + TerminalConfirmationHandler.Action.ACCEPT_NAMES_SESSION), + approveParams, CONV_ID); + + // Evaluate "echo hello && curl example.com" + // echo = global allow, curl = session allow → all approved + InvokeClientToolConfirmationParams params = + buildParams( + new String[]{"echo hello", "curl example.com"}, + new String[]{"echo", "curl"}, + "echo hello && curl example.com"); + ConfirmationResult result = evaluate(params, CONV_ID); + + assertTrue(result.isAutoApproved()); + } + + @Test + void sessionRules_surviveConversationSwitch() { + // Approve "echo" in conversation A + InvokeClientToolConfirmationParams approveParams = + buildParams(new String[]{"echo hello"}, new String[]{"echo"}, + "echo hello"); + handler.cacheDecision( + buildSessionAction( + TerminalConfirmationHandler.Action.ACCEPT_NAMES_SESSION), + approveParams, "conv-A"); + + // Switch to conversation B, then back to A — rule should survive + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"echo world"}, new String[]{"echo"}, + "echo world"); + ConfirmationResult result = evaluate(params, "conv-A"); + assertTrue(result.isAutoApproved()); + } + + @Test + void sessionRules_evictOldestWhenCapExceeded() { + // Fill up to MAX_SESSION_CONVERSATIONS with unique conversation IDs + for (int i = 0; i < TerminalConfirmationHandler.MAX_SESSION_CONVERSATIONS; + i++) { + InvokeClientToolConfirmationParams p = + buildParams(new String[]{"echo"}, new String[]{"echo"}, "echo"); + handler.cacheDecision( + buildSessionAction( + TerminalConfirmationHandler.Action.ACCEPT_NAMES_SESSION), + p, "conv-" + i); + } + + // Add one more — should evict the oldest (conv-0) + InvokeClientToolConfirmationParams p = + buildParams(new String[]{"echo"}, new String[]{"echo"}, "echo"); + handler.cacheDecision( + buildSessionAction( + TerminalConfirmationHandler.Action.ACCEPT_NAMES_SESSION), + p, "conv-new"); + + // conv-0 should have been evicted + InvokeClientToolConfirmationParams params = + buildParams(new String[]{"echo test"}, new String[]{"echo"}, + "echo test"); + ConfirmationResult evicted = evaluate(params, "conv-0"); + assertFalse(evicted.isAutoApproved()); + + // conv-new should still work + ConfirmationResult kept = evaluate(params, "conv-new"); + assertTrue(kept.isAutoApproved()); + + // conv-1 (second oldest, not evicted) should still work + ConfirmationResult second = evaluate(params, "conv-1"); + assertTrue(second.isAutoApproved()); + } +} diff --git a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/services/McpExtensionPointManagerTest.java b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/services/McpExtensionPointManagerTest.java index 3f60a488..69c3e784 100644 --- a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/services/McpExtensionPointManagerTest.java +++ b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/services/McpExtensionPointManagerTest.java @@ -4,10 +4,13 @@ package com.microsoft.copilot.eclipse.ui.chat.services; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -207,4 +210,151 @@ void testUpdateApprovedMcpServerStringWithNullServers() throws Exception { Map resultServers = (Map) result.get("servers"); assertTrue(resultServers.isEmpty(), "Servers map should be empty when MCP servers are null"); } + + @Test + void testDetectChangesDropsApprovedServerWhenPluginUninstalled() throws Exception { + // Regression test for https://github.com/microsoft/copilot-for-eclipse/issues/153 scenario 1: + // a previously approved plugin is no longer providing any MCP server. + IPreferenceStore mockPreferenceStore = mock(IPreferenceStore.class); + when(mockCopilotUi.getPreferenceStore()).thenReturn(mockPreferenceStore); + + Map previouslyApprovedServers = new HashMap<>(); + previouslyApprovedServers.put("server-X", Map.of("url", "http://localhost:9000")); + McpRegistrationInfo persistedInfo = createMcpRegistrationInfo(true, true, "Test Plugin", + previouslyApprovedServers); + Map persisted = new HashMap<>(); + persisted.put("com.example.plugin", persistedInfo); + + // Live extension scan returned nothing (plugin uninstalled or no longer provides servers). + setExtMcpInfoMap(new HashMap<>()); + + invokeDetectChanges(persisted); + + String approvedServers = manager.getApprovedExtMcpServers(); + assertNotNull(approvedServers, "Approved servers JSON should be non-null after detect"); + Map result = gson.fromJson(approvedServers, Map.class); + Map resultServers = (Map) result.get("servers"); + assertTrue(resultServers.isEmpty(), + "Stale approved server must be dropped when the live extension scan returns nothing"); + + // No new approval prompt should be raised because there is no incoming registration to approve. + verify(mockMcpConfigService, never()).setNewExtMcpRegFound(true); + + // The verified state must be persisted so subsequent startups do not resurrect the stale entry. + ArgumentCaptor persistedJson = ArgumentCaptor.forClass(String.class); + verify(mockPreferenceStore, atLeastOnce()).setValue(eq(Constants.MCP_EXTENSION_POINT_CONTRIB), + persistedJson.capture()); + assertEquals("{}", persistedJson.getValue(), + "Persisted contribution map should be empty after the plugin is gone"); + } + + @Test + void testDetectChangesDropsApprovalAndFlagsRedNoticeWhenConfigChanges() throws Exception { + // Regression test for https://github.com/microsoft/copilot-for-eclipse/issues/153 scenario 2: + // the contributing plugin returns a different config than what was previously approved. + IPreferenceStore mockPreferenceStore = mock(IPreferenceStore.class); + when(mockCopilotUi.getPreferenceStore()).thenReturn(mockPreferenceStore); + + Map oldServers = new HashMap<>(); + oldServers.put("server-X", Map.of("url", "http://localhost:9000")); + McpRegistrationInfo persistedInfo = createMcpRegistrationInfo(true, true, "Test Plugin", oldServers); + Map persisted = new HashMap<>(); + persisted.put("com.example.plugin", persistedInfo); + + // Live extension scan returned the same plugin but with a different server config (port change). + Map newServers = new HashMap<>(); + newServers.put("server-X", Map.of("url", "http://localhost:9999")); + McpRegistrationInfo currentInfo = createMcpRegistrationInfo(true, false, "Test Plugin", newServers); + Map currentMap = new HashMap<>(); + currentMap.put("com.example.plugin", currentInfo); + setExtMcpInfoMap(currentMap); + + invokeDetectChanges(persisted); + + String approvedServers = manager.getApprovedExtMcpServers(); + assertNotNull(approvedServers); + Map result = gson.fromJson(approvedServers, Map.class); + Map resultServers = (Map) result.get("servers"); + assertTrue(resultServers.isEmpty(), + "Changed config must not be auto-applied; LSP must not receive the (now unapproved) entry"); + + assertFalse(currentInfo.isApproved(), + "Previously approved entry whose config changed must be marked as unapproved until the user re-approves"); + verify(mockMcpConfigService).setNewExtMcpRegFound(true); + verify(mockPreferenceStore, atLeastOnce()).setValue(eq(Constants.MCP_EXTENSION_POINT_CONTRIB), + org.mockito.ArgumentMatchers.anyString()); + } + + @Test + void testDetectChangesPreservesApprovalWhenConfigUnchanged() throws Exception { + // Companion test: when the live extension scan reports the same config as the persisted cache, + // the previous approval must be carried over so the explicit LSP sync at the end of + // doRegistration() can push the verified servers to the language server. + IPreferenceStore mockPreferenceStore = mock(IPreferenceStore.class); + when(mockCopilotUi.getPreferenceStore()).thenReturn(mockPreferenceStore); + + Map approvedServers = new HashMap<>(); + approvedServers.put("server-X", Map.of("url", "http://localhost:9000")); + McpRegistrationInfo persistedInfo = createMcpRegistrationInfo(true, true, "Test Plugin", approvedServers); + Map persisted = new HashMap<>(); + persisted.put("com.example.plugin", persistedInfo); + + // Live extension scan returned the same servers; default isApproved=false until carry-over runs. + Map sameServers = new HashMap<>(); + sameServers.put("server-X", Map.of("url", "http://localhost:9000")); + McpRegistrationInfo currentInfo = createMcpRegistrationInfo(true, false, "Test Plugin", sameServers); + Map currentMap = new HashMap<>(); + currentMap.put("com.example.plugin", currentInfo); + setExtMcpInfoMap(currentMap); + + invokeDetectChanges(persisted); + + assertTrue(currentInfo.isApproved(), + "When the contributed config matches the persisted JSON, the previous approval must be carried over"); + + String approvedJson = manager.getApprovedExtMcpServers(); + assertNotNull(approvedJson); + Map result = gson.fromJson(approvedJson, Map.class); + Map resultServers = (Map) result.get("servers"); + assertEquals(1, resultServers.size(), + "Carried-over approved server must be present in the approved servers JSON for the LSP sync"); + + // No red-notice should be raised because nothing has changed for the user to re-review. + verify(mockMcpConfigService, never()).setNewExtMcpRegFound(true); + } + + /** + * Reflectively replace the manager's private {@code extMcpInfoMap} so tests can simulate the + * outcome of {@code loadMcpRegistrationExtensionPoint()} without requiring a live OSGi + * extension registry. + */ + private void setExtMcpInfoMap(Map map) throws Exception { + Field field = McpExtensionPointManager.class.getDeclaredField("extMcpInfoMap"); + field.setAccessible(true); + field.set(manager, map); + } + + private void invokeDetectChanges(Map persisted) throws Exception { + // Get the scanned map that was previously set via setExtMcpInfoMap + Field field = McpExtensionPointManager.class.getDeclaredField("extMcpInfoMap"); + field.setAccessible(true); + @SuppressWarnings("unchecked") + Map scannedMap = (Map) field.get(manager); + + // detectChangesInMcpContribs now takes (scannedMap, persistedMap) and no longer + // calls updateApprovedMcpServerString / persistExtMcpInfo (those moved to doRegistration). + Method detectMethod = McpExtensionPointManager.class.getDeclaredMethod("detectChangesInMcpContribs", Map.class, + Map.class); + detectMethod.setAccessible(true); + detectMethod.invoke(manager, scannedMap, persisted); + + // Mirror what doRegistration() does after detectChanges: swap the field and update/persist. + field.set(manager, scannedMap); + Method updateMethod = McpExtensionPointManager.class.getDeclaredMethod("updateApprovedMcpServerString", Map.class); + updateMethod.setAccessible(true); + updateMethod.invoke(manager, scannedMap); + Method persistMethod = McpExtensionPointManager.class.getDeclaredMethod("persistExtMcpInfo", Map.class); + persistMethod.setAccessible(true); + persistMethod.invoke(manager, scannedMap); + } } diff --git a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/tools/CreateFileToolTest.java b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/tools/CreateFileToolTest.java index 4bd2c9ed..428d7297 100644 --- a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/tools/CreateFileToolTest.java +++ b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/tools/CreateFileToolTest.java @@ -5,10 +5,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; @@ -19,12 +24,14 @@ import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.lsp4j.FileChangeType; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.junit.jupiter.MockitoExtension; @@ -52,6 +59,9 @@ class CreateFileToolTest { @Mock private FileToolService mockFileToolService; + @TempDir + private Path tempDir; + private MockedStatic mockedCopilotUi; @BeforeEach @@ -78,6 +88,7 @@ void tearDown() throws Exception { // Clean up test project cleanupTestProject(); + FileToolCacheAccessor.clearCaches(); } private IProject setupTestProject() throws Exception { @@ -251,11 +262,92 @@ void testInvokeWithNullContentReturnsSuccessStatus() throws Exception { assertTrue(newFile.exists()); } + @Test + void testInvokeWithExternalLocalFilePathCreatesFile() throws Exception { + setupMocks(); + Path newFile = tempDir.resolve("external-file.txt"); + + Map input = new HashMap<>(); + input.put("filePath", newFile.toString()); + input.put("content", "test content"); + + CompletableFuture future = createFileTool.invoke(input, null); + LanguageModelToolResult[] results = future.get(); + + assertSuccessResult(results, "File created at"); + assertTrue(Files.exists(newFile)); + assertEquals("test content", Files.readString(newFile)); + verify(mockFileToolService).addChangedFile(ChangedFile.local(newFile), FileChangeType.Created); + } + + @Test + void testInvokeWithExternalLocalFileUriCreatesFile() throws Exception { + setupMocks(); + Path newFile = tempDir.resolve("external-file-uri.txt"); + + Map input = new HashMap<>(); + input.put("filePath", newFile.toUri().toString()); + input.put("content", "test content"); + + CompletableFuture future = createFileTool.invoke(input, null); + LanguageModelToolResult[] results = future.get(); + + assertSuccessResult(results, "File created at"); + assertTrue(Files.exists(newFile)); + assertEquals("test content", Files.readString(newFile)); + verify(mockFileToolService).addChangedFile(ChangedFile.local(newFile), FileChangeType.Created); + } + + @Test + void testOnKeepChangeWithWorkspaceFileClearsOriginalContentCache() { + IFile newFile = mock(IFile.class); + FileToolCacheAccessor.putWorkspaceFileContentCache(newFile, ""); + + createFileTool.onKeepChange(ChangedFile.workspace(newFile)); + + assertNull(FileToolCacheAccessor.getWorkspaceFileContentCache(newFile)); + } + + @Test + void testOnUndoChangeWithWorkspaceFileDeletesFileAndClearsOriginalContentCache() throws Exception { + IProject project = setupTestProject(); + IFile newFile = project.getFile("workspace-file-to-undo.txt"); + newFile.create(new java.io.ByteArrayInputStream("test content".getBytes()), true, null); + FileToolCacheAccessor.putWorkspaceFileContentCache(newFile, ""); + + createFileTool.onUndoChange(ChangedFile.workspace(newFile)); + + assertTrue(!newFile.exists()); + assertNull(FileToolCacheAccessor.getWorkspaceFileContentCache(newFile)); + } + + @Test + void testOnKeepChangeWithExternalLocalFileClearsOriginalContentCache() { + Path newFile = tempDir.resolve("external-file-to-keep.txt"); + FileToolCacheAccessor.putFileContentCache(newFile, ""); + + createFileTool.onKeepChange(ChangedFile.local(newFile)); + + assertNull(FileToolCacheAccessor.getFileContentCache(newFile)); + } + + @Test + void testOnUndoChangeWithExternalLocalFileDeletesFile() throws Exception { + Path newFile = tempDir.resolve("external-file-to-undo.txt"); + Files.writeString(newFile, "test content"); + FileToolCacheAccessor.putFileContentCache(newFile, ""); + + createFileTool.onUndoChange(ChangedFile.local(newFile)); + + assertTrue(Files.notExists(newFile)); + assertNull(FileToolCacheAccessor.getFileContentCache(newFile)); + } + @Test void testInvokeWithInvalidPathReturnsErrorStatus() throws InterruptedException, ExecutionException { // Arrange Map input = new HashMap<>(); - input.put("filePath", "/invalid/path/that/does/not/exist.txt"); + input.put("filePath", "relative/path/that/does/not/exist.txt"); input.put("content", "test content"); // Act @@ -263,7 +355,7 @@ void testInvokeWithInvalidPathReturnsErrorStatus() throws InterruptedException, LanguageModelToolResult[] results = future.get(); // Assert - assertErrorResult(results, "Error creating file"); + assertErrorResult(results, "does not exist in the workspace"); } @Test @@ -286,4 +378,26 @@ void testToolName() { * Note: CoreException and IOException scenarios are difficult to test in unit tests * without complex mocking and would be better covered by integration tests. */ + + private static final class FileToolCacheAccessor extends CreateFileTool { + private static void clearCaches() { + fileContentCache.clear(); + } + + private static void putWorkspaceFileContentCache(IFile file, String content) { + fileContentCache.put(ChangedFile.workspace(file), content); + } + + private static String getWorkspaceFileContentCache(IFile file) { + return fileContentCache.get(ChangedFile.workspace(file)); + } + + private static void putFileContentCache(Path file, String content) { + fileContentCache.put(ChangedFile.local(file), content); + } + + private static String getFileContentCache(Path file) { + return fileContentCache.get(ChangedFile.local(file)); + } + } } diff --git a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/tools/EditFileToolTest.java b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/tools/EditFileToolTest.java new file mode 100644 index 00000000..4ffabcbd --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/tools/EditFileToolTest.java @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.chat.tools; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.lsp4j.FileChangeType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.microsoft.copilot.eclipse.core.lsp.protocol.LanguageModelToolResult; +import com.microsoft.copilot.eclipse.core.lsp.protocol.LanguageModelToolResult.ToolInvocationStatus; +import com.microsoft.copilot.eclipse.ui.CopilotUi; +import com.microsoft.copilot.eclipse.ui.chat.services.ChatServiceManager; + +@ExtendWith(MockitoExtension.class) +class EditFileToolTest { + + @TempDir + Path tempDir; + + @Mock + private CopilotUi mockCopilotUi; + @Mock + private ChatServiceManager mockChatServiceManager; + @Mock + private FileToolService mockFileToolService; + + private MockedStatic mockedCopilotUi; + + private void setupMocks() { + mockedCopilotUi = mockStatic(CopilotUi.class); + mockedCopilotUi.when(CopilotUi::getPlugin).thenReturn(mockCopilotUi); + when(mockCopilotUi.getChatServiceManager()).thenReturn(mockChatServiceManager); + when(mockChatServiceManager.getFileToolService()).thenReturn(mockFileToolService); + } + + @AfterEach + void tearDown() { + if (mockedCopilotUi != null) { + mockedCopilotUi.close(); + } + FileToolCacheAccessor.clearCaches(); + } + + @Test + void testInvoke_withExternalLocalFilePath_editsFile() throws Exception { + setupMocks(); + Path file = tempDir.resolve("target.txt"); + Files.writeString(file, "original"); + + LanguageModelToolResult[] results = invokeEdit(file.toString(), "updated"); + + assertSuccess(results, "updated"); + assertEquals("updated", Files.readString(file)); + verify(mockFileToolService).addChangedFile(ChangedFile.local(file), FileChangeType.Changed); + } + + @Test + void testInvoke_withExternalLocalFileUri_editsFile() throws Exception { + setupMocks(); + Path file = tempDir.resolve("target.patch"); + Files.writeString(file, "old patch content"); + + LanguageModelToolResult[] results = invokeEdit(file.toUri().toString(), "new patch content"); + + assertSuccess(results, "new patch content"); + assertEquals("new patch content", Files.readString(file)); + verify(mockFileToolService).addChangedFile(ChangedFile.local(file), FileChangeType.Changed); + } + + @Test + void testOnUndoChange_withExternalLocalFile_restoresOriginalContent() throws Exception { + setupMocks(); + Path file = tempDir.resolve("target-to-undo.txt"); + Files.writeString(file, "original"); + + EditFileTool editFileTool = new EditFileTool(); + LanguageModelToolResult[] results = invokeEdit(editFileTool, file.toString(), "updated"); + assertSuccess(results, "updated"); + + editFileTool.onUndoChange(ChangedFile.local(file)); + + assertEquals("original", Files.readString(file)); + } + + @Test + void testInvoke_createThenEditExternalLocalFile_preservesEmptyBaseline() throws Exception { + setupMocks(); + Path file = tempDir.resolve("created-then-edited.txt"); + Path normalizedPath = file.toAbsolutePath().normalize(); + + CreateFileTool createFileTool = new CreateFileTool(); + LanguageModelToolResult[] createResults = invokeCreate(createFileTool, file.toString(), "created content"); + assertSuccess(createResults, "File created at: " + normalizedPath); + assertEquals("", FileToolCacheAccessor.getFileContentCache(normalizedPath)); + + EditFileTool editFileTool = new EditFileTool(); + LanguageModelToolResult[] editResults = invokeEdit(editFileTool, file.toString(), "edited content"); + + assertSuccess(editResults, "edited content"); + assertEquals("edited content", Files.readString(file)); + assertEquals("", FileToolCacheAccessor.getFileContentCache(normalizedPath)); + } + + @Test + void testInvoke_withMissingExternalLocalFile_returnsError() throws Exception { + LanguageModelToolResult[] results = invokeEdit(tempDir.resolve("missing.txt").toString(), "updated"); + + assertNotNull(results); + assertEquals(1, results.length); + assertEquals(ToolInvocationStatus.error, results[0].getStatus()); + } + + private LanguageModelToolResult[] invokeEdit(String filePath, String code) throws Exception { + return invokeEdit(new EditFileTool(), filePath, code); + } + + private LanguageModelToolResult[] invokeEdit(EditFileTool editFileTool, String filePath, String code) + throws Exception { + Map input = new HashMap<>(); + input.put("filePath", filePath); + input.put("code", code); + input.put("explanation", "test edit"); + + return editFileTool.invoke(input, null).get(); + } + + private LanguageModelToolResult[] invokeCreate(CreateFileTool createFileTool, String filePath, String content) + throws Exception { + Map input = new HashMap<>(); + input.put("filePath", filePath); + input.put("content", content); + + return createFileTool.invoke(input, null).get(); + } + + private void assertSuccess(LanguageModelToolResult[] results, String expectedContent) throws IOException { + assertNotNull(results); + assertEquals(1, results.length); + assertEquals(ToolInvocationStatus.success, results[0].getStatus()); + assertEquals(expectedContent, results[0].getContent().get(0).getValue()); + } + + private static final class FileToolCacheAccessor extends EditFileTool { + private static void clearCaches() { + fileContentCache.clear(); + } + + private static String getFileContentCache(Path file) { + return fileContentCache.get(ChangedFile.local(file)); + } + } +} \ No newline at end of file diff --git a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/tools/RunInTerminalToolAdapterTest.java b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/tools/RunInTerminalToolAdapterTest.java index 01ebcc41..5f6aa92c 100644 --- a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/tools/RunInTerminalToolAdapterTest.java +++ b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/chat/tools/RunInTerminalToolAdapterTest.java @@ -77,7 +77,8 @@ void testInvokeWithEmptyCommandReturnsErrorStatus() throws InterruptedException, assertNotNull(results); assertEquals(1, results.length); assertEquals(ToolInvocationStatus.error, results[0].getStatus()); - assertTrue(results[0].getContent().get(0).getValue().equals("No terminal implementation available. Terminal service not yet loaded or failed to load.")); + assertEquals("No terminal implementation available. Terminal service not yet loaded or failed to load.", + results[0].getContent().get(0).getValue()); } @Test @@ -113,7 +114,6 @@ void testToolName() { assertEquals("run_in_terminal", runInTerminalToolAdapter.getToolName()); } - @Test void testGetTerminalOutputToolWithNoTerminalServiceReturnsErrorStatus() throws InterruptedException, ExecutionException { diff --git a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/preferences/LanguageServerSettingManagerTests.java b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/preferences/LanguageServerSettingManagerTests.java index 5843ccfe..8cf28098 100644 --- a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/preferences/LanguageServerSettingManagerTests.java +++ b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/preferences/LanguageServerSettingManagerTests.java @@ -14,6 +14,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.LinkedHashMap; + import org.eclipse.core.net.proxy.IProxyData; import org.eclipse.core.net.proxy.IProxyService; import org.eclipse.jface.preference.IPreferenceStore; @@ -23,6 +25,8 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import com.microsoft.copilot.eclipse.core.Constants; import com.microsoft.copilot.eclipse.core.lsp.CopilotLanguageServerConnection; @@ -33,6 +37,7 @@ import com.microsoft.copilot.eclipse.ui.utils.PreferencesUtils; @ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) class LanguageServerSettingManagerTests { @Mock private IPreferenceStore mockPreferenceStore; @@ -53,6 +58,11 @@ void testNoProxy() { settings.getGithubSettings().getCopilotSettings().getAgent() .setEnableSkills(PreferencesUtils.isSkillsEnabled()) .setTranscriptDirectory(PlatformUtils.getTranscriptDirectory()); + settings.getGithubSettings().getCopilotSettings().getAgent().setAutoCompress(true); + settings.getGithubSettings().getCopilotSettings().getAgent() + .getTools().getTerminal().setAutoApprove(new LinkedHashMap<>()); + settings.getGithubSettings().getCopilotSettings().getAgent() + .getTools().getEdit().setAutoApprove(new LinkedHashMap<>()); params.setSettings(settings); // act @@ -83,6 +93,11 @@ void testBasicProxy() { settings.getGithubSettings().getCopilotSettings().getAgent() .setEnableSkills(PreferencesUtils.isSkillsEnabled()) .setTranscriptDirectory(PlatformUtils.getTranscriptDirectory()); + settings.getGithubSettings().getCopilotSettings().getAgent().setAutoCompress(true); + settings.getGithubSettings().getCopilotSettings().getAgent() + .getTools().getTerminal().setAutoApprove(new LinkedHashMap<>()); + settings.getGithubSettings().getCopilotSettings().getAgent() + .getTools().getEdit().setAutoApprove(new LinkedHashMap<>()); params.setSettings(settings); // act @@ -117,10 +132,15 @@ void testUpdateConfigShouldBeCalledWhenWorkspaceInstructionsEnabledWithContent() CopilotSettings copilotSettings = new CopilotSettings(); copilotSettings.setWorkspaceCopilotInstructions("Test instructions"); copilotSettings.getAgent().setEnableSkills(PreferencesUtils.isSkillsEnabled()); + copilotSettings.getAgent().setAutoCompress(true); CopilotLanguageServerSettings settings = new CopilotLanguageServerSettings(); settings.getGithubSettings().setCopilotSettings(copilotSettings); settings.getGithubSettings().getCopilotSettings().getAgent() .setTranscriptDirectory(PlatformUtils.getTranscriptDirectory()); + settings.getGithubSettings().getCopilotSettings().getAgent() + .getTools().getTerminal().setAutoApprove(new LinkedHashMap<>()); + settings.getGithubSettings().getCopilotSettings().getAgent() + .getTools().getEdit().setAutoApprove(new LinkedHashMap<>()); params.setSettings(settings); // act @@ -152,6 +172,11 @@ void testUpdateConfigShouldBeCalledWithoutInstructionWhenWorkspaceInstructionsDi expectedSettings.getGithubSettings().getCopilotSettings().getAgent() .setEnableSkills(PreferencesUtils.isSkillsEnabled()) .setTranscriptDirectory(PlatformUtils.getTranscriptDirectory()); + expectedSettings.getGithubSettings().getCopilotSettings().getAgent().setAutoCompress(true); + expectedSettings.getGithubSettings().getCopilotSettings().getAgent() + .getTools().getTerminal().setAutoApprove(new LinkedHashMap<>()); + expectedSettings.getGithubSettings().getCopilotSettings().getAgent() + .getTools().getEdit().setAutoApprove(new LinkedHashMap<>()); expectedParams.setSettings(expectedSettings); // act diff --git a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/utils/ModelUtilsTests.java b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/utils/ModelUtilsTests.java index e8448ea6..e2185223 100644 --- a/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/utils/ModelUtilsTests.java +++ b/com.microsoft.copilot.eclipse.ui.test/src/com/microsoft/copilot/eclipse/ui/utils/ModelUtilsTests.java @@ -17,6 +17,7 @@ import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel.CopilotModelCapabilities; import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel.CopilotModelCapabilitiesLimits; import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel.CopilotModelCapabilitiesSupports; +import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel.CopilotModelCustomModel; import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotScope; import com.microsoft.copilot.eclipse.core.lsp.protocol.byok.ByokModel; import com.microsoft.copilot.eclipse.core.lsp.protocol.byok.ByokModelCapabilities; @@ -150,6 +151,27 @@ void testSupportsReasoningEffortLevel_falseWhenCapabilitiesMissing() { assertFalse(ModelUtils.supportsReasoningEffortLevel(null)); } + @Test + void testGetModelSuffix_customModelUsesProvider() { + // Organization-contributed custom models arrive without a providerName but carry their provider in the + // custom-model metadata; the suffix should surface that provider like a BYOK model. + CopilotModel model = new CopilotModel(); + model.setModelName("Sonnet (Org)"); + model.setCustomModel(new CopilotModelCustomModel("Contoso Azure Key", "Contoso", "organization", "Azure")); + + assertEquals("Azure", ModelUtils.getModelSuffix(model, null)); + } + + @Test + void testGetModelSuffix_providerNameTakesPrecedenceOverCustomModel() { + CopilotModel model = new CopilotModel(); + model.setModelName("GPT-4o"); + model.setProviderName("OpenAI"); + model.setCustomModel(new CopilotModelCustomModel("Key", "Contoso", "organization", "Azure")); + + assertEquals("OpenAI", ModelUtils.getModelSuffix(model, null)); + } + @Test void testIsAutoModel() { CopilotModel auto = new CopilotModel(); diff --git a/com.microsoft.copilot.eclipse.ui/META-INF/MANIFEST.MF b/com.microsoft.copilot.eclipse.ui/META-INF/MANIFEST.MF index 2a91ad85..dc86d49a 100644 --- a/com.microsoft.copilot.eclipse.ui/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.ui/META-INF/MANIFEST.MF @@ -2,11 +2,12 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: com.microsoft.copilot.eclipse.ui Bundle-SymbolicName: com.microsoft.copilot.eclipse.ui;singleton:=true -Bundle-Version: 0.18.0.qualifier +Bundle-Version: 0.20.0.qualifier Bundle-Vendor: GitHub Copilot Bundle-Localization: plugin Export-Package: com.microsoft.copilot.eclipse.ui, com.microsoft.copilot.eclipse.ui.chat, + com.microsoft.copilot.eclipse.ui.chat.confirmation;x-friends:="com.microsoft.copilot.eclipse.ui.test", com.microsoft.copilot.eclipse.ui.chat.services, com.microsoft.copilot.eclipse.ui.chat.tools, com.microsoft.copilot.eclipse.ui.completion, @@ -24,8 +25,8 @@ Bundle-RequiredExecutionEnvironment: JavaSE-17 Automatic-Module-Name: com.microsoft.copilot.eclipse.ui Bundle-ActivationPolicy: lazy Import-Package: org.osgi.framework;version="[1.10.0,2.0.0)" -Require-Bundle: com.microsoft.copilot.eclipse.core;bundle-version="0.15.0", - com.microsoft.copilot.eclipse.terminal.api;bundle-version="0.15.0", +Require-Bundle: com.microsoft.copilot.eclipse.core;bundle-version="0.20.0", + com.microsoft.copilot.eclipse.terminal.api;bundle-version="0.20.0", org.eclipse.ui.ide;bundle-version="3.22.0", org.eclipse.ui.workbench.texteditor;bundle-version="3.17.200", org.eclipse.ui.editors;bundle-version="3.17.100", diff --git a/com.microsoft.copilot.eclipse.ui/css/dark.css b/com.microsoft.copilot.eclipse.ui/css/dark.css index 6cff9e7e..528204cb 100644 --- a/com.microsoft.copilot.eclipse.ui/css/dark.css +++ b/com.microsoft.copilot.eclipse.ui/css/dark.css @@ -91,7 +91,7 @@ background-color: #3584F1; } -#chat-content-viewer > Composite > CopilotTurnWidget > InvokeToolConfirmationDialog > .bg-command-panel { +#chat-content-viewer > Composite > CopilotTurnWidget > InvokeToolConfirmationDialog > ScrolledComposite > .bg-command-panel { background-color: #48484C; } diff --git a/com.microsoft.copilot.eclipse.ui/css/light.css b/com.microsoft.copilot.eclipse.ui/css/light.css index 9fc554ba..25c39464 100644 --- a/com.microsoft.copilot.eclipse.ui/css/light.css +++ b/com.microsoft.copilot.eclipse.ui/css/light.css @@ -91,7 +91,7 @@ background-color: #3584F1; } -#chat-content-viewer > Composite > CopilotTurnWidget > InvokeToolConfirmationDialog > .bg-command-panel { +#chat-content-viewer > Composite > CopilotTurnWidget > InvokeToolConfirmationDialog > ScrolledComposite > .bg-command-panel { background-color: #FFFFFF; } diff --git a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.16.0/new_chat_input.png b/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.16.0/new_chat_input.png deleted file mode 100644 index 642b240c..00000000 Binary files a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.16.0/new_chat_input.png and /dev/null differ diff --git a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.16.0/new_selector.png b/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.16.0/new_selector.png deleted file mode 100644 index f7ae997c..00000000 Binary files a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.16.0/new_selector.png and /dev/null differ diff --git a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.16.0/syntax_highlighting.png b/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.16.0/syntax_highlighting.png deleted file mode 100644 index 71fc1c78..00000000 Binary files a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.16.0/syntax_highlighting.png and /dev/null differ diff --git a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.16.0/tool_calling_in_ask_mode.png b/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.16.0/tool_calling_in_ask_mode.png deleted file mode 100644 index e6943a02..00000000 Binary files a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.16.0/tool_calling_in_ask_mode.png and /dev/null differ diff --git a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.17.0/context_window_usage.png b/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.17.0/context_window_usage.png deleted file mode 100644 index 7d62deef..00000000 Binary files a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.17.0/context_window_usage.png and /dev/null differ diff --git a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.17.0/new_combo_picker.png b/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.17.0/new_combo_picker.png deleted file mode 100644 index e6905a9a..00000000 Binary files a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.17.0/new_combo_picker.png and /dev/null differ diff --git a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.19.0/auto-approve.png b/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.19.0/auto-approve.png new file mode 100644 index 00000000..f9f98e22 Binary files /dev/null and b/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.19.0/auto-approve.png differ diff --git a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.20.0/custom-model.png b/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.20.0/custom-model.png new file mode 100644 index 00000000..b767bbdb Binary files /dev/null and b/com.microsoft.copilot.eclipse.ui/intro/whatsnew/0.20.0/custom-model.png differ diff --git a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/WHATISNEW.md b/com.microsoft.copilot.eclipse.ui/intro/whatsnew/WHATISNEW.md index 653837f7..0e02ffc3 100644 --- a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/WHATISNEW.md +++ b/com.microsoft.copilot.eclipse.ui/intro/whatsnew/WHATISNEW.md @@ -1,99 +1,89 @@ -# GitHub Copilot 0.18.0 Release Notes +# GitHub Copilot 0.20.0 Release Notes -### Prepare for the Upcoming Usage-Based Billing -Starting from this version, we have added internal support for the [upcoming usage-based billing experience](https://github.blog/news-insights/company-news/github-copilot-is-moving-to-usage-based-billing/), including experience updates to the usage panel, usage notifications, and model picker. These changes will become visible once usage-based billing is rolled out. +### Organization-Level Custom Models +Copilot for Eclipse now supports organization-enabled custom models in the model picker. If your organization has configured custom models, they appear automatically so you can select them alongside Copilot's built-in models. -Clients using older plugin versions will continue to function. However, the billing and usage experience may not be optimal and may not accurately reflect the latest usage-based billing experience. +![Custom Model](0.20.0/custom-model.png) --- -### Custom Instructions Loading Preference -A new Copilot preference lets you control how a chat's custom instructions are loaded. Tailor when and how your project-specific or personal instructions are picked up by Copilot, giving you finer control over the context that shapes each conversation. By default, custom instructions are loaded from **all projects** in your Eclipse workspace; switch to **Referenced projects** to only load instructions from projects whose files or folders are referenced in the current chat. +### Faster and More Reliable Chat Rendering +The chat view now renders long and streaming conversations more efficiently, reducing slowdowns during agent sessions and editor switches. -![Custom Instructions Loading Preference](0.18.0/custom_instructions_loading.png) +This release also includes chat fixes so long conversations scroll correctly to the newest messages, prompts that need user action are brought into view automatically, and model details display better on Linux. --- -### Skills and Prompt Files -Copilot for Eclipse now supports skills and prompt files. Define reusable prompts and skills to streamline your workflows — invoke them on demand to apply consistent instructions and patterns across your chats. Persist your skill files under `/.github/skills/` (for example, `.github/skills/my-skill/SKILL.md`) and prompt files under `/.github/prompts/` (e.g. `my-prompt.prompt.md`) so they're picked up automatically. - -To trigger a skill or prompt in chat, type `/` in the chat input box to open the slash command picker. - -![Skills and Prompt Files](0.18.0/skills_and_prompt_files.png) +### Copilot Menu on the Left +The Copilot menu has moved to the left side of the Eclipse menu bar, immediately before the Help menu. --- -### Thinking Blocks in Chat View -For models that support reasoning, the chat view now displays thinking blocks so you can follow Copilot's reasoning process alongside its final response. Expand or collapse the blocks to dive into the details or keep the view focused on results. +# GitHub Copilot 0.19.0 Release Notes -![Thinking Blocks in Chat View](0.18.0/thinking_blocks.png) +### Agent Tool Auto-Approve Controls +Agent Mode now supports auto-approve controls for tool confirmations. Configure rules for terminal commands, file operations, and MCP tools from Copilot preferences, or use the confirmation dialog's **Allow for Session** and **Always Allow** actions to keep trusted workflows moving without repeated prompts. ---- +Default file safety rules, MCP tool annotations, and the global auto-approve toggle are supported, so you can reduce friction while keeping risky actions visible. -### Selectable Thinking Effort -You can now choose the thinking effort level for supported models. Dial the reasoning depth up for complex problems or keep it light for quick tasks — giving you control over the trade-off between latency and answer quality. - -![Selectable Thinking Effort](0.18.0/thinking_effort.png) +![Tool Auto Approve](0.19.0/auto-approve.png) --- -# GitHub Copilot 0.17.0 Release Notes +### Automatic Chat Context Compression +Copilot can now automatically compress chat context as conversations grow. When a session approaches the context limit, older conversation context is summarized so longer agent runs can continue with fewer interruptions. -### GitHub Copilot for Eclipse Is Now Open Source -We're thrilled to share that GitHub Copilot for Eclipse is now open source! The full source code is available on GitHub at [microsoft/copilot-for-eclipse](https://github.com/microsoft/copilot-for-eclipse). Browse the code, file issues, and send pull requests — we'd love to build the plugin together with the Eclipse community. Your feedback and contributions help shape what comes next. +The chat view also shows compression status while Copilot is compacting the conversation, making long-running sessions easier to follow. --- -### Refreshed Chat View with a New Combo Picker -The chat view has been refreshed with a brand-new combo picker for selecting chat modes and models, with more information surfaced for each model. +### Create and Edit Local Files Outside the Workspace +Agent Mode can now create and edit local files by absolute path even when they are outside the Eclipse workspace. This helps when your code spans external folders, linked resources, or files that are not loaded as Eclipse projects. -![New Combo Picker](0.17.0/new_combo_picker.png) +Local file changes are tracked alongside workspace edits in the changed-files bar, with support for **View Diff**, **Keep**, and **Undo** flows, including empty-baseline diffs for newly created files. --- -### Session Context Window Usage at a Glance -Ever wonder how much of the conversation's context window has been consumed? The chat view now shows a context size donut indicator alongside the input area, with a popup that breaks down token usage for the current session. Auto compression is coming next. +### More Reliable Terminal Command Execution on Windows and Linux +Terminal command execution is more reliable across Windows and Linux. Copilot now runs commands through PowerShell on Windows and Bash on Linux, uses shell-integration markers to detect command completion and exit codes, and handles multiline commands with bracketed paste formatting. -![Context Window Usage](0.17.0/context_window_usage.png) +Copilot also interrupts previous foreground commands before starting new ones, stops active terminal work when a chat request is canceled, truncates long terminal output before sending it back to the model, and chooses a better working directory from the current file or referenced files. --- -### Custom Models (BYOK) for Copilot Business and Enterprise -Bring Your Own Key (BYOK) is now available to GitHub Copilot Business and Enterprise users — in addition to Individual users — when enabled by their organization. Once your organization turns it on, you can configure your own API keys for supported providers and use the custom models directly in Copilot chat in Eclipse. If you don't see custom models enabled, reach out to your organization's administrator to turn the feature on. +# GitHub Copilot 0.18.0 Release Notes ---- +### Prepare for the Upcoming Usage-Based Billing +Starting from this version, we have added internal support for the [upcoming usage-based billing experience](https://github.blog/news-insights/company-news/github-copilot-is-moving-to-usage-based-billing/), including experience updates to the usage panel, usage notifications, and model picker. These changes will become visible once usage-based billing is rolled out. -### Better ABAP Support -This release brings improved support for ABAP development in Eclipse. Copilot now provides more accurate and context-aware chat responses for ABAP projects, and it can read directories and search within the locally cached files. +Clients using older plugin versions will continue to function. However, the billing and usage experience may not be optimal and may not accurately reflect the latest usage-based billing experience. --- -### - -# GitHub Copilot 0.16.0 Release Notes - -### Tool Calling in Ask Mode - -Ask Mode now supports tool calling. When a question requires additional context, Copilot automatically invokes relevant tools — such as listing directories, searching for files, and reading file contents — to gather the information needed to provide an accurate response. Tools invoked in Ask Mode are read-only and will not modify your codebase. +### Custom Instructions Loading Preference +A new Copilot preference lets you control how a chat's custom instructions are loaded. Tailor when and how your project-specific or personal instructions are picked up by Copilot, giving you finer control over the context that shapes each conversation. By default, custom instructions are loaded from **all projects** in your Eclipse workspace; switch to **Referenced projects** to only load instructions from projects whose files or folders are referenced in the current chat. -![Tool Calling in Ask Mode](0.16.0/tool_calling_in_ask_mode.png) +![Custom Instructions Loading Preference](0.18.0/custom_instructions_loading.png) --- -### Redesigned Selectors and Chat Input Area - -- **Mode and Model Selectors**: The chat mode and model selectors have been redesigned to surface more information at a glance. The updated layout includes icons and descriptions, making it easier to identify the capabilities and warnings associated with each option. +### Skills and Prompt Files +Copilot for Eclipse now supports skills and prompt files. Define reusable prompts and skills to streamline your workflows — invoke them on demand to apply consistent instructions and patterns across your chats. Persist your skill files under `/.github/skills/` (for example, `.github/skills/my-skill/SKILL.md`) and prompt files under `/.github/prompts/` (e.g. `my-prompt.prompt.md`) so they're picked up automatically. -![New Selector](0.16.0/new_selector.png) +To trigger a skill or prompt in chat, type `/` in the chat input box to open the slash command picker. -- **Chat Input Area**: The chat input area has been refined with a cleaner, borderless button design for a more streamlined appearance. -![New Chat Input](0.16.0/new_chat_input.png) +![Skills and Prompt Files](0.18.0/skills_and_prompt_files.png) --- -### Syntax Highlighting in Chat +### Thinking Blocks in Chat View +For models that support reasoning, the chat view now displays thinking blocks so you can follow Copilot's reasoning process alongside its final response. Expand or collapse the blocks to dive into the details or keep the view focused on results. -Code snippets in Copilot's chat view now render with full syntax highlighting. Code blocks in responses are automatically highlighted based on the detected language, improving readability and making it easier to follow along with code suggestions and explanations. +![Thinking Blocks in Chat View](0.18.0/thinking_blocks.png) -![Syntax Highlighting](0.16.0/syntax_highlighting.png) +--- +### Selectable Thinking Effort +You can now choose the thinking effort level for supported models. Dial the reasoning depth up for complex problems or keep it light for quick tasks — giving you control over the trade-off between latency and answer quality. + +![Selectable Thinking Effort](0.18.0/thinking_effort.png) diff --git a/com.microsoft.copilot.eclipse.ui/plugin.properties b/com.microsoft.copilot.eclipse.ui/plugin.properties index 38fd45a7..636fc1fb 100644 --- a/com.microsoft.copilot.eclipse.ui/plugin.properties +++ b/com.microsoft.copilot.eclipse.ui/plugin.properties @@ -47,4 +47,5 @@ intro.quickStart.description=Boost your coding efficiency with built-in Copilot theme.category.label=GitHub Copilot theme.category.description=Font and color settings for GitHub Copilot theme.chatFont.label=Chat Font -theme.chatFont.description=The font used for text in the Copilot Chat view \ No newline at end of file +theme.chatFont.description=The font used for text in the Copilot Chat view +page.preferencesPage.autoApprove.name=Tool Auto Approve \ No newline at end of file diff --git a/com.microsoft.copilot.eclipse.ui/plugin.xml b/com.microsoft.copilot.eclipse.ui/plugin.xml index be871853..8771f7ac 100644 --- a/com.microsoft.copilot.eclipse.ui/plugin.xml +++ b/com.microsoft.copilot.eclipse.ui/plugin.xml @@ -29,7 +29,7 @@ + locationURI="menu:org.eclipse.ui.main.menu?before=help">

+ + diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ActionBar.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ActionBar.java index 0cb765f7..2c98738f 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ActionBar.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ActionBar.java @@ -1097,10 +1097,7 @@ private void showMcpToolContextMenu() { approvalItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - String res = chatServiceManager.getMcpExtensionPointManager().approveExtMcpRegistration(); - if (StringUtils.isNotBlank(res)) { - CopilotUi.getPlugin().getLanguageServerSettingManager().syncMcpRegistrationConfiguration(); - } + chatServiceManager.getMcpExtensionPointManager().approveExtMcpRegistration(); } }); diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/BaseTurnWidget.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/BaseTurnWidget.java index c1cc893b..9f099223 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/BaseTurnWidget.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/BaseTurnWidget.java @@ -23,7 +23,9 @@ import org.eclipse.ui.PlatformUI; import org.osgi.service.event.EventHandler; +import com.microsoft.copilot.eclipse.core.Constants; import com.microsoft.copilot.eclipse.core.CopilotCore; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationContent; import com.microsoft.copilot.eclipse.core.events.CopilotEventConstants; import com.microsoft.copilot.eclipse.core.lsp.protocol.AgentToolCall; import com.microsoft.copilot.eclipse.core.lsp.protocol.LanguageModelToolConfirmationResult; @@ -35,6 +37,7 @@ import com.microsoft.copilot.eclipse.core.persistence.CopilotTurnData.EditAgentRoundData; import com.microsoft.copilot.eclipse.core.persistence.CopilotTurnData.ReplyData; import com.microsoft.copilot.eclipse.core.persistence.CopilotTurnData.ToolCallData; +import com.microsoft.copilot.eclipse.ui.CopilotUi; import com.microsoft.copilot.eclipse.ui.chat.services.AvatarService; import com.microsoft.copilot.eclipse.ui.chat.services.ChatServiceManager; import com.microsoft.copilot.eclipse.ui.utils.SwtUtils; @@ -70,6 +73,11 @@ public abstract class BaseTurnWidget extends Composite { protected Font boldFont = null; protected InvokeToolConfirmationDialog confirmDialog; + /** Returns the current confirmation dialog, or {@code null} if none active. */ + public InvokeToolConfirmationDialog getConfirmDialog() { + return confirmDialog; + } + // Footer protected Composite footer; @@ -325,7 +333,7 @@ private void handleSubagentToolCall(AgentToolCall toolCall) { case "completed": // End of subagent block if (currentSubagentBlock != null) { - currentSubagentBlock.notifyTurnEnd(); + currentSubagentBlock.flushMessageBuffer(); inSubagentBlock = false; currentSubagentBlock = null; requestLayout(); @@ -343,7 +351,7 @@ private void handleSubagentToolCall(AgentToolCall toolCall) { case "error": // Handle errors in subagent if (currentSubagentBlock != null) { - currentSubagentBlock.notifyTurnEnd(); + currentSubagentBlock.flushMessageBuffer(); inSubagentBlock = false; currentSubagentBlock = null; } @@ -437,7 +445,7 @@ public void restoreSubagentContent(String toolCallId, CopilotTurnData copilotTur } } - block.notifyTurnEnd(); + block.flushMessageBuffer(); } /** @@ -515,9 +523,10 @@ private void appendTextToTextViewer(String text) { } /** - * Notify the end of the turn. + * Flushes any buffered, not-yet-newline-terminated message text by processing it as a final + * line and clearing the buffer. */ - public void notifyTurnEnd() { + public void flushMessageBuffer() { if (messageBuffer.length() > 0) { this.processMessageLine(messageBuffer.toString()); messageBuffer.setLength(0); @@ -597,16 +606,16 @@ protected void ensureFooterAtBottom() { * @param code the server error code * @param modelProviderName the BYOK model-provider name, or {@code null} for built-in models */ - protected void createWarnDialog(String message, int code, String modelProviderName) { + protected Composite createWarnDialog(String message, int code, String modelProviderName) { // TODO: Remove this legacy fallback after TBB is officially released. // When the language server has not enabled token-based billing yet, restore the original // main-branch warning behavior (no plan-driven actions; single upgrade button on the legacy // 30-day free trial message). if (!this.serviceManager.getAuthStatusManager().getQuotaStatus().tokenBasedBillingEnabled()) { - new WarnWidget(this, SWT.BOTTOM, message, code); + WarnWidget warnWidget = new WarnWidget(this, SWT.BOTTOM, message, code); ensureFooterAtBottom(); requestLayout(); - return; + return warnWidget; } boolean byokQuotaExceeded = QuotaActions.isByokQuotaExceeded(code, modelProviderName); String displayMessage = byokQuotaExceeded ? Messages.chat_warnWidget_byokQuotaUsageMessage : message; @@ -620,9 +629,11 @@ protected void createWarnDialog(String message, int code, String modelProviderNa && quotaStatus.premiumInteractions().overagePermitted(); canUpgradePlan = quotaStatus.canUpgradePlan(); } - new WarnWidget(this, SWT.NONE, displayMessage, planForActions, overageEnabled, canUpgradePlan); + WarnWidget warnWidget = + new WarnWidget(this, SWT.NONE, displayMessage, planForActions, overageEnabled, canUpgradePlan); ensureFooterAtBottom(); requestLayout(); + return warnWidget; } /** @@ -636,20 +647,41 @@ protected void createAgentMessageWidget(CodingAgentMessageRequestParams params) /** * Prompts the user to confirm or deny a tool execution. * - * @param title The title of the confirmation dialog. - * @param message The message to display in the confirmation dialog. + * @param content The confirmation content with title, message, and action buttons. * @param input The input object to be passed to the tool. */ - public CompletableFuture requestToolExecutionConfirmation(String title, - String message, Object input) { - // process all the messages before showing the confirmation dialog + public CompletableFuture requestToolExecutionConfirmation( + ConfirmationContent content, Object input) { reset(); - this.confirmDialog = new InvokeToolConfirmationDialog(this, title, message, input); + this.confirmDialog = new InvokeToolConfirmationDialog(this, content, input); + this.confirmDialog.addDisposeListener(e -> { + Composite ancestor = this.getParent(); + while (ancestor != null && !ancestor.isDisposed()) { + if (ancestor instanceof ChatContentViewer viewer) { + SwtUtils.invokeOnDisplayThreadAsync(() -> viewer.refreshLayoutFull(), viewer); + break; + } + ancestor = ancestor.getParent(); + } + }); CompletableFuture toolConfirmationFuture = this.confirmDialog .getConfirmationFuture(); - this.getParent().layout(); + this.getParent().requestLayout(); + + // Ensure the chat content viewer scrolls to show the newly created confirmation + // dialog. Walk up the composite hierarchy to find a ChatContentViewer + // and request scrolling. Use async exec because layout needs to complete first. + SwtUtils.invokeOnDisplayThreadAsync(() -> { + ChatContentViewer viewer = SwtUtils.findParentOfType(this.getParent(), ChatContentViewer.class); + if (viewer != null) { + if (this.confirmDialog != null && !this.confirmDialog.isDisposed()) { + viewer.showControl(this.confirmDialog); + } + } + + }, this.getParent()); return toolConfirmationFuture; } diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ChatContentViewer.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ChatContentViewer.java index 58ee3f5d..b3db64b4 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ChatContentViewer.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ChatContentViewer.java @@ -5,9 +5,13 @@ import java.util.ArrayList; import java.util.HashMap; +import java.util.IdentityHashMap; import java.util.List; import java.util.Map; +import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Pattern; @@ -15,14 +19,12 @@ import org.eclipse.e4.core.services.events.IEventBroker; import org.eclipse.lsp4j.WorkDoneProgressKind; import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.ScrolledComposite; -import org.eclipse.swt.events.ControlAdapter; -import org.eclipse.swt.events.ControlEvent; -import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.ui.PlatformUI; @@ -46,8 +48,14 @@ /** * Widget to display chat content. + * + *

A self-managed, windowed vertical scroller (not a {@link org.eclipse.swt.custom.ScrolledComposite}): + * on Windows a classic scroller cannot move very tall content far enough to reveal the newest messages. + * Here {@code cmpContent} is pinned to the viewport and each turn is positioned in + * viewport-local coordinates; off-window turns are parked with {@code setVisible(false)}, so no child is + * ever given an out-of-range native coordinate.

*/ -public class ChatContentViewer extends ScrolledComposite { +public class ChatContentViewer extends Composite { private static final int SCROLL_THRESHOLD = 100; @@ -68,11 +76,32 @@ public class ChatContentViewer extends ScrolledComposite { private Composite errorWidget; private BaseTurnWidget latestUserTurn; - private BaseTurnWidget latestCopilotTurn; + private CopilotTurnWidget latestCopilotTurn; private BaseTurnWidget latestTurnWidget; - // Auto-scroll state management private boolean autoScrollEnabled; + /** Streaming events queued by LSP threads and drained on the UI thread in batches. */ + private final Queue pendingEvents = new ConcurrentLinkedQueue<>(); + private final AtomicBoolean drainScheduled = new AtomicBoolean(false); + + /** Client-area width of the last layout pass; a change forces a full re-measure (text re-wraps). */ + private int lastLayoutWidth = -1; + + /** Guards against scheduling more than one pending async refresh from a burst of resize events. */ + private final AtomicBoolean refreshScheduled = new AtomicBoolean(false); + + /** Current logical scroll position (top of the viewport in content coordinates). */ + private int scrollOffset; + + /** Full logical content height in pixels; may far exceed any native coordinate limit. */ + private int totalHeight; + + /** Cached measured heights keyed by row control identity; invalidated on width change. */ + private final Map heightCache = new IdentityHashMap<>(); + + /** Cached font line height (px), the unit for one scroll line; recomputed when the font changes. */ + private int cachedLineHeight = -1; + /** * Create the composite. * @@ -80,45 +109,46 @@ public class ChatContentViewer extends ScrolledComposite { * @param style the style */ public ChatContentViewer(Composite parent, int style, ChatServiceManager serviceManager) { - super(parent, style | SWT.V_SCROLL); - this.setExpandHorizontal(true); - this.setExpandVertical(true); - this.setLayout(new GridLayout(1, true)); + super(parent, style | SWT.V_SCROLL | SWT.DOUBLE_BUFFERED); + // Null layout: children are positioned manually by relayoutWindow() so SWT never stacks them into + // one oversized composite. + this.setLayout(null); this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); this.setData(CssConstants.CSS_ID_KEY, "chat-content-viewer"); this.cmpContent = new Composite(this, SWT.NONE); - GridLayout gl = new GridLayout(1, true); - gl.marginHeight = 0; - gl.marginWidth = 0; - this.cmpContent.setLayout(gl); - this.cmpContent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - this.setContent(this.cmpContent); - - this.addControlListener(new ControlAdapter() { - @Override - public void controlResized(ControlEvent e) { - refreshScrollerLayout(); - } + this.cmpContent.setLayout(null); + + this.addListener(SWT.Resize, e -> { + layoutContentArea(); + coalesceAsync(refreshScheduled, this::refreshLayoutIncremental); }); - // Listen for user scroll events to manage auto-scroll behavior ScrollBar verticalBar = this.getVerticalBar(); if (verticalBar != null) { verticalBar.addListener(SWT.Selection, event -> { - int selection = verticalBar.getSelection(); - int maximum = verticalBar.getMaximum(); - int thumb = verticalBar.getThumb(); - - // If scrolled to bottom, keep auto-scroll enabled - // Otherwise disable it (user is viewing history) - int threshold = SCROLL_THRESHOLD; - int maxScrollPosition = maximum - thumb; - boolean isAtBottom = selection >= (maxScrollPosition - threshold); - autoScrollEnabled = isAtBottom; + scrollOffset = verticalBar.getSelection(); + autoScrollEnabled = isViewportAtBottom(); + relayoutWindow(); }); } + // The wheel does not move the scrollbar on a manually-laid-out composite, so handle it explicitly. + this.addListener(SWT.MouseWheel, event -> { + if (totalHeight <= getClientArea().height) { + return; + } + // event.count is the OS-provided number of lines to scroll for this notch; a font line height + // turns it into pixels, so one notch moves whole text lines like a native scrollable. + int newOffset = clampOffset(scrollOffset - event.count * lineHeight()); + if (newOffset != scrollOffset) { + scrollOffset = newOffset; + autoScrollEnabled = isViewportAtBottom(); + relayoutWindow(); + } + event.doit = false; + }); + this.turns = new HashMap<>(); this.activeThinkingBlockIds = new ConcurrentHashMap<>(); @@ -133,9 +163,9 @@ public void controlResized(ControlEvent e) { public void startNewTurn(String workDoneToken, String message) { BaseTurnWidget turnWidget = getLatestOrCreateNewTurnWidget(workDoneToken, false, true); turnWidget.appendMessage(message); - turnWidget.notifyTurnEnd(); + turnWidget.flushMessageBuffer(); - refreshScrollerLayout(); + refreshLayoutFull(); scrollToLatestUserTurn(); // Reset auto-scroll for new conversation turn autoScrollEnabled = true; @@ -158,9 +188,11 @@ public BaseTurnWidget getLatestOrCreateNewTurnWidget(String workDoneToken, boole turnWidget = latestTurnWidget; } else if (isCopilot) { // Create new Copilot turn widget - turnWidget = new CopilotTurnWidget(cmpContent, SWT.NONE, serviceManager, workDoneToken); - latestCopilotTurn = turnWidget; - latestTurnWidget = turnWidget; + CopilotTurnWidget copilotTurnWidget = new CopilotTurnWidget(cmpContent, SWT.NONE, serviceManager, + workDoneToken); + latestCopilotTurn = copilotTurnWidget; + latestTurnWidget = copilotTurnWidget; + turnWidget = copilotTurnWidget; } else { // Create new User turn widget turnWidget = new UserTurnWidget(cmpContent, SWT.NONE, serviceManager, workDoneToken); @@ -184,123 +216,140 @@ public void setConversationId(String conversationId) { } /** - * Process turn event. + * Process turn event. Events are queued and drained in batches on the UI thread so the LSP thread + * is never blocked and multiple in-flight events coalesce into a single layout pass. */ public void processTurnEvent(ChatProgressValue value) { - SwtUtils.invokeOnDisplayThread(() -> { - if (!turns.containsKey(value.getTurnId())) { - CopilotCore.LOGGER.error(new IllegalStateException("turnId not found: " + value.getTurnId())); - return; - } - BaseTurnWidget turnWidget = turns.get(value.getTurnId()); - if (turnWidget == null) { - appendMessageToTheLatestTurn(value.getReply()); - } - - ChatServiceManager chatServiceManager = CopilotUi.getPlugin().getChatServiceManager(); - - if (value.getKind() == WorkDoneProgressKind.report) { - if (turnWidget instanceof ThinkingTurnWidget thinkingTurn) { - thinkingTurn.setConversationContext(conversationId, value.getTurnId()); - thinkingTurn.appendThinking(value.getThinking()); - updateActiveThinkingBlockId(value.getTurnId(), thinkingTurn); - if (hasRenderableOutput(value)) { - // Seal before appending the reply so the spinner stops and the title is fetched. - thinkingTurn.sealThinking(); - } - } + pendingEvents.offer(value); + coalesceAsync(drainScheduled, this::drainPendingEvents); + } - if (value.getAgentRounds() != null && !value.getAgentRounds().isEmpty()) { - // Handle agent mode responses - AgentRound agentRound = value.getAgentRounds().get(0); + private void drainPendingEvents() { + if (isDisposed()) { + pendingEvents.clear(); + return; + } + ChatProgressValue event; + while ((event = pendingEvents.poll()) != null) { + doProcessTurnEvent(event); + } + refreshLayoutIncremental(); + scrollToBottomIfAutoScroll(); + // Events may have arrived while draining; schedule a follow-up drain if so. + if (!pendingEvents.isEmpty()) { + coalesceAsync(drainScheduled, this::drainPendingEvents); + } + } - if (agentRound.getReply() != null) { - turnWidget.appendMessage(agentRound.getReply()); - } + private void doProcessTurnEvent(ChatProgressValue value) { + if (!turns.containsKey(value.getTurnId())) { + CopilotCore.LOGGER.error(new IllegalStateException("turnId not found: " + value.getTurnId())); + return; + } + BaseTurnWidget turnWidget = turns.get(value.getTurnId()); + if (turnWidget == null) { + CopilotCore.LOGGER.error(new IllegalStateException("turnWidget not found: " + value.getTurnId())); + appendMessageToTheLatestTurn(value.getReply()); + return; + } - if (agentRound.getToolCalls() != null && !agentRound.getToolCalls().isEmpty()) { - AgentToolCall toolCall = agentRound.getToolCalls().get(0); - turnWidget.appendToolCallStatus(toolCall); + ChatServiceManager chatServiceManager = CopilotUi.getPlugin().getChatServiceManager(); - // Extract and process todo list from tool result details - processTodoListFromToolCall(chatServiceManager, value.getConversationId(), toolCall); - } - } else { - // Handle chat mode responses - turnWidget.appendMessage(value.getReply()); - } - } else if (value.getKind() == WorkDoneProgressKind.end) { - // Seal any in-progress thinking block before the turn ends. - if (turnWidget instanceof ThinkingTurnWidget thinkingTurn) { + if (value.getKind() == WorkDoneProgressKind.report) { + if (turnWidget instanceof ThinkingTurnWidget thinkingTurn) { + thinkingTurn.setConversationContext(conversationId, value.getTurnId()); + thinkingTurn.appendThinking(value.getThinking()); + updateActiveThinkingBlockId(value.getTurnId(), thinkingTurn); + if (hasRenderableOutput(value)) { + // Seal before appending the reply so the spinner stops and the title is fetched. thinkingTurn.sealThinking(); - updateActiveThinkingBlockId(value.getTurnId(), thinkingTurn); } - turnWidget.notifyTurnEnd(); } - refreshScrollerLayout(); - // Auto-scroll to bottom if enabled - if (shouldAutoScrollToBottom()) { - scrollToBottom(); - } + if (value.getAgentRounds() != null && !value.getAgentRounds().isEmpty()) { + // Handle agent mode responses + AgentRound agentRound = value.getAgentRounds().get(0); + + if (agentRound.getReply() != null) { + turnWidget.appendMessage(agentRound.getReply()); + } + + if (agentRound.getToolCalls() != null && !agentRound.getToolCalls().isEmpty()) { + AgentToolCall toolCall = agentRound.getToolCalls().get(0); + turnWidget.appendToolCallStatus(toolCall); - String errMsg = value.getErrorMessage(); - if (StringUtils.isNotEmpty(errMsg)) { - errMsg = REQUEST_ID_SUFFIX.matcher(errMsg).replaceAll(StringUtils.EMPTY).trim(); + // Extract and process todo list from tool result details + processTodoListFromToolCall(chatServiceManager, value.getConversationId(), toolCall); + } + } else { + // Handle chat mode responses + turnWidget.appendMessage(value.getReply()); } - String reason = value.getErrorReason(); - if (StringUtils.isNotEmpty(reason) && reason.equals("model_not_supported")) { - // TODO: add enable button for better UX. - errMsg = Messages.chat_model_unsupported_message; + } else if (value.getKind() == WorkDoneProgressKind.end) { + // Seal any in-progress thinking block before the turn ends. + if (turnWidget instanceof ThinkingTurnWidget thinkingTurn) { + thinkingTurn.sealThinking(); + updateActiveThinkingBlockId(value.getTurnId(), thinkingTurn); } - if (StringUtils.isNotEmpty(errMsg)) { - // TODO: Remove this legacy fallback after TBB is officially released. - // When the language server has not enabled token-based billing yet, fall back to the - // original main-branch 402 behavior: replace the message with a plan-driven fallback - // notice, switch to the fallback model, refresh quota, and replay the previous input. - CheckQuotaResult quotaStatus = this.serviceManager.getAuthStatusManager().getQuotaStatus(); - CopilotModel fallbackModel = null; - if (!quotaStatus.tokenBasedBillingEnabled() && value.getCode() == 402) { - CopilotPlan userPlan = quotaStatus.copilotPlan(); - fallbackModel = this.serviceManager.getModelService().getFallbackModel(); - String fallbackModelName = fallbackModel != null ? fallbackModel.getModelName() - : Messages.chat_noQuotaView_fallbackModel; - - if (MenuUtils.isCfiPlan(userPlan)) { - // Pro, Pro+ and Max message - errMsg = String.format(Messages.chat_noQuotaView_proProplusWarnMsg, fallbackModelName); - } else if (userPlan == CopilotPlan.business || userPlan == CopilotPlan.enterprise) { - // CE and CB message - errMsg = String.format(Messages.chat_noQuotaView_cbCeWarnMsg, fallbackModelName); - } + turnWidget.flushMessageBuffer(); + } + + String errMsg = value.getErrorMessage(); + if (StringUtils.isNotEmpty(errMsg)) { + errMsg = REQUEST_ID_SUFFIX.matcher(errMsg).replaceAll(StringUtils.EMPTY).trim(); + } + String reason = value.getErrorReason(); + if (StringUtils.isNotEmpty(reason) && reason.equals("model_not_supported")) { + // TODO: add enable button for better UX. + errMsg = Messages.chat_model_unsupported_message; + } + if (StringUtils.isNotEmpty(errMsg)) { + // TODO: Remove this legacy fallback after TBB is officially released. + // When the language server has not enabled token-based billing yet, fall back to the + // original main-branch 402 behavior: replace the message with a plan-driven fallback + // notice, switch to the fallback model, refresh quota, and replay the previous input. + CheckQuotaResult quotaStatus = this.serviceManager.getAuthStatusManager().getQuotaStatus(); + CopilotModel fallbackModel = null; + if (!quotaStatus.tokenBasedBillingEnabled() && value.getCode() == 402) { + CopilotPlan userPlan = quotaStatus.copilotPlan(); + fallbackModel = this.serviceManager.getModelService().getFallbackModel(); + String fallbackModelName = fallbackModel != null ? fallbackModel.getModelName() + : Messages.chat_noQuotaView_fallbackModel; + + if (MenuUtils.isCfiPlan(userPlan)) { + // Pro, Pro+ and Max message + errMsg = String.format(Messages.chat_noQuotaView_proProplusWarnMsg, fallbackModelName); + } else if (userPlan == CopilotPlan.business || userPlan == CopilotPlan.enterprise) { + // CE and CB message + errMsg = String.format(Messages.chat_noQuotaView_cbCeWarnMsg, fallbackModelName); } + } - renderWarnMessageWithUpgradePlanButton(errMsg, value.getCode(), value.getErrorModelProviderName()); - - // TODO: Remove this legacy fallback after TBB is officially released. - // Only replay the previous input when a fallback model is actually available; otherwise - // setFallBackModelAsActiveModel() is a no-op and re-posting the input with the same - // active model would just trigger the same 402 again. - if (!quotaStatus.tokenBasedBillingEnabled() && value.getCode() == 402 - && quotaStatus.copilotPlan() != CopilotPlan.free - && fallbackModel != null) { - // Detach the failed turn so the replayed response creates a new Copilot turn below the - // warning, instead of streaming into the same turn that just rendered the warn widget. - this.latestTurnWidget = null; - this.latestCopilotTurn = null; - - this.serviceManager.getModelService().setFallBackModelAsActiveModel(); - this.serviceManager.getAuthStatusManager().checkQuota(); - - String previousInput = this.serviceManager.getUserPreferenceService().getPreviousInput(StringUtils.EMPTY); - if (StringUtils.isNotEmpty(previousInput)) { - IEventBroker eventBroker = PlatformUI.getWorkbench().getService(IEventBroker.class); - Map properties = Map.of("previousInput", previousInput, "needCreateUserTurn", false); - eventBroker.post(CopilotEventConstants.TOPIC_CHAT_ON_SEND, properties); - } + renderWarnMessageWithUpgradePlanButton(errMsg, value.getCode(), value.getErrorModelProviderName()); + + // TODO: Remove this legacy fallback after TBB is officially released. + // Only replay the previous input when a fallback model is actually available; otherwise + // setFallBackModelAsActiveModel() is a no-op and re-posting the input with the same + // active model would just trigger the same 402 again. + if (!quotaStatus.tokenBasedBillingEnabled() && value.getCode() == 402 + && quotaStatus.copilotPlan() != CopilotPlan.free + && fallbackModel != null) { + // Detach the failed turn so the replayed response creates a new Copilot turn below the + // warning, instead of streaming into the same turn that just rendered the warn widget. + this.latestTurnWidget = null; + this.latestCopilotTurn = null; + + this.serviceManager.getModelService().setFallBackModelAsActiveModel(); + this.serviceManager.getAuthStatusManager().checkQuota(); + + String previousInput = this.serviceManager.getUserPreferenceService().getPreviousInput(StringUtils.EMPTY); + if (StringUtils.isNotEmpty(previousInput)) { + IEventBroker eventBroker = PlatformUI.getWorkbench().getService(IEventBroker.class); + Map properties = Map.of("previousInput", previousInput, "needCreateUserTurn", false); + eventBroker.post(CopilotEventConstants.TOPIC_CHAT_ON_SEND, properties); } } - }, this); + } } /** Returns the active thinking block ID last observed while processing this turn's progress. */ @@ -379,6 +428,38 @@ private void processTodoListFromToolCall(ChatServiceManager chatServiceManager, } } + /** + * Shows the compacting status on the latest Copilot turn after flushing any buffered reply text. + */ + public void showCompactingStatusOnLatestCopilotTurn() { + if (latestCopilotTurn == null || latestCopilotTurn.isDisposed()) { + return; + } + // Flush any buffered reply text from the previous round so it is rendered + // above the compacting spinner; otherwise it would be concatenated with + // the next round's reply and produce a single garbled line. + latestCopilotTurn.flushMessageBuffer(); + latestCopilotTurn.showCompactingStatus(); + refreshLayoutFull(); + scrollToBottomIfAutoScroll(); + } + + /** + * Hides the compacting status on the latest Copilot turn, flushing any buffered reply text + * first as a guard against buffered content that was not flushed by an end progress event. + */ + public void hideCompactingStatusOnLatestCopilotTurn() { + if (latestCopilotTurn == null || latestCopilotTurn.isDisposed()) { + return; + } + // Always flush before hiding; the buffer should be empty at this point, but flush as a guard + // in case a cancel path did not receive an end progress event to flush it. + latestCopilotTurn.flushMessageBuffer(); + latestCopilotTurn.hideCompactingStatus(); + refreshLayoutFull(); + scrollToBottomIfAutoScroll(); + } + /** * Get an existed turn widget by turn ID. */ @@ -387,9 +468,17 @@ public BaseTurnWidget getTurnWidget(String turnId) { } private void renderWarnMessageWithUpgradePlanButton(String errorMessage, int code, String modelProviderName) { - latestTurnWidget.createWarnDialog(errorMessage, code, modelProviderName); - refreshScrollerLayout(); + Composite warnWidget = latestTurnWidget.createWarnDialog(errorMessage, code, modelProviderName); + refreshLayoutFull(); scrollToLatestUserTurn(); + // Ensure the chat content viewer scrolls to show the newly created warning banner. Walk up the composite hierarchy + // to find a ChatContentViewer and request scrolling. Use async exec because layout needs to complete first. + SwtUtils.invokeOnDisplayThreadAsync(() -> { + if (warnWidget != null && !warnWidget.isDisposed()) { + showControl(warnWidget); + } + + }, this.getParent()); } /** @@ -400,77 +489,266 @@ public void renderErrorMessage(String errorMessage) { this.errorWidget.dispose(); } this.errorWidget = new ErrorWidget(cmpContent, SWT.BOTTOM, errorMessage); - refreshScrollerLayout(); + refreshLayoutFull(); scrollToLatestUserTurn(); + // Ensure the chat content viewer scrolls to show the newly created error banner. + SwtUtils.invokeOnDisplayThreadAsync(() -> { + if (this.errorWidget != null && !this.errorWidget.isDisposed()) { + this.showControl(this.errorWidget); + } + }, this.getParent()); } /** - * Update the size of scrolled composite when there are content updates. + * Coalesces a burst of calls into a single async pass on the UI thread, clearing {@code scheduled} + * right before {@code task} runs so work arriving during the task re-schedules a follow-up pass. + * Breaks synchronous re-entrancy without a re-entrancy guard. + * + * @param scheduled the per-task latch guarding against duplicate scheduling + * @param task the work to run once on the next UI-thread turn */ - public void refreshScrollerLayout() { - if (this.isDisposed()) { - return; + private void coalesceAsync(AtomicBoolean scheduled, Runnable task) { + if (scheduled.compareAndSet(false, true)) { + SwtUtils.invokeOnDisplayThreadAsync(() -> { + scheduled.set(false); + task.run(); + }, this); } + } - Rectangle clientArea = this.getClientArea(); - Point containerSize = cmpContent.computeSize(clientArea.width, SWT.DEFAULT); + /** + * Full re-measure entry point for external callers. Layout only; scrolling is a separate concern + * handled by callers via {@link #scrollToBottomIfAutoScroll()}. + */ + public void refreshLayoutFull() { + refreshLayout(MeasureMode.FULL); + } + + /** + * Incremental re-measure of just the trailing (streaming) turns. Layout only; scrolling is handled + * separately by callers via {@link #scrollToBottomIfAutoScroll()}. + */ + private void refreshLayoutIncremental() { + refreshLayout(MeasureMode.INCREMENTAL); + } + + /** + * Selects how many turns {@link #refreshLayout(MeasureMode)} re-measures. + */ + private enum MeasureMode { + /** Re-measure every turn. */ + FULL, + /** Only re-measure the trailing (mutating) turns; sealed turns keep cached sizes. */ + INCREMENTAL + } - // Use the default size as a fallback - if (latestUserTurn == null) { - this.setMinSize(containerSize); + /** + * Re-measures turns and re-runs the windowing pass. {@link MeasureMode#INCREMENTAL} keeps sealed + * turns' cached heights; a width change forces a full re-measure because text re-wraps. + */ + private void refreshLayout(MeasureMode mode) { + if (this.isDisposed()) { return; } + Rectangle clientArea = this.getClientArea(); + int width = clientArea.width; + boolean fullMeasure = mode == MeasureMode.FULL || width != lastLayoutWidth; + lastLayoutWidth = width; - Point userTurnSize = latestUserTurn.computeSize(SWT.DEFAULT, SWT.DEFAULT); - Point copilotTurnSize = latestCopilotTurn == null ? new Point(0, 0) - : latestCopilotTurn.computeSize(SWT.DEFAULT, SWT.DEFAULT); - - // Calculate the content height, so that the latest user turn is able to be put at the top of the client area. - int contentHeight = 0; - int roundedHeight = userTurnSize.y + copilotTurnSize.y; - if (roundedHeight < clientArea.height) { - contentHeight = clientArea.height + containerSize.y - roundedHeight; + if (fullMeasure) { + heightCache.clear(); } else { - contentHeight = containerSize.y; + invalidateTrailingTurnHeights(); } - this.setMinHeight(contentHeight); - this.setMinWidth(containerSize.x); - this.layout(true, true); + layoutContentArea(); + relayoutWindow(); } /** - * Check if auto-scroll to bottom is needed. Only scroll when auto-scroll is enabled (user hasn't manually scrolled - * during response). + * Scrolls to the bottom when auto-scroll is enabled. The bottom padding reserved by {@link + * #relayoutWindow()} makes this pin the latest user turn to the top while the round is short, then + * follow the real bottom once it grows past the viewport. */ - private boolean shouldAutoScrollToBottom() { - if (this.isDisposed() || latestUserTurn == null) { - return false; + public void scrollToBottomIfAutoScroll() { + if (this.isDisposed() || latestUserTurn == null || latestUserTurn.isDisposed()) { + return; } - if (!autoScrollEnabled) { - return false; + return; } + scrollOffset = Integer.MAX_VALUE; + relayoutWindow(); + } + /** + * Drops the cached heights of the trailing (mutating) turns so they are re-measured next pass, while + * sealed historical turns keep their cached size. + */ + private void invalidateTrailingTurnHeights() { + if (latestUserTurn != null && !latestUserTurn.isDisposed()) { + heightCache.remove(latestUserTurn); + } + if (latestCopilotTurn != null && !latestCopilotTurn.isDisposed()) { + heightCache.remove(latestCopilotTurn); + } + if (errorWidget != null && !errorWidget.isDisposed()) { + heightCache.remove(errorWidget); + } + } + + /** Pins {@code cmpContent} to the current viewport rectangle so it is never grown or moved. */ + private void layoutContentArea() { + if (cmpContent == null || cmpContent.isDisposed()) { + return; + } Rectangle clientArea = this.getClientArea(); - Point userTurnSize = latestUserTurn.computeSize(SWT.DEFAULT, SWT.DEFAULT); - Point copilotTurnSize = latestCopilotTurn == null ? new Point(0, 0) - : latestCopilotTurn.computeSize(SWT.DEFAULT, SWT.DEFAULT); + cmpContent.setBounds(0, 0, Math.max(0, clientArea.width), Math.max(0, clientArea.height)); + } - int roundedHeight = userTurnSize.y + copilotTurnSize.y; + /** + * The core windowing pass: measures every turn (cached), positions the ones intersecting the + * viewport in viewport-local coordinates, and parks the rest with {@code setVisible(false)} so no + * native child ever gets an out-of-range coordinate. + */ + private void relayoutWindow() { + if (this.isDisposed() || cmpContent == null || cmpContent.isDisposed()) { + return; + } + Rectangle clientArea = this.getClientArea(); + int width = clientArea.width; + int viewport = clientArea.height; + if (width <= 0 || viewport <= 0) { + return; + } + + Control[] children = cmpContent.getChildren(); + int[] tops = new int[children.length]; + int[] heights = new int[children.length]; + boolean[] remeasured = new boolean[children.length]; + int running = 0; + int latestUserTop = -1; + for (int i = 0; i < children.length; i++) { + if (children[i] == latestUserTurn) { + latestUserTop = running; + } + boolean wasCached = heightCache.containsKey(children[i]); + int height = measuredHeight(children[i], width); + tops[i] = running; + heights[i] = height; + // A cache miss means the turn was (re)measured this pass: its width changed or its content + // mutated, so its internal GridLayout must be re-run. + remeasured[i] = !wasCached; + running += height; + } + int rawHeight = running; + + // Bottom padding (virtual, no widget): when the last round is shorter than the viewport, reserve + // whitespace below it so the latest user turn can pin to the top instead of floating mid-screen. + // Without it maxOffset is too small, so the new message cannot reach the top and "scroll to + // bottom" misaligns with the real maximum, breaking auto-scroll. + int bottomPadding = 0; + if (latestUserTop >= 0) { + int lastRoundHeight = rawHeight - latestUserTop; + if (lastRoundHeight < viewport) { + bottomPadding = viewport - lastRoundHeight; + } + } + totalHeight = rawHeight + bottomPadding; + scrollOffset = clampOffset(scrollOffset); + + for (int i = 0; i < children.length; i++) { + Control child = children[i]; + if (child.isDisposed()) { + continue; + } + int y = tops[i] - scrollOffset; + if (y + heights[i] > 0 && y < viewport) { + child.setBounds(0, y, width, heights[i]); + if (!child.getVisible()) { + child.setVisible(true); + } + // Run the turn's own layout so its GridLayout children (wrapped text, code blocks, footers) + // reflow. + if (remeasured[i] && child instanceof Composite composite) { + composite.layout(); + } + } else if (child.getVisible()) { + child.setVisible(false); + } + } - // Only auto-scroll when content height exceeds the visible area - return roundedHeight >= clientArea.height; + updateScrollBar(viewport); + } + + /** Returns the measured height of a row, using the identity cache when available. */ + private int measuredHeight(Control child, int width) { + if (child == null || child.isDisposed()) { + return 0; + } + Integer cached = heightCache.get(child); + if (cached != null) { + return cached; + } + int height = child.computeSize(width, SWT.DEFAULT, true).y; + heightCache.put(child, height); + return height; + } + + private void updateScrollBar(int viewport) { + ScrollBar verticalBar = this.getVerticalBar(); + if (verticalBar == null) { + return; + } + if (totalHeight <= viewport) { + int safeViewport = Math.max(1, viewport); + verticalBar.setValues(0, 0, safeViewport, safeViewport, lineHeight(), safeViewport); + verticalBar.setEnabled(false); + return; + } + verticalBar.setEnabled(true); + verticalBar.setValues(scrollOffset, 0, totalHeight, viewport, lineHeight(), viewport); + } + + private int maxOffset() { + return Math.max(0, totalHeight - getClientArea().height); + } + + private int clampOffset(int offset) { + return Math.max(0, Math.min(offset, maxOffset())); + } + + private boolean isViewportAtBottom() { + return scrollOffset >= maxOffset() - SCROLL_THRESHOLD; + } + + /** One scroll "line" in pixels: the current font's line height. Cached until the font changes. */ + private int lineHeight() { + if (cachedLineHeight < 0) { + GC gc = new GC(this); + try { + gc.setFont(getFont()); + cachedLineHeight = Math.max(1, gc.getFontMetrics().getHeight()); + } finally { + gc.dispose(); + } + } + return cachedLineHeight; + } + + @Override + public void setFont(Font font) { + super.setFont(font); + cachedLineHeight = -1; } /** * Scroll to the bottom. */ private void scrollToBottom() { - ScrollBar verticalBar = this.getVerticalBar(); - if (verticalBar != null) { - this.setOrigin(0, verticalBar.getMaximum()); - } + autoScrollEnabled = true; + scrollOffset = Integer.MAX_VALUE; + relayoutWindow(); } /** @@ -478,25 +756,82 @@ private void scrollToBottom() { */ private void scrollToLatestUserTurn() { // Scroll to the bottom as a fallback. - if (latestUserTurn == null) { + if (latestUserTurn == null || latestUserTurn.isDisposed()) { scrollToBottom(); return; } - // Use async execution to ensure layout is computed before reading positions. - // Using sync execution would read positions before the layout is complete, - // resulting in incorrect scroll position (always scrolling to 0). + // Async so heights are measured before reading positions. SwtUtils.invokeOnDisplayThreadAsync(() -> { if (this.isDisposed() || latestUserTurn.isDisposed()) { return; } - Point turnLocation = latestUserTurn.getLocation(); - this.setOrigin(0, turnLocation.y); + scrollOffset = clampOffset(topOf(latestUserTurn)); + relayoutWindow(); }, this); } + /** Returns the cumulative top offset (in content coordinates) of the given row control. */ + private int topOf(Control target) { + int width = this.getClientArea().width; + int running = 0; + for (Control child : cmpContent.getChildren()) { + if (child == target) { + break; + } + running += measuredHeight(child, width); + } + return running; + } + + /** + * Scrolls the viewport to make {@code target} visible, equivalent to + * {@link org.eclipse.swt.custom.ScrolledComposite#showControl(Control)}. + * + *

Walks up the widget tree to find the direct child of {@code cmpContent} that contains + * {@code target}, computes the content-coordinate position of {@code target} by summing + * the turn's {@link #topOf} value with the local y offsets down to {@code target}, then + * adjusts {@link #scrollOffset} by the minimum amount needed to bring {@code target} fully + * into the viewport.

+ */ + public void showControl(Composite target) { + if (target == null || target.isDisposed()) { + return; + } + // Walk up to find the direct child of cmpContent that is the ancestor of target. + Control ancestor = target; + while (ancestor != null && ancestor.getParent() != cmpContent) { + ancestor = ancestor.getParent(); + } + if (ancestor == null || ancestor.getParent() != cmpContent) { + return; + } + // Content-coordinate top of the enclosing turn widget. + int ancestorTop = topOf(ancestor); + // Accumulate the local y offset by walking from target up to (but not including) ancestor. + int localY = 0; + for (Control c = target; c != ancestor; c = c.getParent()) { + localY += c.getLocation().y; + } + int targetTop = ancestorTop + localY; + int targetBottom = targetTop + target.getSize().y; + int viewport = getClientArea().height; + // Scroll the minimum amount: down if target is below the visible area, up if above. + int newOffset = scrollOffset; + if (targetBottom > scrollOffset + viewport) { + newOffset = targetBottom - viewport; + } + if (targetTop < newOffset) { + newOffset = targetTop; + } + scrollOffset = clampOffset(newOffset); + relayoutWindow(); + } + @Override public void dispose() { + pendingEvents.clear(); + heightCache.clear(); super.dispose(); for (BaseTurnWidget turn : turns.values()) { turn.dispose(); diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ChatView.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ChatView.java index 65cf0a74..c5aa62c6 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ChatView.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ChatView.java @@ -3,7 +3,10 @@ package com.microsoft.copilot.eclipse.ui.chat; +import java.util.ArrayList; +import java.util.Collections; import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -31,7 +34,7 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.ScrollBar; +import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IPartListener2; import org.eclipse.ui.IWorkbenchPartReference; import org.eclipse.ui.PlatformUI; @@ -59,6 +62,8 @@ import com.microsoft.copilot.eclipse.core.lsp.protocol.ChatStepStatus; import com.microsoft.copilot.eclipse.core.lsp.protocol.ChatStepTitles; import com.microsoft.copilot.eclipse.core.lsp.protocol.ChatTurnResult; +import com.microsoft.copilot.eclipse.core.lsp.protocol.CompressionCompletedParams; +import com.microsoft.copilot.eclipse.core.lsp.protocol.CompressionStartedParams; import com.microsoft.copilot.eclipse.core.lsp.protocol.ContextSizeInfo; import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel; import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotStatusResult; @@ -78,8 +83,11 @@ import com.microsoft.copilot.eclipse.core.persistence.CopilotTurnData.ReplyData; import com.microsoft.copilot.eclipse.core.persistence.CopilotTurnData.ToolCallData; import com.microsoft.copilot.eclipse.core.persistence.UserTurnData; +import com.microsoft.copilot.eclipse.terminal.api.IRunInTerminalTool; +import com.microsoft.copilot.eclipse.terminal.api.TerminalServiceManager; import com.microsoft.copilot.eclipse.ui.CopilotUi; import com.microsoft.copilot.eclipse.ui.UiConstants; +import com.microsoft.copilot.eclipse.ui.chat.services.AgentToolService; import com.microsoft.copilot.eclipse.ui.chat.services.ChatCompletionService; import com.microsoft.copilot.eclipse.ui.chat.services.ChatServiceManager; import com.microsoft.copilot.eclipse.ui.chat.services.DebugEventAutoResponseHandler; @@ -144,6 +152,8 @@ public class ChatView extends ViewPart implements ChatProgressListener, MessageL private EventHandler autoBreakpointToggleHandler; private EventHandler rateLimitWarningHandler; private EventHandler quotaWarningHandler; + private EventHandler compressionStartedHandler; + private EventHandler compressionCompletedHandler; // Context activation for chat view keyboard shortcuts private static final String CHAT_VIEW_CONTEXT = "com.microsoft.copilot.eclipse.chatViewContext"; @@ -157,6 +167,9 @@ public class ChatView extends ViewPart implements ChatProgressListener, MessageL private IContextActivation chatViewContextActivation; private IPartListener2 partListener; + /** Controls whose {@link #requestLayout(Control...)} call was suppressed while this view was hidden. */ + private final Set pendingLayoutRequests = new LinkedHashSet<>(); + @Override public void createPartControl(Composite parent) { this.parent = parent; @@ -394,6 +407,45 @@ public void done(IJobChangeEvent event) { }; this.eventBroker.subscribe(CopilotEventConstants.TOPIC_QUOTA_WARNING, this.quotaWarningHandler); + this.compressionStartedHandler = event -> { + Object data = event.getProperty(IEventBroker.DATA); + if (!(data instanceof CompressionStartedParams params)) { + return; + } + if (!isCompressionForActiveConversation(params.conversationId())) { + return; + } + SwtUtils.invokeOnDisplayThreadAsync(() -> { + if (this.chatContentViewer == null || this.chatContentViewer.isDisposed()) { + return; + } + this.chatContentViewer.showCompactingStatusOnLatestCopilotTurn(); + }, parent); + }; + this.eventBroker.subscribe(CopilotEventConstants.TOPIC_CHAT_COMPRESSION_STARTED, + this.compressionStartedHandler); + + this.compressionCompletedHandler = event -> { + Object data = event.getProperty(IEventBroker.DATA); + if (!(data instanceof CompressionCompletedParams params)) { + return; + } + if (!isCompressionForActiveConversation(params.conversationId())) { + return; + } + SwtUtils.invokeOnDisplayThreadAsync(() -> { + if (this.chatContentViewer == null || this.chatContentViewer.isDisposed()) { + return; + } + this.chatContentViewer.hideCompactingStatusOnLatestCopilotTurn(); + if (params.contextInfo() != null) { + this.chatServiceManager.getContextWindowService().updateContextSize(params.contextInfo()); + } + }, parent); + }; + this.eventBroker.subscribe(CopilotEventConstants.TOPIC_CHAT_COMPRESSION_COMPLETED, + this.compressionCompletedHandler); + // Register part listener to activate/deactivate chat view context for keyboard shortcuts registerPartListener(); } @@ -471,7 +523,12 @@ public void partOpened(IWorkbenchPartReference partRef) { @Override public void partVisible(IWorkbenchPartReference partRef) { - // No action needed + // Replay layout requests skipped while this view was hidden behind another part in the same + // stack, targeted at just the specific control(s) that changed -- avoids a blind full-tree + // relayout of the (possibly long) chat conversation. + if (partRef.getPart(false) == ChatView.this) { + flushPendingLayoutRequests(); + } } }; @@ -1027,7 +1084,16 @@ private void onSendInternal(String workDoneToken, String message, String agentSl final CopilotLanguageServerConnection ls = CopilotCore.getPlugin().getCopilotLanguageServer(); final CopilotModel activeModel = chatServiceManager.getModelService().getActiveModel(); + // Collect attached file paths for auto-approve of file operations. + // Stage as pending so confirmation requests can match immediately, + // even before the real conversation ID arrives. + List pendingAttachedFiles = + collectAttachedFilePaths(currentFile, references); + stagePendingAttachedFiles(pendingAttachedFiles); + if (conversationState == ConversationState.CONTINUED_CONVERSATION) { + // conversationId is already the real one — flush pending into registry + flushPendingAttachedFiles(this.conversationId); // Continue existing conversation - persist user message and send to existing conversation if (persistenceManager != null) { this.persistUserTurnFuture = persistenceManager.persistUserTurnInfo(conversationId, null, processedMessage, @@ -1131,6 +1197,9 @@ private void onSendInternal(String workDoneToken, String message, String agentSl CopilotCore.LOGGER.error("Error updating conversation ID in persistence manager: ", e); } + // Flush pending attached files into the real conversation ID + flushPendingAttachedFiles(newConversationId); + // Render model information in the Copilot turn widget if (result != null && StringUtils.isNotBlank(result.getModelName()) && !UiConstants.GITHUB_COPILOT_CODING_AGENT_SLUG.equals(result.getAgentSlug())) { @@ -1144,6 +1213,7 @@ private void onSendInternal(String workDoneToken, String message, String agentSl } } }).exceptionally(th -> { + clearPendingAttachedFiles(); if (!ConversationUtils.isConversationCancellationThrowable(th)) { CopilotCore.LOGGER.error("Error creating new conversation with exception: ", th); displayErrorAndResetSendButton(workDoneToken, th.getMessage()); @@ -1192,6 +1262,15 @@ private boolean isProgressForCurrentConversation(ChatProgressValue value) { return StringUtils.equals(progressConversationId, this.conversationId); } + /** + * Checks whether a compression notification targets either the main conversation or the active subagent + * conversation, so the UI can reflect compaction happening at either level. + */ + private boolean isCompressionForActiveConversation(String compressionConversationId) { + return StringUtils.equals(compressionConversationId, this.conversationId) + || StringUtils.equals(compressionConversationId, this.subagentConversationId); + } + /** * Align with @Workspace of vscode, because we are actually indexing the whole workspace, not a single project. * (@Project is only for IntelliJ.) @@ -1246,8 +1325,75 @@ private void handleCodingAgentMessage(CodingAgentMessageRequestParams params) { }, parent); } + /** + * Collects absolute paths of the current file and explicitly attached + * references. The returned list is saved to the + * {@link AttachedFileRegistry} once a stable conversation ID is available. + */ + private List collectAttachedFilePaths(IFile currentFile, + List references) { + List filePaths = new ArrayList<>(); + if (currentFile != null && currentFile.getLocation() != null) { + filePaths.add(currentFile.getLocation().toOSString()); + } + if (references != null) { + for (IResource r : references) { + if (r instanceof IFile && r.getLocation() != null) { + filePaths.add(r.getLocation().toOSString()); + } + } + } + return filePaths; + } + + /** + * Stages file paths as pending in the attached file registry. + * These are immediately visible to confirmation handlers. + */ + private void stagePendingAttachedFiles(List filePaths) { + if (filePaths.isEmpty() || this.chatServiceManager == null) { + return; + } + AgentToolService agentToolService = + this.chatServiceManager.getAgentToolService(); + if (agentToolService == null) { + return; + } + agentToolService.getAttachedFileRegistry().addPending(filePaths); + } + + /** + * Flushes pending attached files into per-conversation storage + * under the given (stable) conversation ID. + */ + private void flushPendingAttachedFiles(String conversationId) { + if (this.chatServiceManager == null + || StringUtils.isBlank(conversationId)) { + return; + } + AgentToolService agentToolService = + this.chatServiceManager.getAgentToolService(); + if (agentToolService == null) { + return; + } + agentToolService.getAttachedFileRegistry() + .flushPending(conversationId); + } + + private void clearPendingAttachedFiles() { + if (this.chatServiceManager == null) { + return; + } + AgentToolService agentToolService = + this.chatServiceManager.getAgentToolService(); + if (agentToolService != null) { + agentToolService.getAttachedFileRegistry().clearPending(); + } + } + private void clearCurrentConversation() { this.onCancel(); + clearPendingAttachedFiles(); this.hasHistory = false; this.conversationId = ""; this.conversationState = ConversationState.NEW_CONVERSATION; @@ -1279,6 +1425,7 @@ public void onCancel() { this.subagentConversationId = null; this.lastRunSubagentToolCallId = null; + cancelCurrentTerminalCommand(); if (persistenceManager != null && StringUtils.isNotBlank(this.conversationId)) { persistenceManager.markRunningToolCallsCancelledAndPersist(this.conversationId); @@ -1292,6 +1439,21 @@ public void onCancel() { if (this.actionBar != null && !this.actionBar.isDisposed()) { this.actionBar.resetSendButton(); } + if (this.chatContentViewer != null && !this.chatContentViewer.isDisposed()) { + this.chatContentViewer.hideCompactingStatusOnLatestCopilotTurn(); + } + } + + private void cancelCurrentTerminalCommand() { + try { + TerminalServiceManager terminalManager = TerminalServiceManager.getInstance(); + IRunInTerminalTool terminalTool = terminalManager != null ? terminalManager.getCurrentService() : null; + if (terminalTool != null) { + terminalTool.cancelCurrentCommand(); + } + } catch (RuntimeException e) { + CopilotCore.LOGGER.error("Failed to cancel terminal command", e); + } } @Override @@ -1468,6 +1630,14 @@ public void dispose() { this.eventBroker.unsubscribe(this.quotaWarningHandler); quotaWarningHandler = null; } + if (compressionStartedHandler != null) { + this.eventBroker.unsubscribe(this.compressionStartedHandler); + compressionStartedHandler = null; + } + if (compressionCompletedHandler != null) { + this.eventBroker.unsubscribe(this.compressionCompletedHandler); + compressionCompletedHandler = null; + } } if (this.chatServiceManager != null) { @@ -1543,16 +1713,75 @@ public void dispose() { getSite().getPage().removePartListener(this.partListener); this.partListener = null; } + pendingLayoutRequests.clear(); deactivateChatViewContext(); super.dispose(); } /** - * Layout the view. + * Request a layout of the given control(s), which must be part of this view's widget tree. + * + *

Passing every control whose content actually changed (rather than a blind {@code + * parent.layout(true, true)}) lets SWT flush exactly those controls' cached sizes -- and only the + * ancestor chains leading to them -- so it never touches unrelated subtrees like the chat + * conversation history. Passing only a subset of what changed (e.g. a text label but not a + * sibling icon label that also changed) will leave the omitted control's cached size stale. + * + *

Skipped while the view isn't visible (e.g. stacked behind another part) to avoid layout cost + * on every editor switch; {@code changed} is instead remembered and replayed by {@link + * #flushPendingLayoutRequests()} once the view becomes visible again. + * + * @param changed every control whose content/layout data just changed */ - public void layout(boolean changed, boolean all) { - parent.layout(changed, all); + public void requestLayout(Control... changed) { + if (getSite() == null || getSite().getPage() == null || !getSite().getPage().isPartVisible(this)) { + if (changed != null) { + Collections.addAll(pendingLayoutRequests, changed); + } + return; + } + layoutNow(changed); + } + + /** + * Replays layout requests that were suppressed by {@link #requestLayout(Control...)} while this + * view was hidden, targeted at just the specific control(s) that changed. + */ + private void flushPendingLayoutRequests() { + if (pendingLayoutRequests.isEmpty()) { + return; + } + // Snapshot and clear before replaying: a control's requestLayout() could in principle + // synchronously trigger a new call back into requestLayout(Control...), which would otherwise + // mutate pendingLayoutRequests while it's being iterated. + Set toFlush = new LinkedHashSet<>(pendingLayoutRequests); + pendingLayoutRequests.clear(); + layoutNow(toFlush.toArray(new Control[0])); + } + + /** + * Flushes cached sizes for exactly the given controls (and the ancestor chains leading to them) + * and lays them out, in a single batched pass. Silently ignores {@code null} or disposed + * controls. + */ + private void layoutNow(Control... controls) { + List valid = new ArrayList<>(); + if (controls != null) { + for (Control control : controls) { + if (control != null && !control.isDisposed()) { + valid.add(control); + } + } + } + if (valid.isEmpty()) { + return; + } + Shell shell = valid.get(0).getShell(); + if (shell == null || shell.isDisposed()) { + return; + } + shell.layout(valid.toArray(new Control[0]), SWT.DEFER); } /** @@ -1659,16 +1888,10 @@ public void scrollContentToBottom() { return; } - chatContentViewer.getDisplay().asyncExec(() -> { - if (chatContentViewer.isDisposed()) { - return; - } - chatContentViewer.refreshScrollerLayout(); - ScrollBar verticalBar = chatContentViewer.getVerticalBar(); - if (verticalBar != null && !verticalBar.isDisposed()) { - chatContentViewer.setOrigin(0, verticalBar.getMaximum()); - } - }); + SwtUtils.invokeOnDisplayThreadAsync(() -> { + chatContentViewer.refreshLayoutFull(); + chatContentViewer.scrollToBottomIfAutoScroll(); + }, chatContentViewer); } /** @@ -1687,8 +1910,11 @@ private void renderModelInfoInTurnWidget(String turnId, String modelName, double if (turnWidget instanceof CopilotTurnWidget copilotWidget) { copilotWidget.renderModelInfo(modelName, billingMultiplier, reasoningEffort); - // Refresh the scroller layout to ensure the footer is visible - SwtUtils.invokeOnDisplayThreadAsync(() -> this.chatContentViewer.refreshScrollerLayout(), this.chatContentViewer); + // Refresh the scroller layout to ensure the footer is visible. + SwtUtils.invokeOnDisplayThreadAsync(() -> { + this.chatContentViewer.refreshLayoutFull(); + this.chatContentViewer.scrollToBottomIfAutoScroll(); + }, this.chatContentViewer); } } @@ -1724,17 +1950,17 @@ private void restoreTurn(AbstractTurnData turn) { if (userTurn.getMessage() == null || StringUtils.isNotBlank(userTurn.getMessage().getText())) { BaseTurnWidget userTurnWidget = chatContentViewer.getLatestOrCreateNewTurnWidget(turn.getTurnId(), false, true); userTurnWidget.appendMessage(userTurn.getMessage().getText()); - userTurnWidget.notifyTurnEnd(); + userTurnWidget.flushMessageBuffer(); return; } } else if (turn instanceof CopilotTurnData copilotTurn) { BaseTurnWidget copilotTurnWidget = chatContentViewer.getLatestOrCreateNewTurnWidget(turn.getTurnId(), true, true); restoreCopilotTurnContent(copilotTurn, copilotTurnWidget); - copilotTurnWidget.notifyTurnEnd(); + copilotTurnWidget.flushMessageBuffer(); // Restore model info footer if model name is present - // This must be done AFTER notifyTurnEnd() to ensure footer appears at the bottom + // This must be done AFTER flushMessageBuffer() to ensure footer appears at the bottom ReplyData replyData = copilotTurn.getReply(); if (replyData != null && StringUtils.isNotBlank(replyData.getModelName())) { // Reasoning effort was captured and persisted at send time so the footer reflects what was actually used diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/CopilotTurnWidget.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/CopilotTurnWidget.java index e3efbdd7..f026aa0e 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/CopilotTurnWidget.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/CopilotTurnWidget.java @@ -17,6 +17,7 @@ import com.microsoft.copilot.eclipse.ui.chat.services.ChatServiceManager; import com.microsoft.copilot.eclipse.ui.i18n.Messages; import com.microsoft.copilot.eclipse.ui.swt.CssConstants; +import com.microsoft.copilot.eclipse.ui.swt.SpinnerAnimator; import com.microsoft.copilot.eclipse.ui.utils.AccessibilityUtils; import com.microsoft.copilot.eclipse.ui.utils.ModelUtils; import com.microsoft.copilot.eclipse.ui.utils.SwtUtils; @@ -25,6 +26,10 @@ * A custom widget that displays a turn for the copilot. */ public class CopilotTurnWidget extends ThinkingTurnWidget { + + private Composite compactingComposite; + private SpinnerAnimator compactingSpinner; + /** * Create the widget. */ @@ -106,6 +111,50 @@ public void renderModelInfo(String modelName, double billingMultiplier, String r } } + /** + * Shows a "Compacting conversation..." spinner below the last message in this turn. + * Must be called on the UI thread. + */ + public void showCompactingStatus() { + if (isDisposed() || compactingComposite != null) { + return; + } + compactingComposite = new Composite(this, SWT.NONE); + GridLayout layout = new GridLayout(2, false); + layout.marginWidth = 0; + layout.marginHeight = 4; + compactingComposite.setLayout(layout); + compactingComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + + Label spinnerLabel = new Label(compactingComposite, SWT.NONE); + spinnerLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); + compactingSpinner = new SpinnerAnimator(spinnerLabel); + compactingSpinner.start(); + + Label statusLabel = new Label(compactingComposite, SWT.NONE); + statusLabel.setText(Messages.chat_compacting_conversation); + statusLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false)); + + ensureFooterAtBottom(); + requestLayout(); + } + + /** + * Hides the "Compacting conversation..." spinner. + * Must be called on the UI thread. + */ + public void hideCompactingStatus() { + if (compactingSpinner != null) { + compactingSpinner.stop(); + compactingSpinner = null; + } + if (compactingComposite != null && !compactingComposite.isDisposed()) { + compactingComposite.dispose(); + compactingComposite = null; + } + requestLayout(); + } + @Override protected void createFooter() { footer = new Composite(this, SWT.NONE); diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/CurrentReferencedFile.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/CurrentReferencedFile.java index 46f22d4d..19a9dde2 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/CurrentReferencedFile.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/CurrentReferencedFile.java @@ -92,6 +92,12 @@ public void setFile(IResource file) { super.setFile(file); } + @Override + protected @Nullable String getAccessibilityName() { + IResource file = getFile(); + return file == null ? null : Messages.chat_currentReferencedFile_description + " " + file.getName(); + } + /** * Set the current selection to display. */ diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/FileAnnotationHyperlinkDetector.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/FileAnnotationHyperlinkDetector.java index eef5dc17..2a4b377b 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/FileAnnotationHyperlinkDetector.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/FileAnnotationHyperlinkDetector.java @@ -3,10 +3,13 @@ package com.microsoft.copilot.eclipse.ui.chat; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; + import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.Path; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.hyperlink.IHyperlink; import org.eclipse.jface.text.hyperlink.URLHyperlink; @@ -59,14 +62,27 @@ public void open() { String urlString = getURLString(); if (urlString.startsWith(LSPEclipseUtils.FILE_URI)) { IResource targetResource = LSPEclipseUtils.findResourceFor(urlString); - if (targetResource != null && targetResource.getType() == IResource.FILE) { - Location location = new Location(); - location.setUri(urlString); - LSPEclipseUtils.openInEditor(location); + if (targetResource != null) { + if (targetResource.getType() == IResource.FILE) { + Location location = new Location(); + location.setUri(urlString); + LSPEclipseUtils.openInEditor(location); + return; + } + if (targetResource.getType() == IResource.FOLDER + || targetResource.getType() == IResource.PROJECT) { + UiUtils.revealInExplorer(targetResource); + return; + } + } + Path localPath = FileUtils.getLocalFilePath(urlString); + if (localPath != null && Files.isRegularFile(localPath, LinkOption.NOFOLLOW_LINKS)) { + UiUtils.openLocalFileInEditor(localPath); return; } } else { - IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(urlString)); + IFile file = ResourcesPlugin.getWorkspace().getRoot() + .getFile(new org.eclipse.core.runtime.Path(urlString)); if (file.exists()) { var workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/InvokeToolConfirmationDialog.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/InvokeToolConfirmationDialog.java index 745f62a5..1f65aead 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/InvokeToolConfirmationDialog.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/InvokeToolConfirmationDialog.java @@ -3,6 +3,8 @@ package com.microsoft.copilot.eclipse.ui.chat; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; @@ -13,23 +15,34 @@ import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationAction; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationContent; import com.microsoft.copilot.eclipse.core.lsp.protocol.LanguageModelToolConfirmationResult; import com.microsoft.copilot.eclipse.core.lsp.protocol.LanguageModelToolConfirmationResult.ToolConfirmationResult; import com.microsoft.copilot.eclipse.ui.CopilotUi; import com.microsoft.copilot.eclipse.ui.swt.CssConstants; +import com.microsoft.copilot.eclipse.ui.swt.SplitDropdownButton; import com.microsoft.copilot.eclipse.ui.utils.SwtUtils; import com.microsoft.copilot.eclipse.ui.utils.UiUtils; /** - * Dialog to confirm tool execution. + * Dialog to confirm tool execution. Renders a title, message, optional command + * block, and action buttons driven by {@link ConfirmationContent}. The primary + * action is shown as a {@link SplitDropdownButton} with secondary actions in + * the dropdown menu. */ public class InvokeToolConfirmationDialog extends Composite { @@ -47,32 +60,74 @@ public class InvokeToolConfirmationDialog extends Composite { * The key for the action in the input map (used by debugger tool). */ private static final String ACTION_KEY = "action"; + private CompletableFuture toolConfirmationFuture; private String cancelMessage; private Label titleLbl; private Font boldFont; private Runnable titleFontChangeCallback; + private ConfirmationContent confirmationContent; + private ConfirmationAction selectedAction; /** - * Create a new confirmation dialog for tool execution. + * Create a new confirmation dialog driven by {@link ConfirmationContent}. * - * @param parent The parent composite - * @param title The title of the confirmation dialog - * @param message The message to display - * @param input The input object to pass to the tool + * @param parent the parent composite + * @param content confirmation content with title, message, and action buttons + * @param input the input object to pass to the tool */ - public InvokeToolConfirmationDialog(Composite parent, String title, String message, Object input) { + public InvokeToolConfirmationDialog(Composite parent, + ConfirmationContent content, Object input) { super(parent, SWT.BORDER | SWT.WRAP); this.setLayout(new GridLayout(1, false)); this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); - createDialogContent(title, message, input); + this.confirmationContent = content; + createDialogContent(content.getTitle(), content.getMessage(), input); this.toolConfirmationFuture = new CompletableFuture<>(); } - private void createDialogContent(String title, String message, Object input) { - // Title of the confirmation dialog + /** + * Returns the action the user selected, or {@code null} if dismissed. + */ + public ConfirmationAction getSelectedAction() { + return selectedAction; + } + + /** + * Get the future that will be completed when the user makes a choice. + * + * @return CompletableFuture containing the result of user's choice + */ + public CompletableFuture getConfirmationFuture() { + return toolConfirmationFuture; + } + + /** + * Cancels the current tool confirmation dialog programmatically. This has + * the same effect as clicking the Cancel / Skip button. + */ + public void cancelConfirmation() { + if (toolConfirmationFuture != null && !toolConfirmationFuture.isDone()) { + toolConfirmationFuture.complete( + new LanguageModelToolConfirmationResult(ToolConfirmationResult.DISMISS)); + + Composite parent = this.getParent(); + SwtUtils.invokeOnDisplayThreadAsync(() -> { + if (parent != null && !parent.isDisposed() + && StringUtils.isNotEmpty(this.cancelMessage)) { + new AgentToolCancelLabel(parent, SWT.NONE, this.cancelMessage); + } + disposeAndRequestParentLayout(); + }, this); + } + } + + // --------------- content creation --------------- + + private void createDialogContent(String title, String message, + Object input) { titleLbl = new Label(this, SWT.LEFT | SWT.WRAP); titleLbl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); titleLbl.setText(title); @@ -93,160 +148,181 @@ private void createDialogContent(String title, String message, Object input) { } }); - // Confirmation message of the confirmation dialog Label messageLbl = new Label(this, SWT.LEFT | SWT.WRAP); - GridData messageGridData = new GridData(SWT.FILL, SWT.FILL, true, false); - messageLbl.setLayoutData(messageGridData); - messageLbl.setText(message); + messageLbl.setLayoutData( + new GridData(SWT.FILL, SWT.FILL, true, false)); + messageLbl.setText(message != null ? message : ""); registerControlForFontUpdates(messageLbl); - // More information about the tool invocation - if (input != null) { - Map inputMap = (Map) input; - - // For debugger tool, show all input parameters - if (inputMap.containsKey(ACTION_KEY)) { - String displayText = formatDebuggerInput(inputMap); - - // Create a scrollable container for the input text - ScrolledComposite commandScroll = new ScrolledComposite(this, SWT.H_SCROLL | SWT.V_SCROLL); - commandScroll.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); - commandScroll.setExpandHorizontal(true); - commandScroll.setExpandVertical(true); - - Label commandLbl = new Label(commandScroll, SWT.LEFT); - // Escape & characters that are followed by non-space characters, needed for SWT labels where & is used as a - // mnemonic character - String escapedCommand = displayText.replace("&", "&&"); - commandLbl.setText(escapedCommand); - commandLbl.setData(CssConstants.CSS_CLASS_NAME_KEY, "bg-command-panel"); - this.cancelMessage = escapedCommand; - registerControlForFontUpdates(commandLbl); - - commandScroll.setContent(commandLbl); - commandScroll.addControlListener(new ControlAdapter() { - @Override - public void controlResized(ControlEvent e) { - Point size = commandLbl.computeSize(SWT.DEFAULT, SWT.DEFAULT); - commandLbl.setSize(size); - commandScroll.setMinSize(size); - } - }); - // Initial size computation - Point size = commandLbl.computeSize(SWT.DEFAULT, SWT.DEFAULT); - commandLbl.setSize(size); - commandScroll.setMinSize(size); - } else if (inputMap.containsKey(COMMAND_KEY)) { - // For terminal tool, show command - // Create a scrollable container for the command text - ScrolledComposite commandScroll = new ScrolledComposite(this, SWT.H_SCROLL); - commandScroll.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); - commandScroll.setExpandHorizontal(true); - commandScroll.setExpandVertical(true); - - Label commandLbl = new Label(commandScroll, SWT.LEFT); - String command = (String) inputMap.get(COMMAND_KEY); - // Escape & characters that are followed by non-space characters, needed for SWT labels where & is used as a - // mnemonic character - String escapedCommand = command.replace("&", "&&"); - commandLbl.setText(escapedCommand); - commandLbl.setData(CssConstants.CSS_CLASS_NAME_KEY, "bg-command-panel"); - this.cancelMessage = escapedCommand; - registerControlForFontUpdates(commandLbl); - - commandScroll.setContent(commandLbl); - commandScroll.addControlListener(new ControlAdapter() { - @Override - public void controlResized(ControlEvent e) { - Point size = commandLbl.computeSize(SWT.DEFAULT, SWT.DEFAULT); - commandLbl.setSize(size); - commandScroll.setMinSize(size); - } - }); - // Initial size computation + createInputContent(input); + createActionButtons(); + } + + @SuppressWarnings("unchecked") + private void createInputContent(Object input) { + if (input == null) { + return; + } + Map inputMap = (Map) input; + + if (inputMap.containsKey(ACTION_KEY)) { + createScrollableCommand(formatDebuggerInput(inputMap), + SWT.H_SCROLL | SWT.V_SCROLL); + } else if (inputMap.containsKey(COMMAND_KEY)) { + createScrollableCommand((String) inputMap.get(COMMAND_KEY), + SWT.H_SCROLL); + } + + if (inputMap.containsKey(EXPLANATION_KEY)) { + Label explanationLbl = new Label(this, SWT.LEFT | SWT.WRAP); + explanationLbl.setLayoutData( + new GridData(SWT.FILL, SWT.FILL, true, false)); + explanationLbl.setText((String) inputMap.get(EXPLANATION_KEY)); + registerControlForFontUpdates(explanationLbl); + } + } + + private void createScrollableCommand(String text, int scrollStyle) { + ScrolledComposite commandScroll = + new ScrolledComposite(this, scrollStyle); + commandScroll.setLayoutData( + new GridData(SWT.FILL, SWT.FILL, true, false)); + commandScroll.setExpandHorizontal(true); + commandScroll.setExpandVertical(true); + + Label commandLbl = new Label(commandScroll, SWT.LEFT); + String escapedCommand = text.replace("&", "&&"); + commandLbl.setText(escapedCommand); + commandLbl.setData(CssConstants.CSS_CLASS_NAME_KEY, "bg-command-panel"); + this.cancelMessage = escapedCommand; + registerControlForFontUpdates(commandLbl); + + commandScroll.setContent(commandLbl); + commandScroll.addControlListener(new ControlAdapter() { + @Override + public void controlResized(ControlEvent e) { Point size = commandLbl.computeSize(SWT.DEFAULT, SWT.DEFAULT); commandLbl.setSize(size); commandScroll.setMinSize(size); } + }); + Point size = commandLbl.computeSize(SWT.DEFAULT, SWT.DEFAULT); + commandLbl.setSize(size); + commandScroll.setMinSize(size); + } + + // --------------- action buttons with dropdown --------------- + + private void createActionButtons() { + List actions = confirmationContent.getActions(); - if (inputMap.containsKey(EXPLANATION_KEY)) { - Label explanationLbl = new Label(this, SWT.LEFT | SWT.WRAP); - explanationLbl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); - explanationLbl.setText((String) inputMap.get(EXPLANATION_KEY)); - registerControlForFontUpdates(explanationLbl); + ConfirmationAction primaryAction = null; + ConfirmationAction dismissAction = null; + List dropdownActions = new ArrayList<>(); + + for (ConfirmationAction action : actions) { + if (!action.isAccept()) { + dismissAction = action; + } else if (action.isPrimary()) { + primaryAction = action; + } else { + dropdownActions.add(action); } } - createButtons(); - } + if (primaryAction == null) { + return; + } - private void createButtons() { - GridLayout actionLayout = new GridLayout(2, false); - actionLayout.marginLeft = 0; - actionLayout.marginRight = 0; - actionLayout.marginWidth = 0; - actionLayout.horizontalSpacing = 0; - actionLayout.marginHeight = 0; - Composite actionArea = new Composite(this, SWT.NONE); - actionArea.setLayout(actionLayout); - actionArea.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - - Button continueButton = new Button(actionArea, SWT.PUSH); - continueButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false)); - continueButton.setText("Continue"); - continueButton.addListener(SWT.Selection, e -> { - this.toolConfirmationFuture.complete(new LanguageModelToolConfirmationResult(ToolConfirmationResult.ACCEPT)); - - // Store parent reference before disposal - Composite parent = this.getParent(); - this.dispose(); - // Check if parent is still valid before using it - if (parent != null && !parent.isDisposed()) { - parent.layout(); + // Column count: primary dropdown button + dismiss + Composite actionArea = newButtonArea(2); + + // --- primary dropdown button --- + SplitDropdownButton primaryDropdown = + new SplitDropdownButton(actionArea, SWT.PUSH); + primaryDropdown.setText(primaryAction.getLabel()); + primaryDropdown.setShowArrow(!dropdownActions.isEmpty()); + primaryDropdown.setSeparatorColor( + getDisplay().getSystemColor(SWT.COLOR_WHITE)); + + Button primaryBtn = primaryDropdown.getButton(); + primaryBtn.setData(CssConstants.CSS_CLASS_NAME_KEY, "btn-primary"); + primaryBtn.setLayoutData( + new GridData(SWT.BEGINNING, SWT.CENTER, false, false)); + registerControlForFontUpdates(primaryBtn); + + final ConfirmationAction primaryRef = primaryAction; + primaryDropdown.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (e.detail == SWT.ARROW && !dropdownActions.isEmpty()) { + Menu menu = new Menu(primaryBtn.getShell(), SWT.POP_UP); + for (ConfirmationAction action : dropdownActions) { + MenuItem item = new MenuItem(menu, SWT.PUSH); + item.setText(action.getLabel()); + item.addListener(SWT.Selection, + ev -> acceptAndDispose(action)); + } + menu.addListener(SWT.Hide, ev -> { + ev.display.asyncExec(menu::dispose); + }); + Rectangle bounds = primaryBtn.getBounds(); + Point loc = primaryBtn.getParent() + .toDisplay(bounds.x, bounds.y + bounds.height); + menu.setLocation(loc); + menu.setVisible(true); + } else { + acceptAndDispose(primaryRef); + } } }); - continueButton.setData(CssConstants.CSS_CLASS_NAME_KEY, "btn-primary"); - registerControlForFontUpdates(continueButton); - Button cancelButton = new Button(actionArea, SWT.PUSH); - cancelButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false)); - cancelButton.setText("Cancel"); - cancelButton.addListener(SWT.Selection, e -> { + // --- dismiss (skip) button --- + Button dismissBtn = new Button(actionArea, SWT.PUSH); + dismissBtn.setLayoutData( + new GridData(SWT.BEGINNING, SWT.CENTER, false, false)); + dismissBtn.setText( + dismissAction != null ? dismissAction.getLabel() + : Messages.confirmation_action_skip); + registerControlForFontUpdates(dismissBtn); + + final ConfirmationAction dismissRef = dismissAction; + dismissBtn.addListener(SWT.Selection, e -> { + this.selectedAction = dismissRef; cancelConfirmation(); }); - registerControlForFontUpdates(cancelButton); } - /** - * Get the future that will be completed when the user makes a choice. - * - * @return CompletableFuture containing the result of user's choice - */ - public CompletableFuture getConfirmationFuture() { - return toolConfirmationFuture; + // --------------- helpers --------------- + + private Composite newButtonArea(int columns) { + GridLayout layout = new GridLayout(columns, false); + layout.marginLeft = 0; + layout.marginRight = 0; + layout.marginWidth = 0; + layout.horizontalSpacing = 0; + layout.marginHeight = 0; + + Composite area = new Composite(this, SWT.NONE); + area.setLayout(layout); + area.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + return area; } - /** - * Cancels the current tool confirmation dialog programmatically. This has the same effect as clicking the Cancel - * button in the confirmation dialog. - */ - public void cancelConfirmation() { - if (toolConfirmationFuture != null && !toolConfirmationFuture.isDone()) { - toolConfirmationFuture.complete(new LanguageModelToolConfirmationResult(ToolConfirmationResult.DISMISS)); + private void acceptAndDispose(ConfirmationAction action) { + this.selectedAction = action; + this.toolConfirmationFuture.complete( + new LanguageModelToolConfirmationResult( + ToolConfirmationResult.ACCEPT)); - // Store parent reference before disposal - Composite parent = this.getParent(); - SwtUtils.invokeOnDisplayThread(() -> { - // Only show the cancel widget for special cases when the tool has a parameter "command" in the input map - if (StringUtils.isNotEmpty(this.cancelMessage)) { - new AgentToolCancelLabel(this.getParent(), SWT.NONE, this.cancelMessage); - } - this.dispose(); - // Check if parent is still valid before using it - if (parent != null && !parent.isDisposed()) { - parent.layout(); - } - }, this); + disposeAndRequestParentLayout(); + } + + private void disposeAndRequestParentLayout() { + Composite parent = this.getParent(); + this.dispose(); + if (parent != null && !parent.isDisposed()) { + parent.requestLayout(); } } diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/Messages.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/Messages.java index 9c905913..f1a06d18 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/Messages.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/Messages.java @@ -41,6 +41,39 @@ public final class Messages extends NLS { public static String thinking_expandTooltip; public static String thinking_collapseTooltip; + // Confirmation dialog action labels + public static String confirmation_action_allowOnce; + public static String confirmation_action_skip; + public static String confirmation_action_allowAllCommands; + public static String confirmation_action_allowNamesSession; + public static String confirmation_action_alwaysAllowNames; + public static String confirmation_action_allowExactSession; + public static String confirmation_action_alwaysAllowExact; + public static String confirmation_action_alwaysAllow; + public static String confirmation_action_allowFileSession; + public static String confirmation_action_allowFolderSession; + + // MCP confirmation dialog action labels + public static String confirmation_title_mcpTool; + public static String confirmation_title_mcpToolDefault; + public static String confirmation_action_allowServerSession; + public static String confirmation_action_alwaysAllowServer; + + // Confirmation dialog titles + public static String confirmation_title_terminal; + public static String confirmation_title_fallback; + public static String confirmation_title_fileRead; + public static String confirmation_title_fileWrite; + public static String confirmation_title_fileOperation; + + // Confirmation dialog messages + public static String confirmation_message_fileRead; + public static String confirmation_message_fileWrite; + public static String confirmation_message_fileOperation; + + // Misc + public static String confirmation_autoApprovedDescription; + static { // initialize resource bundle NLS.initializeMessages(BUNDLE_NAME, Messages.class); diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ModelPickerGroupsBuilder.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ModelPickerGroupsBuilder.java index fb838528..46a245ee 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ModelPickerGroupsBuilder.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ModelPickerGroupsBuilder.java @@ -66,7 +66,7 @@ public static List build(Map modelMap, List customModels = new ArrayList<>(); for (CopilotModel model : modelMap.values()) { - if (model.getProviderName() != null) { + if (model.getProviderName() != null || model.getCustomModel() != null) { customModels.add(model); } else if (model.getBilling() != null) { if (model.getBilling().isPremium()) { diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ReferencedFile.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ReferencedFile.java index 8c9faf9d..e1bf9b25 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ReferencedFile.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ReferencedFile.java @@ -9,6 +9,8 @@ import org.eclipse.e4.ui.css.swt.CSSSWTConstants; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.swt.SWT; +import org.eclipse.swt.accessibility.AccessibleAdapter; +import org.eclipse.swt.accessibility.AccessibleEvent; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.MouseAdapter; @@ -19,6 +21,7 @@ import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowData; import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; @@ -100,6 +103,7 @@ public void keyPressed(KeyEvent e) { }); AccessibilityUtils.addFocusBorderToComposite(this); + addAccessibilityName(this); } /** @@ -166,10 +170,33 @@ protected void setFile(@Nullable IResource file) { setLayoutData(layoutData); ChatView chatView = UiUtils.getView(Constants.CHAT_VIEW_ID, ChatView.class); if (chatView != null) { - chatView.layout(true, true); + // Pass every child whose content setFile()/setupXDisplay() can touch (icon image, file name + // text/CSS class, close button image) -- not just this composite or a single child. SWT's + // targeted requestLayout() only flushes cached sizes for the exact controls it's given (plus + // their ancestor chains up to cmpFileRef and beyond); passing a subset silently leaves the + // others' cached sizes stale (previously: a clipped icon, and before that a chip that didn't + // shrink). Since all three are descendants of this composite, their ancestor walk-up already + // covers this chip's own RowData/visibility change too -- no need to pass `this` separately. + chatView.requestLayout(lblfileIcon, lblFileName, lblClose); } } + /** + * Returns the accessible name for this referenced file widget. + */ + protected @Nullable String getAccessibilityName() { + return file == null ? null : file.getName(); + } + + private void addAccessibilityName(Control control) { + control.getAccessible().addAccessibleListener(new AccessibleAdapter() { + @Override + public void getName(AccessibleEvent event) { + event.result = getAccessibilityName(); + } + }); + } + /** * Setup display for unsupported files (e.g., images without vision support). */ diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/SourceViewerComposite.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/SourceViewerComposite.java index b661f77b..b1e737a8 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/SourceViewerComposite.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/SourceViewerComposite.java @@ -213,6 +213,24 @@ private Button createActionButton(Composite parent, int style, Image image, Stri return result; } + @Override + public Point computeSize(int widthHint, int heightHint, boolean changed) { + if (this.sourceViewer == null) { + return super.computeSize(widthHint, heightHint, changed); + } + + StyledText textWidget = this.sourceViewer.getTextWidget(); + if (textWidget == null || textWidget.isDisposed()) { + return super.computeSize(widthHint, heightHint, changed); + } + + Point textSize = textWidget.computeSize(widthHint, SWT.DEFAULT, changed); + Rectangle trim = computeTrim(0, 0, textSize.x, getSourceViewerHeight(textWidget, textSize)); + int width = widthHint == SWT.DEFAULT ? trim.width : widthHint; + int height = heightHint == SWT.DEFAULT ? trim.height : heightHint; + return new Point(Math.max(0, width), Math.max(0, height)); + } + private void refreshScrollerLayout() { if (this.sourceViewer == null) { return; @@ -224,16 +242,20 @@ private void refreshScrollerLayout() { } Point size = textWidget.computeSize(SWT.DEFAULT, SWT.DEFAULT); Rectangle clientArea = this.getClientArea(); - // remove scroll-bar height - ScrollBar horizontalBar = textWidget.getHorizontalBar(); - int scrollbarHeight = horizontalBar != null ? horizontalBar.getSize().y : 0; - int height = size.y - scrollbarHeight; + int height = getSourceViewerHeight(textWidget, size); // Set bounds on SourceViewer's control (the direct child), not just the textWidget this.sourceViewer.getControl().setBounds(0, 0, clientArea.width, height); textWidget.redraw(); }); } + private int getSourceViewerHeight(StyledText textWidget, Point textSize) { + // remove scroll-bar height + ScrollBar horizontalBar = textWidget.getHorizontalBar(); + int scrollbarHeight = horizontalBar != null ? horizontalBar.getSize().y : 0; + return Math.max(0, textSize.y - scrollbarHeight); + } + private void insert(Event e) { String content = this.sourceViewer.getDocument().get(); if (StringUtils.isNotEmpty(content)) { diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/SubagentMessageBlock.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/SubagentMessageBlock.java index 45edd8cb..e7dcf908 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/SubagentMessageBlock.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/SubagentMessageBlock.java @@ -91,9 +91,9 @@ public void appendToolCallStatus(AgentToolCall toolCall) { /** * Notify the end of the subagent turn. */ - public void notifyTurnEnd() { + public void flushMessageBuffer() { if (currentSubagentTurnWidget != null) { - currentSubagentTurnWidget.notifyTurnEnd(); + currentSubagentTurnWidget.flushMessageBuffer(); } } diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ThinkingBlock.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ThinkingBlock.java index 8e974b9e..e273986f 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ThinkingBlock.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/ThinkingBlock.java @@ -315,7 +315,6 @@ private void refreshBody() { body.requestLayout(); updateScrollerDuringStreaming(); - refreshEnclosingScroller(); } /** Resize the scroller to fit content (up to max height) and auto-scroll to bottom if enabled. */ @@ -499,7 +498,7 @@ private void refreshEnclosingScroller() { Composite p = getParent(); while (p != null && !p.isDisposed()) { if (p instanceof ChatContentViewer) { - ((ChatContentViewer) p).refreshScrollerLayout(); + ((ChatContentViewer) p).refreshLayoutFull(); return; } p = p.getParent(); diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/WorkingSetBar.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/WorkingSetBar.java index cc6a8a5a..1c0780a6 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/WorkingSetBar.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/WorkingSetBar.java @@ -7,7 +7,6 @@ import java.util.List; import java.util.Map; -import org.eclipse.core.resources.IFile; import org.eclipse.e4.ui.services.IStylingEngine; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; @@ -31,6 +30,7 @@ import com.microsoft.copilot.eclipse.ui.CopilotUi; import com.microsoft.copilot.eclipse.ui.chat.services.ChatFontService; +import com.microsoft.copilot.eclipse.ui.chat.tools.ChangedFile; import com.microsoft.copilot.eclipse.ui.chat.tools.FileToolService; import com.microsoft.copilot.eclipse.ui.chat.tools.FileToolService.FileChangeProperty; import com.microsoft.copilot.eclipse.ui.swt.CssConstants; @@ -70,7 +70,7 @@ public WorkingSetBar(Composite parent, int style) { * * @param filesMap a map of files and their change status */ - public void buildSummaryBarFor(Map filesMap) { + public void buildSummaryBarFor(Map filesMap) { if (filesMap == null || isDisposed()) { return; } @@ -167,7 +167,7 @@ class WorkingSetTitleBar extends Composite { private Button undoButton; private String changeFilesTitle; - public WorkingSetTitleBar(Composite parent, int style, Map filesMap) { + public WorkingSetTitleBar(Composite parent, int style, Map filesMap) { super(parent, style); GridLayout gl = new GridLayout(3, false); gl.marginWidth = 0; @@ -302,9 +302,10 @@ class ChangedFiles extends Composite { private static final int MAX_VISIBLE_FILES = 5; private final Composite contentArea; private final ScrolledComposite scrolledComposite; + private final WorkbenchLabelProvider labelProvider = new WorkbenchLabelProvider(); private List fileRows; // List to keep track of file rows - public ChangedFiles(Composite parent, int style, Map filesMap) { + public ChangedFiles(Composite parent, int style, Map filesMap) { super(parent, style); // Main layout @@ -313,6 +314,7 @@ public ChangedFiles(Composite parent, int style, Map layout.marginHeight = 0; setLayout(layout); setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + addDisposeListener(e -> labelProvider.dispose()); // Count files long fileCount = filesMap.size(); @@ -345,15 +347,14 @@ public ChangedFiles(Composite parent, int style, Map contentArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); } - // TODO: Should share a same instance with ReferencedFile - WorkbenchLabelProvider labelProvider = new WorkbenchLabelProvider(); fileRows = new LinkedList<>(); - for (IFile file : filesMap.keySet()) { + for (ChangedFile file : filesMap.keySet()) { if (file == null) { continue; } - Image image = labelProvider.getImage(file); + Image image = file.isWorkspaceFile() ? labelProvider.getImage(file.getWorkspaceFile()) + : PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE); fileRows.add(new FileRow(contentArea, SWT.NONE, image, file)); } @@ -396,7 +397,7 @@ public class FileRow extends Composite { /** * Constructs a new FileRow. */ - public FileRow(Composite parent, int style, Image fileImage, IFile file) { + public FileRow(Composite parent, int style, Image fileImage, ChangedFile file) { super(parent, style); GridLayout layout = new GridLayout(2, false); @@ -434,7 +435,7 @@ public void mouseUp(MouseEvent e) { // File name (bold) Label nameLabel = new Label(fileInfo, SWT.NONE); nameLabel.setText(file.getName()); - nameLabel.setToolTipText(file.getFullPath().toString()); + nameLabel.setToolTipText(file.getDisplayPath()); nameLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false)); nameLabel.addMouseListener(new MouseAdapter() { @Override @@ -466,7 +467,7 @@ public void mouseUp(MouseEvent e) { // File path CLabel pathLabel = new CLabel(fileInfo, SWT.NONE); - pathLabel.setText(file.getFullPath().toString()); + pathLabel.setText(file.getDisplayPath()); pathLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, true, false)); pathLabel.addMouseListener(new MouseAdapter() { @Override diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/AttachedFileRegistry.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/AttachedFileRegistry.java new file mode 100644 index 00000000..bb548c77 --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/AttachedFileRegistry.java @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.chat.confirmation; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; + +/** + * Tracks files explicitly attached by the user in the context panel. + * + *

New files are first stored in a {@code pending} set (not yet bound + * to any conversation ID). The confirmation handler checks pending files + * first, so auto-approve works even before the real conversation ID + * arrives from CLS. Once the real ID is known, call + * {@link #flushPending(String)} to move them into per-conversation + * storage. + */ +public class AttachedFileRegistry { + + private final Map> attachedPaths = + Collections.synchronizedMap(new LinkedHashMap<>()); + + /** Files waiting for a stable conversation ID. */ + private final Set pendingFiles = + Collections.synchronizedSet(new HashSet<>()); + + /** + * Stages file paths for auto-approve before the conversation ID is + * known. These are checked by {@link #isAttachedFile} immediately. + */ + public void addPending(Collection filePaths) { + if (filePaths == null || filePaths.isEmpty()) { + return; + } + filePaths.stream() + .filter(StringUtils::isNotBlank) + .map(AttachedFileRegistry::toComparisonKey) + .forEach(pendingFiles::add); + } + + /** + * Moves pending files into per-conversation storage under the given + * conversation ID, then clears the pending set. + */ + public void flushPending(String conversationId) { + if (StringUtils.isBlank(conversationId) || pendingFiles.isEmpty()) { + return; + } + Set flushed; + synchronized (pendingFiles) { + flushed = new HashSet<>(pendingFiles); + pendingFiles.clear(); + } + evictOldestIfNeeded(); + synchronized (attachedPaths) { + attachedPaths.merge(conversationId, flushed, (a, b) -> { + Set merged = new HashSet<>(a); + merged.addAll(b); + return merged; + }); + } + } + + /** + * Records files for an existing conversation (continued turns). + */ + public void addAttachedFiles(String conversationId, + Collection filePaths) { + if (filePaths == null || filePaths.isEmpty() + || StringUtils.isBlank(conversationId)) { + return; + } + Set keys = filePaths.stream() + .filter(StringUtils::isNotBlank) + .map(AttachedFileRegistry::toComparisonKey) + .collect(Collectors.toSet()); + if (keys.isEmpty()) { + return; + } + evictOldestIfNeeded(); + synchronized (attachedPaths) { + attachedPaths.merge(conversationId, keys, (a, b) -> { + Set merged = new HashSet<>(a); + merged.addAll(b); + return merged; + }); + } + } + + /** + * Returns {@code true} when the given file was explicitly attached + * by the user — either in the pending set or for the given conversation. + */ + public boolean isAttachedFile(String conversationId, String filePath) { + if (StringUtils.isBlank(filePath)) { + return false; + } + String key = toComparisonKey(filePath); + // Check pending files first (before conversation ID is known) + if (pendingFiles.contains(key)) { + return true; + } + Set paths = attachedPaths.get(conversationId); + return paths != null && paths.contains(key); + } + + /** Removes all tracked data for a conversation. */ + public void clearConversation(String conversationId) { + attachedPaths.remove(conversationId); + } + + /** Discards any pending (pre-conversation) files. */ + public void clearPending() { + pendingFiles.clear(); + } + + private void evictOldestIfNeeded() { + synchronized (attachedPaths) { + while (attachedPaths.size() >= ConfirmationHandler.MAX_SESSION_CONVERSATIONS) { + var it = attachedPaths.entrySet().iterator(); + if (it.hasNext()) { + it.next(); + it.remove(); + } + } + } + } + + private static String toComparisonKey(String path) { + return ConfirmationHandler.normalizePath(path); + } +} diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/ConfirmationHandler.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/ConfirmationHandler.java new file mode 100644 index 00000000..3e1e2e1a --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/ConfirmationHandler.java @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.chat.confirmation; + +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; + +import com.microsoft.copilot.eclipse.core.chat.ConfirmationAction; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationResult; +import com.microsoft.copilot.eclipse.core.lsp.protocol.InvokeClientToolConfirmationParams; + +/** + * Evaluates whether a tool confirmation request can be auto-approved. + * Each implementation handles a specific category of tool (terminal, file operations, MCP, etc.). + */ +public interface ConfirmationHandler { + + /** Maximum number of conversations tracked in session memory. */ + int MAX_SESSION_CONVERSATIONS = 50; + + /** + * Normalizes a file path for case-insensitive, separator-agnostic comparison. + * Converts backslashes to forward slashes and lowercases the result. + * + * @param path the file path to normalize + * @return the normalized path + */ + static String normalizePath(String path) { + return path.replace('\\', '/').toLowerCase(Locale.ROOT); + } + + /** + * Extracts the {@code toolType} string from the input map of a confirmation request. + * Returns {@code null} if the field is absent or not a string. + * + * @param params the confirmation request parameters from CLS + * @return the toolType value, or {@code null} + */ + static String extractToolType(InvokeClientToolConfirmationParams params) { + Object input = params.getInput(); + if (input instanceof Map inputMap) { + Object toolType = inputMap.get("toolType"); + if (toolType instanceof String) { + return (String) toolType; + } + } + return null; + } + + /** + * Evaluates whether the given confirmation request should be auto-approved, + * taking into account whether the auto-approval feature is enabled by token/policy. + * + * @param params the confirmation request parameters from CLS + * @param sessionConversationId the conversation ID to use for session-scoped + * lookups (may differ from params.getConversationId() when called from a + * subagent context) + * @param isAutoApprovalEnabled whether the auto-approval feature is currently enabled + * @return the confirmation result + */ + ConfirmationResult evaluate(InvokeClientToolConfirmationParams params, + String sessionConversationId, boolean isAutoApprovalEnabled); + + /** + * Caches a user's decision based on the action scope. + * SESSION actions are stored in-memory per conversation; + * GLOBAL actions are written to preferences. + * + * @param action the user's selected action with metadata + * @param params the original confirmation params (for command data etc.) + * @param sessionConversationId the conversation ID to use for session storage + */ + default void cacheDecision(ConfirmationAction action, + InvokeClientToolConfirmationParams params, + String sessionConversationId) { + // no-op by default + } + + /** Clears session-scoped approvals for the given conversation. */ + default void clearSession(String conversationId) { + // no-op by default + } + + /** + * Evicts the oldest entry from a {@link java.util.LinkedHashMap}-backed map when it reaches + * {@link #MAX_SESSION_CONVERSATIONS}. Thread-safe via {@code synchronized(map)}. + * + * @param value type + * @param map the map to evict from (must be a {@code Collections.synchronizedMap} wrapping a + * {@code LinkedHashMap} for correct eviction order) + */ + static void evictOldestIfNeeded(Map map) { + synchronized (map) { + while (map.size() >= MAX_SESSION_CONVERSATIONS) { + Entry oldest = map.entrySet().iterator().next(); + map.remove(oldest.getKey()); + } + } + } +} diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/ConfirmationService.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/ConfirmationService.java new file mode 100644 index 00000000..50242adc --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/ConfirmationService.java @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.chat.confirmation; + +import java.util.EnumMap; +import java.util.Map; + +import org.eclipse.jface.preference.IPreferenceStore; + +import com.microsoft.copilot.eclipse.core.Constants; +import com.microsoft.copilot.eclipse.core.CopilotCore; +import com.microsoft.copilot.eclipse.core.FeatureFlags; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationAction; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationActionScope; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationResult; +import com.microsoft.copilot.eclipse.core.lsp.protocol.InvokeClientToolConfirmationParams; + +/** + * Central entry point for auto-approve evaluation. Classifies each tool confirmation request + * into a category using the toolType field provided by CLS, then dispatches to the registered + * handler for that category. All session/global persist logic lives in each handler. + */ +public class ConfirmationService { + + /** Tool functional types matching CLS ToolFunctionalType enum values. */ + public enum ToolCategory { + TERMINAL("terminal"), + FILE_READ("file_read"), + FILE_WRITE("file_write"), + FILE_OPERATION("file_operation"), + MCP_TOOL("mcp_tool"), + SAFE_TOOL("safe_tool"), + WEB("web"), + UNKNOWN("unknown"); + + private final String value; + + ToolCategory(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + /** + * Resolves a CLS toolType string to a ToolCategory. + */ + public static ToolCategory fromValue(String value) { + if (value != null) { + for (ToolCategory category : values()) { + if (category.value.equals(value)) { + return category; + } + } + } + return UNKNOWN; + } + } + + private final Map handlers = + new EnumMap<>(ToolCategory.class); + private final ConfirmationHandler fallbackHandler = + new FallbackConfirmationHandler(); + private final IPreferenceStore preferenceStore; + + /** + * Creates a new ConfirmationService. + * + * @param preferenceStore the preference store for reading auto-approve settings + * @param attachedFileRegistry registry of user-attached context files + */ + public ConfirmationService(IPreferenceStore preferenceStore, + AttachedFileRegistry attachedFileRegistry) { + this.preferenceStore = preferenceStore; + handlers.put(ToolCategory.TERMINAL, + new TerminalConfirmationHandler(preferenceStore)); + FileOperationConfirmationHandler fileHandler = + new FileOperationConfirmationHandler(preferenceStore, + attachedFileRegistry); + handlers.put(ToolCategory.FILE_READ, fileHandler); + handlers.put(ToolCategory.FILE_WRITE, fileHandler); + handlers.put(ToolCategory.FILE_OPERATION, fileHandler); + handlers.put(ToolCategory.MCP_TOOL, + new McpConfirmationHandler(preferenceStore)); + } + + /** + * Evaluates whether a tool confirmation request should be auto-approved. + * + *

When the auto-approval feature is disabled by token or organization policy, all + * auto-approve rules (YOLO, session, global) are bypassed and the user is always prompted + * with a simple Allow-Once / Skip dialog. + * + * @param params the confirmation request parameters + * @param sessionConversationId the conversation ID for session-scoped lookups + */ + public ConfirmationResult evaluate( + InvokeClientToolConfirmationParams params, + String sessionConversationId) { + FeatureFlags flags = CopilotCore.getPlugin().getFeatureFlags(); + boolean autoApprovalEnabled = flags == null || flags.isAutoApprovalEnabled(); + + if (autoApprovalEnabled && preferenceStore.getBoolean(Constants.AUTO_APPROVE_YOLO_MODE)) { + return ConfirmationResult.AUTO_APPROVED; + } + + ToolCategory category = classify(params); + if (category == ToolCategory.SAFE_TOOL) { + return ConfirmationResult.AUTO_APPROVED; + } + + ConfirmationHandler handler = handlers.getOrDefault(category, fallbackHandler); + return handler.evaluate(params, sessionConversationId, autoApprovalEnabled); + } + + /** + * Caches the user's decision for future auto-approve lookups. + * + * @param action the user's selected action + * @param params the original confirmation params + * @param sessionConversationId the conversation ID for session storage + */ + public void cacheDecision(ConfirmationAction action, + InvokeClientToolConfirmationParams params, + String sessionConversationId) { + if (action == null || action.getScope() == null + || action.getScope() == ConfirmationActionScope.ONCE) { + return; + } + ToolCategory category = classify(params); + ConfirmationHandler handler = handlers.get(category); + if (handler != null) { + handler.cacheDecision(action, params, sessionConversationId); + } + } + + /** Clears session-scoped approvals for a conversation across all handlers. */ + public void clearSession(String conversationId) { + for (ConfirmationHandler handler : handlers.values()) { + handler.clearSession(conversationId); + } + } + + ToolCategory classify(InvokeClientToolConfirmationParams params) { + return ToolCategory.fromValue(ConfirmationHandler.extractToolType(params)); + } + +} diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/FallbackConfirmationHandler.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/FallbackConfirmationHandler.java new file mode 100644 index 00000000..d58c77e7 --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/FallbackConfirmationHandler.java @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.chat.confirmation; + +import java.util.List; + +import org.eclipse.osgi.util.NLS; + +import com.microsoft.copilot.eclipse.core.chat.ConfirmationAction; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationContent; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationResult; +import com.microsoft.copilot.eclipse.core.lsp.protocol.InvokeClientToolConfirmationParams; +import com.microsoft.copilot.eclipse.ui.chat.Messages; + +/** + * Catch-all handler for tool types that have no dedicated handler registered. + * Always shows a simple confirmation dialog with Allow Once / Skip. + */ +public class FallbackConfirmationHandler implements ConfirmationHandler { + + @Override + public ConfirmationResult evaluate( + InvokeClientToolConfirmationParams params, + String sessionConversationId, boolean isAutoApprovalEnabled) { + String title = params.getTitle() != null + ? params.getTitle() + : NLS.bind(Messages.confirmation_title_fallback, params.getName()); + return ConfirmationResult.needsConfirmation( + new ConfirmationContent(title, params.getMessage(), + List.of( + ConfirmationAction.allowOnce( + Messages.confirmation_action_allowOnce), + ConfirmationAction.skip( + Messages.confirmation_action_skip)))); + } +} diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/FileOperationConfirmationHandler.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/FileOperationConfirmationHandler.java new file mode 100644 index 00000000..ba861ed4 --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/FileOperationConfirmationHandler.java @@ -0,0 +1,504 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.chat.confirmation; + +import java.lang.reflect.Type; +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.nio.file.PathMatcher; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import org.apache.commons.lang3.StringUtils; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.osgi.util.NLS; + +import com.microsoft.copilot.eclipse.core.Constants; +import com.microsoft.copilot.eclipse.core.CopilotCore; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationAction; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationActionScope; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationContent; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationResult; +import com.microsoft.copilot.eclipse.core.chat.FileOperationAutoApproveRule; +import com.microsoft.copilot.eclipse.core.chat.service.IChatServiceManager; +import com.microsoft.copilot.eclipse.core.chat.service.ICustomizationFileService; +import com.microsoft.copilot.eclipse.core.lsp.protocol.InvokeClientToolConfirmationParams; +import com.microsoft.copilot.eclipse.core.lsp.protocol.ToolMetadata; +import com.microsoft.copilot.eclipse.core.utils.FileUtils; +import com.microsoft.copilot.eclipse.ui.chat.Messages; + +/** + * Evaluates file-operation confirmation requests against user-configured glob pattern rules. + * Files outside the workspace always require confirmation. + */ +public class FileOperationConfirmationHandler implements ConfirmationHandler { + + /** Action types for edit confirmation. */ + public enum Action { + /** Allow this specific file for the rest of the session. */ + ACCEPT_FILE_SESSION, + /** Always allow this specific file (persisted globally). */ + ACCEPT_FILE_GLOBAL, + /** Allow all files under this folder for the session. */ + ACCEPT_FOLDER_SESSION + } + + /** File tool type matching CLS values. */ + enum FileToolType { + FILE_READ("file_read"), + FILE_WRITE("file_write"), + FILE_OPERATION("file_operation"); + + private final String value; + + FileToolType(String value) { + this.value = value; + } + + String getDefaultTitle() { + switch (this) { + case FILE_READ: + return Messages.confirmation_title_fileRead; + case FILE_WRITE: + return Messages.confirmation_title_fileWrite; + default: + return Messages.confirmation_title_fileOperation; + } + } + + String getMessageTemplate() { + switch (this) { + case FILE_READ: + return Messages.confirmation_message_fileRead; + case FILE_WRITE: + return Messages.confirmation_message_fileWrite; + default: + return Messages.confirmation_message_fileOperation; + } + } + + static FileToolType fromValue(String value) { + if (value != null) { + for (FileToolType t : values()) { + if (t.value.equals(value)) { + return t; + } + } + } + return FILE_OPERATION; + } + } + + static final String META_FILE_PATH = "filePath"; + static final String META_FOLDER_PATH = "folderPath"; + + /** + * Local fallback defaults matching CLS + * {@code FileSafetyRulesService.defaultRules}. + * Used when CLS is not yet available. + */ + public static final List FALLBACK_DEFAULT_RULES = List.of( + new FileOperationAutoApproveRule("**/.github/instructions/*", + "GitHub instructions files", false, true), + new FileOperationAutoApproveRule("**/github-copilot/**/*", + "GitHub Copilot settings and token files", false, true)); + + private static final Type RULES_TYPE = + new TypeToken>() { + }.getType(); + + private final IPreferenceStore preferenceStore; + private final AttachedFileRegistry attachedFileRegistry; + private final Map> sessionApprovedFiles = + Collections.synchronizedMap(new LinkedHashMap<>()); + private final Map> sessionApprovedFolders = + Collections.synchronizedMap(new LinkedHashMap<>()); + + /** + * Creates a new FileOperationConfirmationHandler. + * + * @param preferenceStore the preference store for reading file-operation auto-approve rules + * @param attachedFileRegistry registry of user-attached files for auto-approval + */ + public FileOperationConfirmationHandler(IPreferenceStore preferenceStore, + AttachedFileRegistry attachedFileRegistry) { + this.preferenceStore = preferenceStore; + this.attachedFileRegistry = attachedFileRegistry; + } + + @Override + public ConfirmationResult evaluate(InvokeClientToolConfirmationParams params, + String sessionConversationId, boolean isAutoApprovalEnabled) { + if (!isAutoApprovalEnabled) { + return evaluateAutoApprovalDisabled(params, sessionConversationId); + } + return evaluateAutoApprovalEnabled(params, sessionConversationId); + } + + private ConfirmationResult evaluateAutoApprovalEnabled( + InvokeClientToolConfirmationParams params, + String sessionConversationId) { + String filePath = extractFilePath(params); + if (StringUtils.isBlank(filePath)) { + return ConfirmationResult.DISMISSED; + } + + // Auto-approve files explicitly attached by the user in the context panel + if (attachedFileRegistry.isAttachedFile( + sessionConversationId, filePath)) { + return ConfirmationResult.AUTO_APPROVED; + } + + // Session override — file level + String convId = sessionConversationId; + Set convFiles = sessionApprovedFiles.get(convId); + if (convFiles != null && convFiles.contains(normalizePath(filePath))) { + return ConfirmationResult.AUTO_APPROVED; + } + // Session override — folder level + Set convFolders = sessionApprovedFolders.get(convId); + if (convFolders != null && filePath != null) { + String normalizedPath = normalizePath(filePath); + for (String folder : convFolders) { + if (normalizedPath.startsWith(folder + "/")) { + return ConfirmationResult.AUTO_APPROVED; + } + } + } + + // Auto-approve reads of Copilot customization files (skills, instructions, prompts, agents) + // discovered by the language server. Reading them is normal agent operation; edits still prompt. + if (isFileRead(params)) { + Path localPath = FileUtils.getLocalFilePath(filePath); + ICustomizationFileService service = getCustomizationFileService(); + if (localPath != null && service != null && isCustomizationRead( + localPath, service.getCustomizationFiles(), service.getSkillFolders())) { + return ConfirmationResult.AUTO_APPROVED; + } + } + + // Files outside workspace always require confirmation + if (isOutsideWorkspace(params)) { + return ConfirmationResult.needsConfirmation(buildContent(params)); + } + + // Check against rules + List rules = loadRules(); + for (FileOperationAutoApproveRule rule : rules) { + if (matchesGlob(filePath, rule.getPattern())) { + return rule.isAutoApprove() + ? ConfirmationResult.AUTO_APPROVED + : ConfirmationResult.needsConfirmation(buildContent(params)); + } + } + + return evaluateUnmatched(params); + } + + private ConfirmationResult evaluateAutoApprovalDisabled( + InvokeClientToolConfirmationParams params, String sessionConversationId) { + String filePath = extractFilePath(params); + if (StringUtils.isBlank(filePath)) { + return ConfirmationResult.DISMISSED; + } + + // Still honor files explicitly attached by the user (intentional context) + if (attachedFileRegistry.isAttachedFile(sessionConversationId, filePath)) { + return ConfirmationResult.AUTO_APPROVED; + } + + // Outside workspace always requires confirmation (simplified dialog only) + if (isOutsideWorkspace(params)) { + return ConfirmationResult.needsConfirmation(buildSimplifiedContent(params)); + } + + // Only check default rules; ignore user-configured rules + for (FileOperationAutoApproveRule rule : FALLBACK_DEFAULT_RULES) { + if (matchesGlob(filePath, rule.getPattern())) { + return rule.isAutoApprove() + ? ConfirmationResult.AUTO_APPROVED + : ConfirmationResult.needsConfirmation(buildSimplifiedContent(params)); + } + } + + // Unmatched workspace file: auto-approve + return ConfirmationResult.AUTO_APPROVED; + } + + private ConfirmationResult evaluateUnmatched( + InvokeClientToolConfirmationParams params) { + if (preferenceStore.getBoolean(Constants.AUTO_APPROVE_UNMATCHED_FILE_OP)) { + return ConfirmationResult.AUTO_APPROVED; + } + return ConfirmationResult.needsConfirmation(buildContent(params)); + } + + private ConfirmationContent buildContent( + InvokeClientToolConfirmationParams params) { + String filePath = extractFilePath(params); + final FileToolType fileType = + FileToolType.fromValue(ConfirmationHandler.extractToolType(params)); + String safeFilePath = filePath != null ? filePath : ""; + boolean outsideWorkspace = isOutsideWorkspace(params); + + List actions = new ArrayList<>(); + actions.add(ConfirmationAction.allowOnce( + Messages.confirmation_action_allowOnce)); + + if (outsideWorkspace && filePath != null) { + // Outside workspace: offer folder-level approval + Path parent = Path.of(filePath).getParent(); + String folderName = (parent != null && parent.getFileName() != null) + ? parent.getFileName().toString() + : (parent != null ? parent.toString() : filePath); + String folderPath = parent != null ? parent.toString() : ""; + actions.add(action(Action.ACCEPT_FOLDER_SESSION, + NLS.bind(Messages.confirmation_action_allowFolderSession, + folderName), + ConfirmationActionScope.SESSION, + Map.of(META_FOLDER_PATH, folderPath))); + } else { + // In workspace: offer file-level approval + actions.add(action(Action.ACCEPT_FILE_SESSION, + Messages.confirmation_action_allowFileSession, + ConfirmationActionScope.SESSION, + Map.of(META_FILE_PATH, safeFilePath))); + actions.add(action(Action.ACCEPT_FILE_GLOBAL, + Messages.confirmation_action_alwaysAllow, + ConfirmationActionScope.GLOBAL, + Map.of(META_FILE_PATH, safeFilePath))); + } + actions.add(ConfirmationAction.skip( + Messages.confirmation_action_skip)); + + String title = params.getTitle() != null + ? params.getTitle() : fileType.getDefaultTitle(); + String fileName = ""; + try { + if (filePath != null) { + fileName = Path.of(filePath).getFileName().toString(); + } + } catch (Exception ignored) { + // use empty + } + String message = NLS.bind(fileType.getMessageTemplate(), fileName); + return new ConfirmationContent(title, message, actions); + } + + /** + * Builds a simplified confirmation dialog with only Allow Once and Skip actions. + * Used when the auto-approval feature is disabled by token/policy. + */ + private ConfirmationContent buildSimplifiedContent( + InvokeClientToolConfirmationParams params) { + String filePath = extractFilePath(params); + final FileToolType fileType = + FileToolType.fromValue(ConfirmationHandler.extractToolType(params)); + String fileName = ""; + try { + if (filePath != null) { + fileName = Path.of(filePath).getFileName().toString(); + } + } catch (Exception ignored) { + // use empty + } + String title = params.getTitle() != null ? params.getTitle() : fileType.getDefaultTitle(); + String message = NLS.bind(fileType.getMessageTemplate(), fileName); + return new ConfirmationContent(title, message, + List.of( + ConfirmationAction.allowOnce(Messages.confirmation_action_allowOnce), + ConfirmationAction.skip(Messages.confirmation_action_skip))); + } + + private static ConfirmationAction action(Action type, String label, + ConfirmationActionScope scope, Map extra) { + Map meta = new java.util.HashMap<>(extra); + meta.put(ConfirmationAction.META_ACTION, type.name()); + return new ConfirmationAction(label, true, scope, meta, false); + } + + private String extractFilePath(InvokeClientToolConfirmationParams params) { + // Try toolMetadata first + ToolMetadata metadata = params.getToolMetadata(); + if (metadata != null && metadata.getSensitiveFileData() != null) { + return metadata.getSensitiveFileData().getFilePath(); + } + // Fallback: extract from input map + Object input = params.getInput(); + if (input instanceof Map) { + Object path = ((Map) input).get("filePath"); + if (path == null) { + path = ((Map) input).get("path"); + } + return path instanceof String ? (String) path : null; + } + return null; + } + + // Uses CLS-provided isGlobal flag from sensitiveFileData metadata + private boolean isOutsideWorkspace(InvokeClientToolConfirmationParams params) { + ToolMetadata metadata = params.getToolMetadata(); + if (metadata != null && metadata.getSensitiveFileData() != null) { + return metadata.getSensitiveFileData().isGlobal(); + } + return false; + } + + private static boolean isFileRead(InvokeClientToolConfirmationParams params) { + return FileToolType.fromValue(ConfirmationHandler.extractToolType(params)) + == FileToolType.FILE_READ; + } + + private static ICustomizationFileService getCustomizationFileService() { + IChatServiceManager chatServiceManager = CopilotCore.getPlugin().getChatServiceManager(); + return chatServiceManager == null ? null : chatServiceManager.getCustomizationFileService(); + } + + /** + * Returns whether reading {@code file} is a customization-file read that is safe to auto-approve. + * A read matches when the file exactly equals a language-server-reported customization file, or + * sits inside a reported skill folder (covering {@code SKILL.md} and the helper files it uses). + * + * @param file the absolute path being read + * @param customizationFiles reported single-file customizations (prompts, instructions, agents) + * @param skillFolders reported skill folders (each directory containing a {@code SKILL.md}) + * @return {@code true} when the read is a recognized customization read + */ + public static boolean isCustomizationRead(Path file, Set customizationFiles, Set skillFolders) { + Path normalized = file.toAbsolutePath().normalize(); + if (customizationFiles.contains(normalized)) { + return true; + } + for (Path skillFolder : skillFolders) { + if (normalized.startsWith(skillFolder)) { + return true; + } + } + return false; + } + + /** Normalizes a file path for case-insensitive, separator-agnostic comparison. */ + private static String normalizePath(String path) { + return ConfirmationHandler.normalizePath(path); + } + + static boolean matchesGlob(String filePath, String globPattern) { + if (StringUtils.isBlank(filePath) || StringUtils.isBlank(globPattern)) { + return false; + } + try { + // Normalize both path and pattern to forward slashes for consistent matching + String normalizedPath = filePath.replace('\\', '/'); + String normalizedPattern = globPattern.replace('\\', '/'); + + // Fast exact-match for absolute file path rules (e.g., from "Always Allow") + if (normalizedPath.equalsIgnoreCase(normalizedPattern)) { + return true; + } + + PathMatcher matcher = FileSystems.getDefault() + .getPathMatcher("glob:" + normalizedPattern); + return matcher.matches(Path.of(normalizedPath)); + } catch (Exception e) { + CopilotCore.LOGGER.error( + "Invalid file-operation auto-approve glob: " + globPattern, e); + return false; + } + } + + List loadRules() { + String json = + preferenceStore.getString(Constants.AUTO_APPROVE_FILE_OP_RULES); + if (StringUtils.isBlank(json) || "[]".equals(json.trim())) { + return Collections.emptyList(); + } + try { + List rules = + new Gson().fromJson(json, RULES_TYPE); + return rules != null ? rules : Collections.emptyList(); + } catch (Exception e) { + CopilotCore.LOGGER.error( + "Failed to parse file-operation auto-approve rules", e); + return Collections.emptyList(); + } + } + + @Override + public void cacheDecision(ConfirmationAction action, + InvokeClientToolConfirmationParams params, + String sessionConversationId) { + String actionName = action.getMetadata() + .get(ConfirmationAction.META_ACTION); + if (actionName == null) { + return; + } + Action type; + try { + type = Action.valueOf(actionName); + } catch (IllegalArgumentException e) { + return; + } + + String convId = sessionConversationId; + Map meta = action.getMetadata(); + switch (type) { + case ACCEPT_FILE_SESSION: + String fp = meta.getOrDefault(META_FILE_PATH, ""); + if (!fp.isEmpty()) { + ConfirmationHandler.evictOldestIfNeeded(sessionApprovedFiles); + sessionApprovedFiles.computeIfAbsent( + convId, k -> ConcurrentHashMap.newKeySet()) + .add(normalizePath(fp)); + } + break; + case ACCEPT_FOLDER_SESSION: + String folder = meta.getOrDefault(META_FOLDER_PATH, ""); + if (!folder.isEmpty()) { + ConfirmationHandler.evictOldestIfNeeded(sessionApprovedFolders); + sessionApprovedFolders.computeIfAbsent( + convId, k -> ConcurrentHashMap.newKeySet()) + .add(normalizePath(folder)); + } + break; + case ACCEPT_FILE_GLOBAL: + String globalFp = meta.getOrDefault(META_FILE_PATH, ""); + if (!globalFp.isEmpty()) { + List rules = + new ArrayList<>(loadRules()); + // Update existing rule if path matches (case-insensitive for Windows) + boolean found = false; + for (FileOperationAutoApproveRule r : rules) { + if (r.getPattern().equalsIgnoreCase(globalFp)) { + r.setAutoApprove(true); + found = true; + break; + } + } + if (!found) { + rules.add(new FileOperationAutoApproveRule(globalFp, + Messages.confirmation_autoApprovedDescription, true)); + } + preferenceStore.setValue(Constants.AUTO_APPROVE_FILE_OP_RULES, + new Gson().toJson(rules)); + } + break; + default: + break; + } + } + + @Override + public void clearSession(String conversationId) { + sessionApprovedFiles.remove(conversationId); + sessionApprovedFolders.remove(conversationId); + attachedFileRegistry.clearConversation(conversationId); + } +} diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/McpConfirmationHandler.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/McpConfirmationHandler.java new file mode 100644 index 00000000..c2757223 --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/McpConfirmationHandler.java @@ -0,0 +1,364 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.chat.confirmation; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import org.apache.commons.lang3.StringUtils; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.osgi.util.NLS; + +import com.microsoft.copilot.eclipse.core.Constants; +import com.microsoft.copilot.eclipse.core.CopilotCore; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationAction; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationActionScope; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationContent; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationResult; +import com.microsoft.copilot.eclipse.core.lsp.protocol.InvokeClientToolConfirmationParams; +import com.microsoft.copilot.eclipse.core.lsp.protocol.ToolAnnotations; +import com.microsoft.copilot.eclipse.ui.chat.Messages; + +/** + * Evaluates MCP tool confirmation requests against session and global approval lists. + * Supports per-server and per-tool approval at both session and global scopes, + * plus optional trust-annotation-based auto-approve for read-only tools. + */ +public class McpConfirmationHandler implements ConfirmationHandler { + + /** Action types for MCP tool confirmation decisions. */ + public enum Action { + /** Allow a specific tool for the current session/conversation. */ + ACCEPT_TOOL_SESSION, + /** Always allow a specific tool (persisted globally). */ + ACCEPT_TOOL_GLOBAL, + /** Allow all tools from a server for the current session/conversation. */ + ACCEPT_SERVER_SESSION, + /** Always allow all tools from a server (persisted globally). */ + ACCEPT_SERVER_GLOBAL + } + + static final String META_SERVER_NAME = "serverName"; + static final String META_TOOL_KEY = "toolKey"; + + private static final String SEPARATOR = "::"; + private static final Type STRING_LIST_TYPE = + new TypeToken>() {}.getType(); + + private final IPreferenceStore preferenceStore; + + // Session-scoped in-memory storage keyed by conversationId. + private final Map> approvedServers = + Collections.synchronizedMap(new LinkedHashMap<>()); + private final Map> approvedTools = + Collections.synchronizedMap(new LinkedHashMap<>()); + + /** + * Creates a new McpConfirmationHandler. + * + * @param preferenceStore the preference store for reading MCP auto-approve settings + */ + public McpConfirmationHandler(IPreferenceStore preferenceStore) { + this.preferenceStore = preferenceStore; + } + + /** + * When the auto-approval feature is disabled, MCP tools always prompt with + * Allow Once / Skip only — no session or global approval buttons. + * This matches IntelliJ's behavior where MCP ignores all rules when disabled. + */ + @Override + public ConfirmationResult evaluate(InvokeClientToolConfirmationParams params, + String sessionConversationId, boolean isAutoApprovalEnabled) { + if (!isAutoApprovalEnabled) { + return evaluateAutoApprovalDisabled(params); + } + return evaluateAutoApprovalEnabled(params, sessionConversationId); + } + + /** + * Evaluates an MCP tool confirmation request. Check order: + * 1. Session approved servers (by conversationId) + * 2. Session approved tools (by conversationId, key = "server::tool") + * 3. Global approved servers list + * 4. Global approved tools list + * 5. Trust annotations (readOnlyHint=true AND openWorldHint=false) + * 6. Otherwise: needs confirmation + */ + private ConfirmationResult evaluateAutoApprovalEnabled( + InvokeClientToolConfirmationParams params, + String sessionConversationId) { + String serverName = extractServerName(params); + String toolName = extractToolName(params); + String serverLower = serverName != null + ? serverName.toLowerCase(Locale.ROOT) : null; + String toolKey = buildToolKey(serverLower, toolName); + + // 1. Session: server approved for this conversation + if (serverLower != null) { + Set sessionServers = + approvedServers.get(sessionConversationId); + if (sessionServers != null + && sessionServers.contains(serverLower)) { + return ConfirmationResult.AUTO_APPROVED; + } + } + + // 2. Session: specific tool approved for this conversation + if (toolKey != null) { + Set sessionTools = + approvedTools.get(sessionConversationId); + if (sessionTools != null && sessionTools.contains(toolKey)) { + return ConfirmationResult.AUTO_APPROVED; + } + } + + // 3. Global: server in approved servers list + if (serverLower != null) { + List globalServers = loadJsonList( + Constants.AUTO_APPROVE_MCP_SERVERS); + for (String s : globalServers) { + if (s.toLowerCase(Locale.ROOT).equals(serverLower)) { + return ConfirmationResult.AUTO_APPROVED; + } + } + } + + // 4. Global: tool in approved tools list + if (toolKey != null) { + List globalTools = loadJsonList( + Constants.AUTO_APPROVE_MCP_TOOLS); + for (String t : globalTools) { + if (t.toLowerCase(Locale.ROOT).equals(toolKey)) { + return ConfirmationResult.AUTO_APPROVED; + } + } + } + + // 5. Trust annotations: read-only and not open-world + if (preferenceStore.getBoolean( + Constants.AUTO_APPROVE_TRUST_TOOL_ANNOTATIONS)) { + ToolAnnotations annotations = params.getAnnotations(); + if (annotations != null + && annotations.isReadOnlyHint() + && !annotations.isOpenWorldHint()) { + return ConfirmationResult.AUTO_APPROVED; + } + } + + // 6. Needs confirmation + return ConfirmationResult.needsConfirmation( + buildContent(params, serverName, toolName)); + } + + private ConfirmationResult evaluateAutoApprovalDisabled( + InvokeClientToolConfirmationParams params) { + String serverName = extractServerName(params); + String toolName = extractToolName(params); + return ConfirmationResult.needsConfirmation( + buildContent(params, serverName, toolName, /* simplifiedOnly= */ true)); + } + + @Override + public void cacheDecision(ConfirmationAction confirmAction, + InvokeClientToolConfirmationParams params, + String sessionConversationId) { + String actionName = confirmAction.getMetadata() + .get(ConfirmationAction.META_ACTION); + if (actionName == null) { + return; + } + Action type; + try { + type = Action.valueOf(actionName); + } catch (IllegalArgumentException e) { + return; + } + + Map meta = confirmAction.getMetadata(); + String serverName = meta.get(META_SERVER_NAME); + String toolKey = meta.get(META_TOOL_KEY); + + switch (type) { + case ACCEPT_TOOL_SESSION: + if (toolKey != null) { + synchronized (approvedTools) { + ConfirmationHandler.evictOldestIfNeeded(approvedTools); + approvedTools.computeIfAbsent( + sessionConversationId, + k -> ConcurrentHashMap.newKeySet()) + .add(toolKey.toLowerCase(Locale.ROOT)); + } + } + break; + case ACCEPT_SERVER_SESSION: + if (serverName != null) { + synchronized (approvedServers) { + ConfirmationHandler.evictOldestIfNeeded(approvedServers); + approvedServers.computeIfAbsent( + sessionConversationId, + k -> ConcurrentHashMap.newKeySet()) + .add(serverName.toLowerCase(Locale.ROOT)); + } + } + break; + case ACCEPT_TOOL_GLOBAL: + if (toolKey != null) { + addToGlobalList(Constants.AUTO_APPROVE_MCP_TOOLS, toolKey); + } + break; + case ACCEPT_SERVER_GLOBAL: + if (serverName != null) { + addToGlobalList(Constants.AUTO_APPROVE_MCP_SERVERS, serverName); + } + break; + default: + break; + } + } + + @Override + public void clearSession(String conversationId) { + approvedServers.remove(conversationId); + approvedTools.remove(conversationId); + } + + private ConfirmationContent buildContent( + InvokeClientToolConfirmationParams params, + String serverName, String toolName) { + return buildContent(params, serverName, toolName, false); + } + + private ConfirmationContent buildContent( + InvokeClientToolConfirmationParams params, + String serverName, String toolName, boolean simplifiedOnly) { + String toolKey = buildToolKey( + serverName != null ? serverName.toLowerCase(Locale.ROOT) : null, + toolName); + + List actions = new ArrayList<>(); + actions.add(ConfirmationAction.allowOnce( + Messages.confirmation_action_allowOnce)); + + if (!simplifiedOnly) { + if (toolName != null && toolKey != null) { + actions.add(action(Action.ACCEPT_TOOL_SESSION, + NLS.bind(Messages.confirmation_action_allowNamesSession, + "'" + toolName + "'"), + ConfirmationActionScope.SESSION, + Map.of(META_TOOL_KEY, toolKey))); + actions.add(action(Action.ACCEPT_TOOL_GLOBAL, + NLS.bind(Messages.confirmation_action_alwaysAllowNames, + "'" + toolName + "'"), + ConfirmationActionScope.GLOBAL, + Map.of(META_TOOL_KEY, toolKey))); + } + + if (serverName != null) { + actions.add(action(Action.ACCEPT_SERVER_SESSION, + NLS.bind(Messages.confirmation_action_allowServerSession, + "'" + serverName + "'"), + ConfirmationActionScope.SESSION, + Map.of(META_SERVER_NAME, serverName))); + actions.add(action(Action.ACCEPT_SERVER_GLOBAL, + NLS.bind(Messages.confirmation_action_alwaysAllowServer, + "'" + serverName + "'"), + ConfirmationActionScope.GLOBAL, + Map.of(META_SERVER_NAME, serverName))); + } + } + + actions.add(ConfirmationAction.skip( + Messages.confirmation_action_skip)); + + String title; + if (toolName != null && serverName != null) { + title = NLS.bind(Messages.confirmation_title_mcpTool, + toolName, serverName); + } else { + title = params.getTitle() != null + ? params.getTitle() + : Messages.confirmation_title_mcpToolDefault; + } + + return new ConfirmationContent(title, params.getMessage(), actions); + } + + private static ConfirmationAction action(Action type, String label, + ConfirmationActionScope scope, Map extra) { + Map meta = new HashMap<>(extra); + meta.put(ConfirmationAction.META_ACTION, type.name()); + return new ConfirmationAction(label, true, scope, meta, false); + } + + private String extractServerName( + InvokeClientToolConfirmationParams params) { + Object input = params.getInput(); + if (input instanceof Map inputMap) { + Object value = inputMap.get("mcpServerName"); + if (value instanceof String s && StringUtils.isNotBlank(s)) { + return s; + } + } + return null; + } + + private String extractToolName( + InvokeClientToolConfirmationParams params) { + Object input = params.getInput(); + if (input instanceof Map inputMap) { + Object value = inputMap.get("mcpToolName"); + if (value instanceof String s && StringUtils.isNotBlank(s)) { + return s; + } + } + return null; + } + + private static String buildToolKey(String serverLower, String toolName) { + if (serverLower == null || toolName == null) { + return null; + } + return serverLower + SEPARATOR + + toolName.toLowerCase(Locale.ROOT); + } + + private List loadJsonList(String preferenceKey) { + String json = preferenceStore.getString(preferenceKey); + if (StringUtils.isBlank(json) || "[]".equals(json.trim())) { + return Collections.emptyList(); + } + try { + List list = new Gson().fromJson(json, STRING_LIST_TYPE); + return list != null ? list : Collections.emptyList(); + } catch (Exception e) { + CopilotCore.LOGGER.error( + "Failed to parse MCP auto-approve list: " + preferenceKey, e); + return Collections.emptyList(); + } + } + + private void addToGlobalList(String preferenceKey, String value) { + List current = new ArrayList<>(loadJsonList(preferenceKey)); + String lowerValue = value.toLowerCase(Locale.ROOT); + for (String existing : current) { + if (existing.toLowerCase(Locale.ROOT).equals(lowerValue)) { + return; // already present + } + } + current.add(value); + preferenceStore.setValue(preferenceKey, new Gson().toJson(current)); + } + +} diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/TerminalConfirmationHandler.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/TerminalConfirmationHandler.java new file mode 100644 index 00000000..b4641499 --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/TerminalConfirmationHandler.java @@ -0,0 +1,547 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.chat.confirmation; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; +import java.util.stream.Collectors; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import org.apache.commons.lang3.StringUtils; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.osgi.util.NLS; + +import com.microsoft.copilot.eclipse.core.Constants; +import com.microsoft.copilot.eclipse.core.CopilotCore; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationAction; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationActionScope; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationContent; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationResult; +import com.microsoft.copilot.eclipse.core.chat.TerminalAutoApproveRule; +import com.microsoft.copilot.eclipse.core.lsp.protocol.InvokeClientToolConfirmationParams; +import com.microsoft.copilot.eclipse.core.lsp.protocol.ToolMetadata; +import com.microsoft.copilot.eclipse.ui.chat.Messages; + +/** + * Evaluates terminal command confirmation requests against user-configured allow/deny rules. + * Rules are matched against command names provided by CLS in toolMetadata.terminalCommandData. + */ +public class TerminalConfirmationHandler implements ConfirmationHandler { + + /** Action types matching IntelliJ's TerminalAutoApproveAction enum. */ + public enum Action { + /** Allow specific command names for the current session/conversation. */ + ACCEPT_NAMES_SESSION, + /** Always allow specific command names (persisted as a global rule). */ + ACCEPT_NAMES_GLOBAL, + /** Allow this exact command line for the current session/conversation. */ + ACCEPT_EXACT_SESSION, + /** Always allow this exact command line (persisted as a global rule). */ + ACCEPT_EXACT_GLOBAL, + /** Allow all terminal commands for the current session/conversation. */ + ACCEPT_ALL_SESSION + } + + /** Result of evaluating sub-commands against rules. */ + enum RuleVerdict { ALL_APPROVED, DENY_BLOCKED, UNMATCHED } + + private static final class RuleResult { + final RuleVerdict verdict; + final List unapprovedItems; + + RuleResult(RuleVerdict verdict, List unapprovedItems) { + this.verdict = verdict; + this.unapprovedItems = unapprovedItems; + } + } + + static final String META_COMMAND_NAMES = "commandNames"; + static final String META_COMMAND_LINE = "commandLine"; + + /** Default deny rules for dangerous terminal commands. */ + public static final List DEFAULT_RULES = List.of( + new TerminalAutoApproveRule("rm", false), + new TerminalAutoApproveRule("rmdir", false), + new TerminalAutoApproveRule("del", false), + new TerminalAutoApproveRule("kill", false), + new TerminalAutoApproveRule("curl", false), + new TerminalAutoApproveRule("wget", false), + new TerminalAutoApproveRule("eval", false), + new TerminalAutoApproveRule("chmod", false), + new TerminalAutoApproveRule("chown", false), + new TerminalAutoApproveRule("/^Remove-Item\\b/i", false), + new TerminalAutoApproveRule("/(\\(.+\\))/s", false), + new TerminalAutoApproveRule("/`.+`/s", false), + new TerminalAutoApproveRule("/\\{.+\\}/s", false)); + + private static final Type RULES_TYPE = new TypeToken>() { + }.getType(); + + private final IPreferenceStore preferenceStore; + + // Session-scoped in-memory storage keyed by conversationId. + // Uses insertion-ordered maps so we can evict the oldest entry when the + // map grows beyond MAX_SESSION_CONVERSATIONS. + private final Map> allowedCommandNames = + Collections.synchronizedMap(new LinkedHashMap<>()); + private final Map> allowedExactCommands = + Collections.synchronizedMap(new LinkedHashMap<>()); + private final Set allowAllConversations = + Collections.newSetFromMap( + Collections.synchronizedMap(new LinkedHashMap<>())); + + /** + * Creates a new TerminalConfirmationHandler. + * + * @param preferenceStore the preference store for reading terminal auto-approve rules + */ + public TerminalConfirmationHandler(IPreferenceStore preferenceStore) { + this.preferenceStore = preferenceStore; + } + + /** + * When the auto-approval feature is disabled, terminal commands always prompt + * with Allow Once / Skip only — no session or global approval buttons. + * This matches IntelliJ's behavior where terminal ignores all rules when disabled. + */ + @Override + public ConfirmationResult evaluate(InvokeClientToolConfirmationParams params, + String sessionConversationId, boolean isAutoApprovalEnabled) { + if (!isAutoApprovalEnabled) { + return evaluateAutoApprovalDisabled(params); + } + return evaluateAutoApprovalEnabled(params, sessionConversationId); + } + + /** + * Evaluates a terminal confirmation request. Check order follows IntelliJ: + * 1. Session "allow all" flag + * 2. Session exact commandLine match + * 3. Session command name match (all names must be approved) + * 4. Global exact commandLine match against rules + * 5. Global per-subCommand regex/prefix match against rules + * 6. Unmatched fallback (auto-approve if preference enabled) + */ + private ConfirmationResult evaluateAutoApprovalEnabled( + InvokeClientToolConfirmationParams params, + String sessionConversationId) { + String convId = sessionConversationId; + String commandLine = extractCommandLine(params); + + // 1. Session: all commands allowed for this conversation + if (allowAllConversations.contains(convId)) { + return ConfirmationResult.AUTO_APPROVED; + } + + // 2. Session: exact commandLine previously approved + Set exactSet = allowedExactCommands.get(convId); + if (commandLine != null && exactSet != null + && exactSet.contains(commandLine.trim())) { + return ConfirmationResult.AUTO_APPROVED; + } + + // 3. Session: all command names (e.g. "tree", "echo") approved + String[] cmdNames = getCommandNames(params); + Set namesSet = allowedCommandNames.get(convId); + if (cmdNames != null && namesSet != null && cmdNames.length > 0) { + boolean allApproved = true; + for (String name : cmdNames) { + if (!namesSet.contains(name)) { + allApproved = false; + break; + } + } + if (allApproved) { + return ConfirmationResult.AUTO_APPROVED; + } + } + + // 4-6. Global rules + String[] subCommands = getSubCommands(params); + if (subCommands == null || subCommands.length == 0) { + return ConfirmationResult.needsConfirmation( + buildContent(params, null)); + } + + List rules = loadRules(); + + // 4. Exact commandLine match + if (commandLine != null) { + for (TerminalAutoApproveRule rule : rules) { + if (commandLine.trim().equals(rule.getCommand().trim()) + && rule.isAutoApprove()) { + return ConfirmationResult.AUTO_APPROVED; + } + } + } + + // 5. Per-subCommand evaluation + RuleResult result = evaluateSubCommands( + subCommands, cmdNames, rules, namesSet); + + switch (result.verdict) { + case ALL_APPROVED: + return ConfirmationResult.AUTO_APPROVED; + case DENY_BLOCKED: + return ConfirmationResult.needsConfirmation( + buildContent(params, result.unapprovedItems)); + case UNMATCHED: + default: + // 6. Unmatched fallback + if (preferenceStore.getBoolean( + Constants.AUTO_APPROVE_UNMATCHED_TERMINAL)) { + return ConfirmationResult.AUTO_APPROVED; + } + List items = result.unapprovedItems.isEmpty() + ? null : result.unapprovedItems; + return ConfirmationResult.needsConfirmation( + buildContent(params, items)); + } + } + + private ConfirmationResult evaluateAutoApprovalDisabled( + InvokeClientToolConfirmationParams params) { + String title = params.getTitle() != null + ? params.getTitle() : Messages.confirmation_title_terminal; + return ConfirmationResult.needsConfirmation( + new ConfirmationContent(title, params.getMessage(), + List.of( + ConfirmationAction.allowOnce(Messages.confirmation_action_allowOnce), + ConfirmationAction.skip(Messages.confirmation_action_skip)))); + } + + /** + * Evaluates each sub-command against global rules and session state. + * Returns a verdict and the list of unapproved command names. + */ + private RuleResult evaluateSubCommands(String[] subCommands, + String[] cmdNames, List rules, + Set sessionApprovedNames) { + boolean allApproved = true; + boolean hasDeny = false; + List unapproved = new ArrayList<>(); + + for (int i = 0; i < subCommands.length; i++) { + String subCommand = subCommands[i]; + String cmdName = cmdNames != null && i < cmdNames.length + ? cmdNames[i] : null; + boolean hasAllow = false; + boolean denied = false; + + // Session command-name approval + if (cmdName != null && sessionApprovedNames != null + && sessionApprovedNames.contains(cmdName)) { + hasAllow = true; + } + + // Global rule matching + for (TerminalAutoApproveRule rule : rules) { + if (matchesRule(subCommand, rule.getCommand())) { + if (rule.isAutoApprove()) { + hasAllow = true; + } else { + denied = true; + } + break; + } + } + + if (denied && !hasAllow) { + hasDeny = true; + if (cmdName != null && !unapproved.contains(cmdName)) { + unapproved.add(cmdName); + } + } else if (!hasAllow) { + allApproved = false; + if (cmdName != null && !unapproved.contains(cmdName)) { + unapproved.add(cmdName); + } + } + } + + RuleVerdict verdict; + if (hasDeny) { + verdict = RuleVerdict.DENY_BLOCKED; + } else if (allApproved) { + verdict = RuleVerdict.ALL_APPROVED; + } else { + verdict = RuleVerdict.UNMATCHED; + } + return new RuleResult(verdict, unapproved); + } + + /** + * Builds the confirmation dialog content. When {@code unapprovedNames} + * is non-null, only those names appear in the command-name actions + * (already-approved names are filtered out). + */ + private ConfirmationContent buildContent( + InvokeClientToolConfirmationParams params, + List unapprovedNames) { + final String[] commandNames = getCommandNames(params); + String commandLine = extractCommandLine(params); + + // Use unapproved names if available, otherwise all unique names + List uniqueNames = unapprovedNames != null + ? unapprovedNames : dedup(commandNames); + String label = !uniqueNames.isEmpty() + ? "'" + String.join(", ", uniqueNames) + "'" : "'command'"; + String namesValue = String.join(",", uniqueNames); + + // Show exact command actions when commandLine differs from + // a single command name (otherwise redundant). + boolean showExact = commandLine != null + && !(uniqueNames.size() == 1 + && commandLine.trim().equals(uniqueNames.get(0))); + + List actions = new ArrayList<>(); + actions.add(ConfirmationAction.allowOnce(Messages.confirmation_action_allowOnce)); + if (!uniqueNames.isEmpty()) { + actions.add(action(Action.ACCEPT_NAMES_SESSION, + NLS.bind(Messages.confirmation_action_allowNamesSession, label), + ConfirmationActionScope.SESSION, + Map.of(META_COMMAND_NAMES, namesValue))); + actions.add(action(Action.ACCEPT_NAMES_GLOBAL, + NLS.bind(Messages.confirmation_action_alwaysAllowNames, label), + ConfirmationActionScope.GLOBAL, + Map.of(META_COMMAND_NAMES, namesValue))); + } + if (showExact) { + actions.add(action(Action.ACCEPT_EXACT_SESSION, + Messages.confirmation_action_allowExactSession, + ConfirmationActionScope.SESSION, + Map.of(META_COMMAND_LINE, commandLine))); + actions.add(action(Action.ACCEPT_EXACT_GLOBAL, + Messages.confirmation_action_alwaysAllowExact, + ConfirmationActionScope.GLOBAL, + Map.of(META_COMMAND_LINE, commandLine))); + } + actions.add(action(Action.ACCEPT_ALL_SESSION, + Messages.confirmation_action_allowAllCommands, + ConfirmationActionScope.SESSION, Map.of())); + actions.add(ConfirmationAction.skip(Messages.confirmation_action_skip)); + + String title = params.getTitle() != null + ? params.getTitle() : Messages.confirmation_title_terminal; + return new ConfirmationContent(title, params.getMessage(), actions); + } + + private static ConfirmationAction action(Action type, String label, + ConfirmationActionScope scope, Map extra) { + Map meta = new HashMap<>(extra); + meta.put(ConfirmationAction.META_ACTION, type.name()); + return new ConfirmationAction(label, true, scope, meta, false); + } + + private String extractCommandLine( + InvokeClientToolConfirmationParams params) { + Object input = params.getInput(); + if (input instanceof Map inputMap) { + Object cmd = inputMap.get("command"); + if (cmd instanceof String) { + return (String) cmd; + } + } + return null; + } + + private static List dedup(String[] items) { + if (items == null || items.length == 0) { + return Collections.emptyList(); + } + LinkedHashSet set = new LinkedHashSet<>(); + for (String item : items) { + if (item != null && !item.isBlank()) { + set.add(item); + } + } + return new ArrayList<>(set); + } + + private String[] getSubCommands(InvokeClientToolConfirmationParams params) { + ToolMetadata metadata = params.getToolMetadata(); + if (metadata != null && metadata.getTerminalCommandData() != null) { + return metadata.getTerminalCommandData().getSubCommands(); + } + return null; + } + + private String[] getCommandNames(InvokeClientToolConfirmationParams params) { + ToolMetadata metadata = params.getToolMetadata(); + if (metadata != null && metadata.getTerminalCommandData() != null) { + return metadata.getTerminalCommandData().getCommandNames(); + } + return null; + } + + /** + * Matches a sub-command against a rule. Exact string match is checked + * first (for exact-command rules). Then regex rules (/pattern/flags) are + * used directly, and simple rules (e.g., "rm") are converted to ^rm\b. + */ + static boolean matchesRule(String subCommand, String rulePattern) { + if (StringUtils.isBlank(subCommand) + || StringUtils.isBlank(rulePattern)) { + return false; + } + + // Exact match first + if (subCommand.trim().equals(rulePattern.trim())) { + return true; + } + + String regex; + int regexFlags = 0; + + if (rulePattern.startsWith("/") + && rulePattern.lastIndexOf('/') > 0) { + // Explicit regex: "/^git\b/i" + int lastSlash = rulePattern.lastIndexOf('/'); + regex = rulePattern.substring(1, lastSlash); + String flags = rulePattern.substring(lastSlash + 1); + if (flags.contains("i")) { + regexFlags |= Pattern.CASE_INSENSITIVE; + } + if (flags.contains("s")) { + regexFlags |= Pattern.DOTALL; + } + } else { + // Simple rule: "rm" → "^rm\b" + regex = "^" + Pattern.quote(rulePattern) + "\\b"; + } + + try { + return Pattern.compile(regex, regexFlags) + .matcher(subCommand).find(); + } catch (PatternSyntaxException e) { + CopilotCore.LOGGER.error( + "Invalid terminal auto-approve regex: " + rulePattern, e); + return false; + } + } + + List loadRules() { + String json = preferenceStore.getString(Constants.AUTO_APPROVE_TERMINAL_RULES); + if (StringUtils.isBlank(json) || "[]".equals(json.trim())) { + return Collections.emptyList(); + } + try { + List rules = new Gson().fromJson(json, RULES_TYPE); + return rules != null ? rules : Collections.emptyList(); + } catch (Exception e) { + CopilotCore.LOGGER.error("Failed to parse terminal auto-approve rules", e); + return Collections.emptyList(); + } + } + + @Override + public void cacheDecision(ConfirmationAction confirmAction, + InvokeClientToolConfirmationParams params, + String sessionConversationId) { + String actionName = confirmAction.getMetadata() + .get(ConfirmationAction.META_ACTION); + if (actionName == null) { + return; + } + Action type; + try { + type = Action.valueOf(actionName); + } catch (IllegalArgumentException e) { + return; + } + + String convId = sessionConversationId; + + // Prefer command data from action metadata (set by buildContent) + // so we persist exactly what the user chose, not the full params. + Map meta = confirmAction.getMetadata(); + String metaNames = meta.get(META_COMMAND_NAMES); + String metaLine = meta.get(META_COMMAND_LINE); + + String[] cmdNames = metaNames != null && !metaNames.isBlank() + ? metaNames.split(",") : getCommandNames(params); + String commandLine = metaLine != null && !metaLine.isBlank() + ? metaLine : extractCommandLine(params); + + switch (type) { + case ACCEPT_NAMES_SESSION: + if (cmdNames != null) { + ConfirmationHandler.evictOldestIfNeeded(allowedCommandNames); + Set nameSet = allowedCommandNames.computeIfAbsent( + convId, k -> ConcurrentHashMap.newKeySet()); + Collections.addAll(nameSet, cmdNames); + } + break; + case ACCEPT_EXACT_SESSION: + if (commandLine != null && !commandLine.isBlank()) { + ConfirmationHandler.evictOldestIfNeeded(allowedExactCommands); + allowedExactCommands.computeIfAbsent( + convId, k -> ConcurrentHashMap.newKeySet()) + .add(commandLine.trim()); + } + break; + case ACCEPT_ALL_SESSION: + allowAllConversations.add(convId); + // Cap allowAllConversations the same way + while (allowAllConversations.size() > MAX_SESSION_CONVERSATIONS) { + allowAllConversations.iterator().remove(); + } + break; + case ACCEPT_NAMES_GLOBAL: + if (cmdNames != null) { + addGlobalRules(List.of(cmdNames)); + } + break; + case ACCEPT_EXACT_GLOBAL: + if (commandLine != null && !commandLine.isBlank()) { + addGlobalRules(List.of(commandLine.trim())); + } + break; + default: + break; + } + } + + @Override + public void clearSession(String conversationId) { + allowedCommandNames.remove(conversationId); + allowedExactCommands.remove(conversationId); + allowAllConversations.remove(conversationId); + } + + private void addGlobalRules(List commands) { + List original = loadRules(); + Set existing = original.stream() + .map(TerminalAutoApproveRule::getCommand) + .collect(Collectors.toSet()); + + // Override existing deny rules → allow + List updated = original.stream() + .map(r -> commands.contains(r.getCommand()) && !r.isAutoApprove() + ? new TerminalAutoApproveRule(r.getCommand(), true) : r) + .collect(Collectors.toCollection(ArrayList::new)); + + // Append new rules for commands not yet present + commands.stream() + .filter(cmd -> !existing.contains(cmd)) + .map(cmd -> new TerminalAutoApproveRule(cmd, true)) + .forEach(updated::add); + + if (!updated.equals(original)) { + preferenceStore.setValue(Constants.AUTO_APPROVE_TERMINAL_RULES, + new Gson().toJson(updated)); + } + } +} diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/contextwindow/ContextSizeDonut.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/contextwindow/ContextSizeDonut.java index c6cc8630..6c226499 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/contextwindow/ContextSizeDonut.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/contextwindow/ContextSizeDonut.java @@ -63,7 +63,7 @@ public ContextSizeDonut(Composite parent, ContextWindowService contextWindowServ e.gc.drawArc(arcOffset, arcOffset, arcSize, arcSize, 0, 360); // Used portion starting from 12 o'clock (90°) going clockwise (negative angle) - double pct = Math.min(info.utilizationPercentage(), 100.0); + double pct = Math.min(contextWindowService.getDisplayUtilizationPercentage(info), 100.0); int filledAngle = (int) Math.round(pct / 100.0 * 360); if (filledAngle > 0) { Color filledColor = pct >= 90 ? CssConstants.getDonutWarningColor(e.display) diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/contextwindow/ContextWindowPopup.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/contextwindow/ContextWindowPopup.java index 7f67021a..15f38afd 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/contextwindow/ContextWindowPopup.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/contextwindow/ContextWindowPopup.java @@ -67,12 +67,12 @@ protected void populateContent(Composite parent) { tokenUsageLabel = createSecondaryTextLabel(tokenRow, formatTokenRow(latestInfo)); tokenUsageLabel.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false)); percentageLabel = createSecondaryTextLabel(tokenRow, - formatPercentage(latestInfo.utilizationPercentage())); + formatPercentage(contextWindowService.getDisplayUtilizationPercentage(latestInfo))); percentageLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.NONE, false, false)); progressBar = new ContextWindowBar(parent, SWT.NONE); progressBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - progressBar.setPercentage((int) Math.round(latestInfo.utilizationPercentage())); + progressBar.setPercentage((int) Math.round(contextWindowService.getDisplayUtilizationPercentage(latestInfo))); addSeparator(parent, SECTION_SPACING); @@ -107,7 +107,7 @@ private void updateLabels(ContextSizeInfo info) { return; } setLabelText(tokenUsageLabel, formatTokenRow(info)); - setLabelText(percentageLabel, formatPercentage(info.utilizationPercentage())); + setLabelText(percentageLabel, formatPercentage(contextWindowService.getDisplayUtilizationPercentage(info))); setLabelText(systemInstructionsValue, percentageOf(info.systemPromptTokens(), info.totalTokenLimit())); setLabelText(toolDefinitionsValue, @@ -120,7 +120,7 @@ private void updateLabels(ContextSizeInfo info) { setLabelText(toolResultsValue, percentageOf(info.toolResultsTokens(), info.totalTokenLimit())); if (progressBar != null && !progressBar.isDisposed()) { - progressBar.setPercentage((int) Math.round(info.utilizationPercentage())); + progressBar.setPercentage((int) Math.round(contextWindowService.getDisplayUtilizationPercentage(info))); } shell.requestLayout(); } @@ -146,9 +146,9 @@ private static String formatPercentage(double pct) { return String.format("%.1f%%", pct); } - private static String formatTokenRow(ContextSizeInfo info) { + private String formatTokenRow(ContextSizeInfo info) { return MessageFormat.format(Messages.context_window_tokens, - formatTokens(info.totalUsedTokens()), formatTokens(info.totalTokenLimit())); + formatTokens(info.totalUsedTokens()), formatTokens(contextWindowService.getDisplayTokenLimit(info))); } private static String percentageOf(int tokens, int totalLimit) { diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/contextwindow/ContextWindowService.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/contextwindow/ContextWindowService.java index 412c41ea..d1b7b781 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/contextwindow/ContextWindowService.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/contextwindow/ContextWindowService.java @@ -17,6 +17,9 @@ import org.eclipse.swt.widgets.Display; import com.microsoft.copilot.eclipse.core.lsp.protocol.ContextSizeInfo; +import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel; +import com.microsoft.copilot.eclipse.ui.chat.services.ModelService; +import com.microsoft.copilot.eclipse.ui.utils.ModelUtils; import com.microsoft.copilot.eclipse.ui.utils.SwtUtils; /** @@ -27,11 +30,15 @@ public class ContextWindowService { private IObservableValue contextSizeObservable; private final Map popupSideEffects = new HashMap<>(); + private final ModelService modelService; /** * Creates the service and initializes the observable state on the UI realm. + * + * @param modelService the model service used to resolve the active model's context window */ - public ContextWindowService() { + public ContextWindowService(ModelService modelService) { + this.modelService = modelService; AtomicReference> observableRef = new AtomicReference<>(); SwtUtils.invokeOnDisplayThread(() -> { Realm realm = Realm.getDefault(); @@ -58,6 +65,68 @@ public ContextSizeInfo getState() { return result.get(); } + /** + * Returns the context-window limit shown in the donut popup. Prefer the active model's resolved full context window, + * falling back to the language-server usage snapshot when the model metadata is unavailable. + * + * @param info the context usage snapshot + * @return the display context-window limit + */ + public int getDisplayTokenLimit(ContextSizeInfo info) { + if (info == null) { + return 0; + } + + Integer outputLimit = getActiveModelOutputLimit(); + if (info.reservedOutputTokens() > 0) { + outputLimit = info.reservedOutputTokens(); + } + if (outputLimit != null && outputLimit > 0) { + return info.totalTokenLimit() + outputLimit; + } + + Integer modelContextWindow = getActiveModelContextWindow(); + return modelContextWindow != null && modelContextWindow > 0 ? modelContextWindow : info.totalTokenLimit(); + } + + /** + * Returns the utilization percentage against the displayed context window. + * + * @param info the context usage snapshot + * @return the utilization percentage + */ + public double getDisplayUtilizationPercentage(ContextSizeInfo info) { + if (info == null) { + return 0; + } + int displayLimit = getDisplayTokenLimit(info); + if (displayLimit <= 0) { + return info.utilizationPercentage(); + } + return (double) info.totalUsedTokens() / displayLimit * 100; + } + + private Integer getActiveModelContextWindow() { + CopilotModel activeModel = getActiveModel(); + if (activeModel == null) { + return null; + } + return ModelUtils.resolveContextWindowSize(activeModel); + } + + private Integer getActiveModelOutputLimit() { + CopilotModel activeModel = getActiveModel(); + if (activeModel == null || activeModel.getCapabilities() == null + || activeModel.getCapabilities().limits() == null) { + return null; + } + return activeModel.getCapabilities().limits().maxOutputTokens(); + } + + private CopilotModel getActiveModel() { + return modelService == null ? null : modelService.getActiveModel(); + } + /** * Updates the current context size state and notifies bound UI. * diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/messages.properties b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/messages.properties index 05a27d94..d46ae613 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/messages.properties +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/messages.properties @@ -35,3 +35,36 @@ todoList_collapseTooltip=Click to collapse the todo list thinking_title=Thinking thinking_expandTooltip=Click to show the thinking details thinking_collapseTooltip=Click to hide the thinking details + +# Confirmation dialog action labels +confirmation_action_allowOnce=Allow Once +confirmation_action_skip=Skip +confirmation_action_allowAllCommands=Allow all commands in this Session +confirmation_action_allowNamesSession=Allow {0} in this Session +confirmation_action_alwaysAllowNames=Always Allow {0} +confirmation_action_allowExactSession=Allow this exact command in this Session +confirmation_action_alwaysAllowExact=Always Allow this exact command +confirmation_action_alwaysAllow=Always Allow +confirmation_action_allowFileSession=Allow this file in this Session +confirmation_action_allowFolderSession=Allow folder ''{0}'' in this Session + +# MCP confirmation dialog +confirmation_title_mcpTool=Run ''{0}'' tool from ''{1}'' MCP server +confirmation_title_mcpToolDefault=Allow MCP tool? +confirmation_action_allowServerSession=Allow tools from {0} in this Session +confirmation_action_alwaysAllowServer=Always Allow tools from {0} + +# Confirmation dialog titles +confirmation_title_terminal=Run command in terminal +confirmation_title_fallback=Allow {0}? +confirmation_title_fileRead=Allow reading sensitive file? +confirmation_title_fileWrite=Allow edits to sensitive file? +confirmation_title_fileOperation=Allow operation on sensitive file? + +# Confirmation dialog messages +confirmation_message_fileRead=The model wants to read sensitive file ({0}). +confirmation_message_fileWrite=The model wants to edit sensitive file ({0}). +confirmation_message_fileOperation=The model wants to access sensitive file ({0}). + +# Misc +confirmation_autoApprovedDescription=Auto-approved from dialog diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/AgentToolService.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/AgentToolService.java index 4eab4f0c..c7a013c2 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/AgentToolService.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/AgentToolService.java @@ -18,6 +18,9 @@ import com.microsoft.copilot.eclipse.core.CopilotCore; import com.microsoft.copilot.eclipse.core.chat.ChatEventsManager; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationAction; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationContent; +import com.microsoft.copilot.eclipse.core.chat.ConfirmationResult; import com.microsoft.copilot.eclipse.core.chat.ToolInvocationListener; import com.microsoft.copilot.eclipse.core.lsp.CopilotLanguageServerConnection; import com.microsoft.copilot.eclipse.core.lsp.protocol.InvokeClientToolConfirmationParams; @@ -32,9 +35,13 @@ import com.microsoft.copilot.eclipse.core.utils.PlatformUtils; import com.microsoft.copilot.eclipse.terminal.api.IRunInTerminalTool; import com.microsoft.copilot.eclipse.terminal.api.TerminalServiceManager; +import com.microsoft.copilot.eclipse.ui.CopilotUi; import com.microsoft.copilot.eclipse.ui.chat.BaseTurnWidget; import com.microsoft.copilot.eclipse.ui.chat.ChatContentViewer; import com.microsoft.copilot.eclipse.ui.chat.ChatView; +import com.microsoft.copilot.eclipse.ui.chat.InvokeToolConfirmationDialog; +import com.microsoft.copilot.eclipse.ui.chat.confirmation.AttachedFileRegistry; +import com.microsoft.copilot.eclipse.ui.chat.confirmation.ConfirmationService; import com.microsoft.copilot.eclipse.ui.chat.tools.BaseTool; import com.microsoft.copilot.eclipse.ui.chat.tools.CreateFileTool; import com.microsoft.copilot.eclipse.ui.chat.tools.EditFileTool; @@ -55,6 +62,8 @@ public class AgentToolService implements ToolInvocationListener, TerminalService protected CopilotLanguageServerConnection lsConnection; private volatile boolean terminalToolsRegistered = false; private List cachedBuiltInTools; + private final ConfirmationService confirmationService; + private final AttachedFileRegistry attachedFileRegistry; /** * Constructor for AgentToolService. @@ -62,6 +71,10 @@ public class AgentToolService implements ToolInvocationListener, TerminalService public AgentToolService(CopilotLanguageServerConnection lsConnection) { this.tools = new ConcurrentHashMap<>(); this.lsConnection = lsConnection; + this.attachedFileRegistry = new AttachedFileRegistry(); + this.confirmationService = new ConfirmationService( + CopilotUi.getPlugin().getPreferenceStore(), + attachedFileRegistry); TerminalServiceManager terminalManager = TerminalServiceManager.getInstance(); if (terminalManager != null) { terminalManager.addListener(this); @@ -243,6 +256,29 @@ public CompletableFuture onToolConfirmation return CompletableFuture.completedFuture(result); } + // Resolve the session conversation ID: map subagent conversations to the + // parent so that session-scoped approvals apply to the whole chat. + String sessionConversationId = params.getConversationId(); + if (boundChatView != null + && !Objects.equals(sessionConversationId, + boundChatView.getConversationId()) + && Objects.equals(sessionConversationId, + boundChatView.getSubagentConversationId())) { + sessionConversationId = boundChatView.getConversationId(); + } + + // Auto-approve evaluation + ConfirmationResult autoApproveResult = + confirmationService.evaluate(params, sessionConversationId); + if (autoApproveResult.isAutoApproved()) { + return CompletableFuture.completedFuture( + new LanguageModelToolConfirmationResult(ToolConfirmationResult.ACCEPT)); + } + if (autoApproveResult.isDismissed()) { + return CompletableFuture.completedFuture( + new LanguageModelToolConfirmationResult(ToolConfirmationResult.DISMISS)); + } + BaseTurnWidget turnWidget = boundChatView.getChatContentViewer().getTurnWidget(params.getTurnId()); if (turnWidget == null) { LanguageModelToolConfirmationResult result = new LanguageModelToolConfirmationResult( @@ -254,13 +290,30 @@ public CompletableFuture onToolConfirmation BaseTurnWidget activeTurnWidget = turnWidget.getActiveTurnWidget(); AtomicReference> ref = new AtomicReference<>(); + ConfirmationContent content = autoApproveResult.getContent(); SwtUtils.invokeOnDisplayThread(() -> { - ref.set( - activeTurnWidget.requestToolExecutionConfirmation(params.getTitle(), params.getMessage(), params.getInput())); - boundChatView.getChatContentViewer().refreshScrollerLayout(); + ref.set(activeTurnWidget.requestToolExecutionConfirmation( + content, params.getInput())); + boundChatView.getChatContentViewer().refreshLayoutFull(); }); - return ref.get(); + CompletableFuture future = ref.get(); + if (future != null && content != null) { + // Capture dialog reference before it can be reset by a new request + final InvokeToolConfirmationDialog dialog = + activeTurnWidget.getConfirmDialog(); + final String sessConvId = sessionConversationId; + future = future.thenApply(result -> { + ConfirmationAction selected = dialog != null + ? dialog.getSelectedAction() : null; + if (selected != null && selected.isAccept()) { + confirmationService.cacheDecision(selected, params, + sessConvId); + } + return result; + }); + } + return future; } private boolean validToolConfirmInvokeParams(String conversationId, String turnId) { @@ -283,6 +336,20 @@ private boolean validToolConfirmInvokeParams(String conversationId, String turnI return true; } + /** + * Get the confirmation service for auto-approve evaluation. + * + * @return the confirmation service + */ + public ConfirmationService getConfirmationService() { + return confirmationService; + } + + /** Returns the registry of user-attached context files. */ + public AttachedFileRegistry getAttachedFileRegistry() { + return attachedFileRegistry; + } + /** * Dispose the service. */ diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/ChatCompletionService.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/ChatCompletionService.java index cff99834..1f0953cd 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/ChatCompletionService.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/ChatCompletionService.java @@ -30,6 +30,7 @@ import com.microsoft.copilot.eclipse.core.CopilotAuthStatusListener; import com.microsoft.copilot.eclipse.core.CopilotCore; import com.microsoft.copilot.eclipse.core.FeatureFlags; +import com.microsoft.copilot.eclipse.core.chat.service.ICustomizationFileService.CustomizationType; import com.microsoft.copilot.eclipse.core.events.CopilotEventConstants; import com.microsoft.copilot.eclipse.core.lsp.CopilotLanguageServerConnection; import com.microsoft.copilot.eclipse.core.lsp.protocol.ChatMode; @@ -76,7 +77,13 @@ public ChatCompletionService(CopilotLanguageServerConnection lsConnection, AuthS ResourcesPlugin.getWorkspace().addResourceChangeListener(skillFileListener, IResourceChangeEvent.POST_CHANGE); this.eventBroker = PlatformUI.getWorkbench().getService(IEventBroker.class); if (this.eventBroker != null) { - this.customPromptsChangedHandler = event -> fetchAsync(); + // Templates only surface skills and prompts, so ignore instruction/agent changes. + this.customPromptsChangedHandler = event -> { + Object type = event.getProperty(IEventBroker.DATA); + if (type == CustomizationType.SKILL || type == CustomizationType.PROMPT) { + fetchAsync(); + } + }; this.eventBroker.subscribe(CopilotEventConstants.TOPIC_CHAT_DID_CHANGE_CUSTOMIZATION_FILES, customPromptsChangedHandler); } diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/ChatServiceManager.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/ChatServiceManager.java index ac3d955a..62e6c4a6 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/ChatServiceManager.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/ChatServiceManager.java @@ -5,6 +5,7 @@ import com.microsoft.copilot.eclipse.core.AuthStatusManager; import com.microsoft.copilot.eclipse.core.CopilotCore; +import com.microsoft.copilot.eclipse.core.chat.service.CustomizationFileService; import com.microsoft.copilot.eclipse.core.chat.service.IChatServiceManager; import com.microsoft.copilot.eclipse.core.lsp.CopilotLanguageServerConnection; import com.microsoft.copilot.eclipse.core.persistence.ConversationPersistenceManager; @@ -29,6 +30,7 @@ public class ChatServiceManager implements IChatServiceManager { private ReferencedFileService referencedFileService; private McpConfigService mcpConfigService; private McpExtensionPointManager mcpExtensionPointManager; + private CustomizationFileService customizationFileService; private McpRuntimeLogger mcpRuntimeLogger; private ConversationPersistenceManager persistenceManager; @@ -51,10 +53,12 @@ public ChatServiceManager() { referencedFileService = new ReferencedFileService(); mcpConfigService = new McpConfigService(); mcpExtensionPointManager = new McpExtensionPointManager(mcpConfigService); + customizationFileService = new CustomizationFileService(this.lsConnection); + customizationFileService.refreshAllAsync(); mcpRuntimeLogger = new McpRuntimeLogger(); persistenceManager = new ConversationPersistenceManager(this.authStatusManager); chatFontService = new ChatFontService(); - contextWindowService = new ContextWindowService(); + contextWindowService = new ContextWindowService(modelService); } /** @@ -140,6 +144,11 @@ public McpConfigService getMcpConfigService() { return mcpConfigService; } + @Override + public CustomizationFileService getCustomizationFileService() { + return customizationFileService; + } + /** * Get the persistence manager. * @@ -202,6 +211,7 @@ public void dispose() { this.agentToolService.dispose(); this.referencedFileService.dispose(); this.mcpConfigService.dispose(); + this.customizationFileService.dispose(); this.contextWindowService.dispose(); if (this.byokService != null) { this.byokService.dispose(); diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/McpConfigService.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/McpConfigService.java index 60ccc202..078faa1e 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/McpConfigService.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/McpConfigService.java @@ -29,6 +29,7 @@ import com.microsoft.copilot.eclipse.ui.CopilotUi; import com.microsoft.copilot.eclipse.ui.chat.dialogs.DynamicOauthDialog; import com.microsoft.copilot.eclipse.ui.i18n.Messages; +import com.microsoft.copilot.eclipse.ui.preferences.McpAutoApproveSection; import com.microsoft.copilot.eclipse.ui.preferences.McpPreferencePage; /** @@ -50,6 +51,7 @@ public class McpConfigService extends ChatBaseService implements IMcpConfigServi private ISideEffect mcpToolButtonEnableSideEffect; private ISideEffect mcpToolsButtonRedNoticeSideEffect; private ISideEffect mcpPrefencePageExtMcpTitleRedNoticeSideEffect; + private ISideEffect mcpAutoApproveSideEffect; private IEventBroker eventBroker; @@ -108,6 +110,28 @@ private void initializeMcpFeatureFlagUpdateEvent() { eventBroker.subscribe(CopilotEventConstants.TOPIC_CHAT_DID_CHANGE_FEATURE_FLAGS, featureFlagNotifiedEventHandler); } + /** + * Bind the observable with UI in McpAutoApproveSection. + */ + public void bindWithAutoApproveSection(McpAutoApproveSection section) { + ensureRealm(() -> { + unbindWithAutoApproveSection(); + mcpAutoApproveSideEffect = ISideEffect.create( + mcpToolsObservableValue::getValue, + section::updateServerCollections); + }); + } + + /** + * Unbind the McpAutoApproveSection side-effect. + */ + public void unbindWithAutoApproveSection() { + if (mcpAutoApproveSideEffect != null) { + mcpAutoApproveSideEffect.dispose(); + mcpAutoApproveSideEffect = null; + } + } + /** * Bind the observable with UI in McpPreferencePage. */ diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/McpExtensionPointManager.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/McpExtensionPointManager.java index 759af1a0..07685bda 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/McpExtensionPointManager.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/McpExtensionPointManager.java @@ -52,11 +52,12 @@ public class McpExtensionPointManager { private static final String ELEMENT_PROVIDER = "provider"; private static final String ATTRIBUTE_CLASS = "class"; - private String approvedExtMcpServers; + private volatile String approvedExtMcpServers; private Map extMcpInfoMap = new HashMap<>(); // Key: Plugin-Id(Bundle) private McpConfigService mcpConfigService; private Gson gson; + private IEventBroker eventBroker; /** * Constructor for McpExtensionPointManager. @@ -64,28 +65,36 @@ public class McpExtensionPointManager { public McpExtensionPointManager(McpConfigService mcpConfigService) { gson = new GsonBuilder().disableHtmlEscaping().create(); this.mcpConfigService = mcpConfigService; + this.eventBroker = PlatformUI.getWorkbench().getService(IEventBroker.class); if (CopilotCore.getPlugin().getFeatureFlags().isMcpContributionPointEnabled()) { initializeExtMcpRegistration(); } - IEventBroker eventBroker = PlatformUI.getWorkbench().getService(IEventBroker.class); eventBroker.subscribe(CopilotEventConstants.TOPIC_DID_CHANGE_MCP_CONTRIBUTION_POINT_POLICY, event -> { Boolean enabled = (Boolean) event.getProperty(IEventBroker.DATA); if (enabled.booleanValue()) { initializeExtMcpRegistration(); } else { - extMcpInfoMap.clear(); - approvedExtMcpServers = null; - persistExtMcpInfo(extMcpInfoMap); - mcpConfigService.setNewExtMcpRegFound(false); + // Disabling the contribution point clears the in-memory state shared with doRegistration(). + // Hold the manager monitor so the (non-thread-safe) HashMap clear and the approved-servers + // reset are not observed mid-update by a concurrent doRegistration() running on the async + // worker. + synchronized (this) { + extMcpInfoMap.clear(); + approvedExtMcpServers = null; + persistExtMcpInfo(extMcpInfoMap); + mcpConfigService.setNewExtMcpRegFound(false); + } } }); } private synchronized void initializeExtMcpRegistration() { - // Previously approved servers will be started during Plugin startup. + // Avoid pre-populating the in-memory approved servers from the persisted cache. If we did so, + // the initial syncMcpRegistrationConfiguration() at startup would push potentially stale data + // (server removed by the contributing plugin, port changed, plugin uninstalled) to the language + // server, which would surface a connection failure before doRegistration() can refresh the state. Map persistedMcpContribs = loadPersistedMcpContribs(); - updateApprovedMcpServerString(persistedMcpContribs); // Run the heavy initialization work asynchronously, which has weak relation with Plugin startup. CompletableFuture.runAsync(() -> { @@ -93,16 +102,42 @@ private synchronized void initializeExtMcpRegistration() { }); } - private synchronized void doRegistration(Map persistedMcpContribs) { + private void doRegistration(Map persistedMcpContribs) { + String approvedServersToPublish = null; + boolean shouldPublish = false; try { FeatureFlags flags = CopilotCore.getPlugin().getFeatureFlags(); if (flags != null && !flags.isMcpEnabled()) { return; } - loadMcpRegistrationExtensionPoint(); - detectChangesInMcpContribs(persistedMcpContribs); + // Perform the slow extension-point scan and diff work outside the lock so that + // UI-thread callers (e.g. approveExtMcpRegistration) are not blocked. + Map scannedMap = loadMcpRegistrationExtensionPoint(); + detectChangesInMcpContribs(scannedMap, persistedMcpContribs); + synchronized (this) { + extMcpInfoMap = scannedMap; + updateApprovedMcpServerString(extMcpInfoMap); + persistExtMcpInfo(extMcpInfoMap); + approvedServersToPublish = approvedExtMcpServers; + shouldPublish = true; + } } catch (Exception e) { CopilotCore.LOGGER.error("Error during EXT MCP registration initialization", e); + return; + } + // Publish the verified state outside the synchronized section so the manager monitor is not + // held while subscribers (notably LanguageServerSettingManager) push to the language server. + // The event fires unconditionally on success - including when the persisted JSON is unchanged + // and IPreferenceStore.setValue() therefore short-circuits its property-change notification - + // so the LSP always receives the verified extension-contributed servers. + if (shouldPublish) { + publishRegistrationCompleted(approvedServersToPublish); + } + } + + private void publishRegistrationCompleted(String approvedServersJson) { + if (eventBroker != null) { + eventBroker.post(CopilotEventConstants.TOPIC_MCP_EXTENSION_POINT_REGISTRATION_COMPLETED, approvedServersJson); } } @@ -151,11 +186,12 @@ private void updateApprovedMcpServerString(Map extM /** * Load MCP registration from extension point. */ - private void loadMcpRegistrationExtensionPoint() { + private Map loadMcpRegistrationExtensionPoint() { + Map result = new HashMap<>(); IExtensionRegistry registry = Platform.getExtensionRegistry(); IExtensionPoint extensionPoint = registry.getExtensionPoint(EXTENSION_POINT_ID); if (extensionPoint == null) { - return; + return result; } // Traverse all extensions/bundles. @@ -167,7 +203,7 @@ private void loadMcpRegistrationExtensionPoint() { CopilotCore.LOGGER.error("Cannot find bundle: " + bundleName, null); continue; // Skip inactive plug-ins } - if (bundle.getState() != Bundle.ACTIVE || bundle.getState() != Bundle.STARTING) { + if (bundle.getState() != Bundle.ACTIVE && bundle.getState() != Bundle.STARTING) { try { bundle.start(Bundle.START_ACTIVATION_POLICY); } catch (BundleException e) { @@ -221,9 +257,10 @@ private void loadMcpRegistrationExtensionPoint() { // Update registration info if (!mergedServers.isEmpty()) { - extMcpInfoMap.put(bundleName, new McpRegistrationInfo(isTrusted, isApproved, pluginDisplayName, mergedServers)); + result.put(bundleName, new McpRegistrationInfo(isTrusted, isApproved, pluginDisplayName, mergedServers)); } } + return result; } /** @@ -268,14 +305,16 @@ private boolean isMcpFromSignedBundle(Bundle bundle) { /** * Detect changes in MCP registration from extension point compared to the existing record. */ - private void detectChangesInMcpContribs(Map existingExtMcpInfoMap) { + private void detectChangesInMcpContribs( + Map scannedMap, + Map existingExtMcpInfoMap) { boolean newExtMcpRegFound = false; if (existingExtMcpInfoMap == null) { existingExtMcpInfoMap = Collections.emptyMap(); } // Compare each plugin's current MCP servers with the stored record - for (Map.Entry entry : extMcpInfoMap.entrySet()) { + for (Map.Entry entry : scannedMap.entrySet()) { String contributorName = entry.getKey(); McpRegistrationInfo mcpRegistrationInfo = entry.getValue(); McpRegistrationInfo storedInfo = existingExtMcpInfoMap.get(contributorName); @@ -296,13 +335,6 @@ private void detectChangesInMcpContribs(Map existin if (newExtMcpRegFound) { mcpConfigService.setNewExtMcpRegFound(true); } - - // Always persist the latest MCP registration info, in case some plug-ins are un-installed, or unregister MCP - // servers. - if (!extMcpInfoMap.equals(existingExtMcpInfoMap)) { - updateApprovedMcpServerString(extMcpInfoMap); - persistExtMcpInfo(extMcpInfoMap); - } } /** @@ -310,18 +342,35 @@ private void detectChangesInMcpContribs(Map existin */ public String approveExtMcpRegistration() { Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); - if (extMcpInfoMap.isEmpty()) { - MessageDialog.openInformation(shell, "", "No MCP server registration found"); - return null; + Map dialogInput; + synchronized (this) { + if (extMcpInfoMap.isEmpty()) { + MessageDialog.openInformation(shell, "", "No MCP server registration found"); + return null; + } + // Take a shallow snapshot so the dialog can iterate the map safely even if doRegistration() + // mutates extMcpInfoMap on the async worker. Approval flips happen on the McpRegistrationInfo + // value objects, which are shared between the snapshot and the live map by reference, so the + // user's choices are reflected in extMcpInfoMap once the dialog returns. + dialogInput = new HashMap<>(extMcpInfoMap); } - McpApprovalDialog dialog = new McpApprovalDialog(shell, extMcpInfoMap); + // Open the modal dialog outside the synchronized block so a concurrent doRegistration() worker + // is not stalled on this manager's monitor while the user interacts with the dialog. + McpApprovalDialog dialog = new McpApprovalDialog(shell, dialogInput); dialog.open(); - mcpConfigService.setNewExtMcpRegFound(false); // Reset the flag after user approval - updateApprovedMcpServerString(extMcpInfoMap); - persistExtMcpInfo(extMcpInfoMap); - return approvedExtMcpServers; + String approvedJson; + synchronized (this) { + mcpConfigService.setNewExtMcpRegFound(false); // Reset the flag after user approval + updateApprovedMcpServerString(extMcpInfoMap); + persistExtMcpInfo(extMcpInfoMap); + approvedJson = approvedExtMcpServers; + } + // Publish outside the lock so subscribers (notably LanguageServerSettingManager) are not + // running their LSP push while the manager monitor is held. + publishRegistrationCompleted(approvedJson); + return approvedJson; } private void persistExtMcpInfo(Map extMcpInfoMap) { @@ -396,7 +445,7 @@ public String getMcpServersAsJson() { /** * Check if there is any MCP registration from extension point. */ - public boolean hasExtMcpRegistration() { + public synchronized boolean hasExtMcpRegistration() { return !extMcpInfoMap.isEmpty(); } } diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/ChangedFile.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/ChangedFile.java new file mode 100644 index 00000000..aed4594c --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/ChangedFile.java @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.chat.tools; + +import java.nio.file.Path; +import java.util.Objects; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.eclipse.core.resources.IFile; + +/** + * Represents a file tracked in the file change summary bar. + */ +public final class ChangedFile { + private final IFile workspaceFile; + private final Path localPath; + + private ChangedFile(IFile workspaceFile, Path localPath) { + this.workspaceFile = workspaceFile; + this.localPath = localPath; + } + + /** + * Creates a changed file entry for a workspace file. + * + * @param file the workspace file + * @return the changed file entry + */ + public static ChangedFile workspace(IFile file) { + return new ChangedFile(Objects.requireNonNull(file), null); + } + + /** + * Creates a changed file entry for a local file. + * + * @param path the local file path + * @return the changed file entry + */ + public static ChangedFile local(Path path) { + return new ChangedFile(null, normalize(path)); + } + + /** + * Returns true if this entry represents a workspace file. + * + * @return true for workspace files, false for local files + */ + public boolean isWorkspaceFile() { + return workspaceFile != null; + } + + /** + * Gets the workspace file for this entry. + * + * @return the workspace file, or null for local files + */ + public IFile getWorkspaceFile() { + return workspaceFile; + } + + /** + * Gets the local path for this entry. + * + * @return the local path, or null for workspace files + */ + public Path getLocalPath() { + return localPath; + } + + /** + * Gets the display name for this file. + * + * @return the file name + */ + public String getName() { + if (workspaceFile != null) { + return workspaceFile.getName(); + } + Path fileName = localPath.getFileName(); + return fileName == null ? localPath.toString() : fileName.toString(); + } + + /** + * Gets the display path for this file. + * + * @return the workspace path or local filesystem path + */ + public String getDisplayPath() { + if (workspaceFile != null) { + return workspaceFile.getFullPath().toString(); + } + return localPath.toString(); + } + + private static Path normalize(Path path) { + return Objects.requireNonNull(path).toAbsolutePath().normalize(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof ChangedFile other)) { + return false; + } + return Objects.equals(workspaceFile, other.workspaceFile) && Objects.equals(localPath, other.localPath); + } + + @Override + public int hashCode() { + return Objects.hash(workspaceFile, localPath); + } + + @Override + public String toString() { + ToStringBuilder builder = new ToStringBuilder(this); + builder.append("workspaceFile", workspaceFile); + builder.append("localPath", localPath); + return builder.toString(); + } +} \ No newline at end of file diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/CreateFileTool.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/CreateFileTool.java index 29a807ce..ca9485dd 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/CreateFileTool.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/CreateFileTool.java @@ -5,9 +5,13 @@ import java.io.ByteArrayInputStream; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; @@ -19,6 +23,7 @@ import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.lsp4j.FileChangeType; +import com.microsoft.copilot.eclipse.core.CopilotCore; import com.microsoft.copilot.eclipse.core.lsp.protocol.InputSchema; import com.microsoft.copilot.eclipse.core.lsp.protocol.InputSchemaPropertyValue; import com.microsoft.copilot.eclipse.core.lsp.protocol.LanguageModelToolInformation; @@ -57,7 +62,7 @@ public LanguageModelToolInformation getToolInformation() { // Set the name and description of the tool toolInfo.setName(TOOL_NAME); toolInfo.setDescription(""" - This is a tool for creating a new file in the workspace. + This is a tool for creating a new workspace file or a new file at an absolute local filesystem path. The file will be created with the specified content. """); @@ -90,34 +95,49 @@ public CompletableFuture invoke(Map i return CompletableFuture.completedFuture(new LanguageModelToolResult[] { result }); } - try { - // Resolve file in workspace - IFile file = FileUtils.getFileFromPath(filePath, false); + String content = StringUtils.isBlank((String) input.get("content")) ? "" : (String) input.get("content"); + result = createFile(filePath, content); - if (file == null) { - result.setStatus(ToolInvocationStatus.error); - result.addContent("Invalid file path: " + filePath + " does not exist in the workspace."); - return CompletableFuture.completedFuture(new LanguageModelToolResult[] { result }); - } + return CompletableFuture.completedFuture(new LanguageModelToolResult[] { result }); + } + + private LanguageModelToolResult createFile(String filePath, String content) { + IFile file = FileUtils.getFileFromPath(filePath, false); + + if (file != null && file.getProject().exists()) { + return createWorkspaceFile(file, filePath, content); + } + + Path localPath = FileUtils.getLocalFilePath(filePath); + if (localPath != null) { + return createLocalFile(localPath, content); + } - // Check if file already exists + LanguageModelToolResult result = new LanguageModelToolResult(); + result.setStatus(ToolInvocationStatus.error); + result.addContent("Invalid file path: " + filePath + " does not exist in the workspace."); + return result; + } + + private LanguageModelToolResult createWorkspaceFile(IFile file, String filePath, String content) { + LanguageModelToolResult result = new LanguageModelToolResult(); + + try { if (file.exists()) { result.setStatus(ToolInvocationStatus.error); result.addContent("Failed: file already exists: " + filePath + ". Please use edit file tool to update."); - return CompletableFuture.completedFuture(new LanguageModelToolResult[] { result }); + return result; } - // Create parent folders if needed createParentFolders(file.getParent()); - // Create file with content - String content = StringUtils.isBlank((String) input.get("content")) ? "" : (String) input.get("content"); try (ByteArrayInputStream contentStream = new ByteArrayInputStream( content.getBytes(PlatformUtils.getFileCharset(file)))) { file.create(contentStream, IResource.FORCE, new NullProgressMonitor()); - cacheTheOriginalFileContent(file); + cacheTheOriginalFileContent(ChangedFile.workspace(file), StringUtils.EMPTY); } - CopilotUi.getPlugin().getChatServiceManager().getFileToolService().addChangedFile(file, FileChangeType.Created); + CopilotUi.getPlugin().getChatServiceManager().getFileToolService().addChangedFile(ChangedFile.workspace(file), + FileChangeType.Created); file.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor()); result.addContent("File created at: " + file.getFullPath().toOSString()); @@ -130,7 +150,36 @@ public CompletableFuture invoke(Map i result.addContent("Error handling file stream: " + e.getMessage()); } - return CompletableFuture.completedFuture(new LanguageModelToolResult[] { result }); + return result; + } + + private LanguageModelToolResult createLocalFile(Path filePath, String content) { + LanguageModelToolResult result = new LanguageModelToolResult(); + Path normalizedPath = normalizeLocalPath(filePath); + if (Files.exists(normalizedPath, LinkOption.NOFOLLOW_LINKS)) { + result.setStatus(ToolInvocationStatus.error); + result.addContent("Failed: file already exists: " + normalizedPath + ". Please use edit file tool to update."); + return result; + } + + try { + Path parent = normalizedPath.getParent(); + if (parent != null) { + Files.createDirectories(parent); + } + Files.writeString(normalizedPath, content, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW); + cacheTheOriginalFileContent(ChangedFile.local(normalizedPath), StringUtils.EMPTY); + CopilotUi.getPlugin().getChatServiceManager().getFileToolService().addChangedFile( + ChangedFile.local(normalizedPath), FileChangeType.Created); + result.addContent("File created at: " + normalizedPath); + result.setStatus(ToolInvocationStatus.success); + } catch (IOException e) { + CopilotCore.LOGGER.error("Error creating local file", e); + result.setStatus(ToolInvocationStatus.error); + result.addContent("Error creating file: " + e.getMessage()); + } + + return result; } /** @@ -152,33 +201,36 @@ private void createParentFolders(IResource parent) throws CoreException { } @Override - public void onKeepAllChanges(List files) { - files.forEach(this::onKeepChange); + public void onKeepChange(ChangedFile file) { + removeCachedFileContent(file); + closeCompareEditor(file); } @Override - public void onKeepChange(IFile file) { + public void onUndoChange(ChangedFile file) throws CoreException, IOException { + deleteCreatedFile(file); + removeCachedFileContent(file); closeCompareEditor(file); } - @Override - public void onUndoAllChanges(List files) throws CoreException { - for (IFile file : files) { - onUndoChange(file); + private void deleteCreatedFile(ChangedFile file) throws CoreException, IOException { + if (file.isWorkspaceFile()) { + IFile workspaceFile = file.getWorkspaceFile(); + if (workspaceFile != null && workspaceFile.exists()) { + workspaceFile.delete(true, new NullProgressMonitor()); + } + return; } + Files.deleteIfExists(file.getLocalPath()); } @Override - public void onUndoChange(IFile file) throws CoreException { - if (file != null && file.exists()) { - file.delete(true, new NullProgressMonitor()); + public void onViewDiff(ChangedFile file) { + if (file.isWorkspaceFile()) { + SwtUtils.invokeOnDisplayThreadAsync(() -> UiUtils.openInEditor(file.getWorkspaceFile())); + return; } - closeCompareEditor(file); - } - - @Override - public void onViewDiff(IFile file) { - SwtUtils.invokeOnDisplayThreadAsync(() -> UiUtils.openInEditor(file)); + SwtUtils.invokeOnDisplayThreadAsync(() -> UiUtils.openLocalFileInEditor(file.getLocalPath())); } @Override diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/EditFileTool.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/EditFileTool.java index 9a6c532e..1260b0a1 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/EditFileTool.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/EditFileTool.java @@ -7,13 +7,14 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; import java.util.Arrays; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; -import org.eclipse.compare.CompareEditorInput; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; @@ -52,7 +53,7 @@ public LanguageModelToolInformation getToolInformation() { // Set the name and description of the tool toolInfo.setName(TOOL_NAME); toolInfo.setDescription(""" - Insert new code into an existing file in the workspace. + Insert new code into an existing workspace file or local filesystem file. Use this tool once per file that needs to be modified, even if there are multiple changes for a file. Generate the "explanation" property first. The system is very smart and can understand how to apply your edits to the files, @@ -122,30 +123,8 @@ class Person { public CompletableFuture invoke(Map input, ChatView chatView) { CompletableFuture resultFuture = new CompletableFuture<>(); if (input.get("filePath") instanceof String filePath) { - IFile file = FileUtils.getFileFromPath(filePath, true); - - if (file == null || !file.exists()) { - resultFuture.complete(new LanguageModelToolResult[] { - new LanguageModelToolResult("The file path provided does not exist. Please check the path and try again.", - ToolInvocationStatus.error) }); - return resultFuture; - } - if (input.get("code") instanceof String code) { - CopilotUi.getPlugin().getChatServiceManager().getFileToolService().addChangedFile(file, FileChangeType.Changed); - cacheTheOriginalFileContent(file); - try { - applyChangesToFile(code, file); - } catch (CoreException | IOException e) { - CopilotCore.LOGGER.error("Error replacing file content", e); - resultFuture.complete(new LanguageModelToolResult[] { new LanguageModelToolResult( - "Failed to apply changes to the file: " + e.getMessage(), ToolInvocationStatus.error) }); - return resultFuture; - } - refreshCompareEditorIfOpen(fileContentCache.get(file), file); - // Must return the updated content as a result to the CLS. - resultFuture.complete( - new LanguageModelToolResult[] { new LanguageModelToolResult(code, ToolInvocationStatus.success) }); + resultFuture.complete(editFile(filePath, code)); } else { resultFuture.complete(new LanguageModelToolResult[] { new LanguageModelToolResult("The code provided is not a valid string. Please check the code and try again.", @@ -160,6 +139,60 @@ public CompletableFuture invoke(Map i return resultFuture; } + private LanguageModelToolResult[] editFile(String filePath, String code) { + IFile file = FileUtils.getFileFromPath(filePath, true); + + if (file != null && file.exists()) { + return editWorkspaceFile(file, code); + } + + Path localPath = FileUtils.getLocalFilePath(filePath); + if (localPath != null && Files.isRegularFile(localPath, LinkOption.NOFOLLOW_LINKS)) { + return editLocalFile(localPath, code); + } + + return new LanguageModelToolResult[] { + new LanguageModelToolResult("The file path provided does not exist. Please check the path and try again.", + ToolInvocationStatus.error) }; + } + + private LanguageModelToolResult[] editWorkspaceFile(IFile file, String code) { + ChangedFile changedFile = ChangedFile.workspace(file); + CopilotUi.getPlugin().getChatServiceManager().getFileToolService().addChangedFile(changedFile, + FileChangeType.Changed); + cacheTheOriginalFileContent(changedFile); + try { + applyChangesToFile(code, file); + } catch (CoreException | IOException e) { + CopilotCore.LOGGER.error("Error replacing file content", e); + return new LanguageModelToolResult[] { new LanguageModelToolResult( + "Failed to apply changes to the file: " + e.getMessage(), ToolInvocationStatus.error) }; + } + refreshCompareEditorIfOpen(getCachedFileContent(changedFile), changedFile); + return new LanguageModelToolResult[] { new LanguageModelToolResult(code, ToolInvocationStatus.success) }; + } + + private LanguageModelToolResult[] editLocalFile(Path filePath, String code) { + Path normalizedPath = normalizeLocalPath(filePath); + ChangedFile changedFile = ChangedFile.local(normalizedPath); + try { + String originalContent = getCachedFileContent(changedFile); + if (originalContent == null) { + originalContent = Files.readString(normalizedPath, StandardCharsets.UTF_8); + } + Files.writeString(normalizedPath, code, StandardCharsets.UTF_8); + cacheTheOriginalFileContent(changedFile, originalContent); + CopilotUi.getPlugin().getChatServiceManager().getFileToolService().addChangedFile(changedFile, + FileChangeType.Changed); + refreshCompareEditorIfOpen(getCachedFileContent(changedFile), changedFile); + return new LanguageModelToolResult[] { new LanguageModelToolResult(code, ToolInvocationStatus.success) }; + } catch (IOException e) { + CopilotCore.LOGGER.error("Error replacing local file content", e); + return new LanguageModelToolResult[] { new LanguageModelToolResult( + "Failed to apply changes to the file: " + e.getMessage(), ToolInvocationStatus.error) }; + } + } + private void applyChangesToFile(String changedContent, IFile file) throws CoreException, IOException { if (!validateEdit(file)) { throw new IllegalStateException("File validation failed for " + file.getFullPath()); @@ -189,55 +222,40 @@ private ByteArrayInputStream getInputStream(String changedContent, IFile file) { } @Override - public void onKeepChange(IFile file) { - fileContentCache.remove(file); + public void onKeepChange(ChangedFile file) { + removeCachedFileContent(file); closeCompareEditor(file); } @Override - public void onKeepAllChanges(List files) { - for (IFile file : files) { - onKeepChange(file); - } - } - - @Override - public void onUndoChange(IFile file) throws CoreException, IOException { + public void onUndoChange(ChangedFile file) throws CoreException, IOException { undoChangesToFile(file); closeCompareEditor(file); } @Override - public void onUndoAllChanges(List files) throws CoreException, IOException { - for (IFile file : files) { - onUndoChange(file); + public void onViewDiff(ChangedFile file) { + if (bringCompareEditorToTopIfOpen(file)) { + return; } + compareStringWithFile(getCachedFileContent(file), file); } - @Override - public void onViewDiff(IFile file) { - CompareEditorInput input = compareEditorInputMap.get(file); - if (input != null) { - if (isCompareEditorOpen(input)) { - bringCompareEditorToTop(input); - return; - } - // Compare editor was closed by the user, remove stale entry and recreate - compareEditorInputMap.remove(file); + private void undoChangesToFile(ChangedFile file) throws CoreException, IOException { + String fileCache = getCachedFileContent(file); + if (fileCache == null) { + return; + } + if (file.isWorkspaceFile()) { + applyChangesToFile(fileCache, file.getWorkspaceFile()); + } else { + Files.writeString(file.getLocalPath(), fileCache, StandardCharsets.UTF_8); } - compareStringWithFile(fileContentCache.get(file), file); + removeCachedFileContent(file); } @Override public void onResolveAllChanges() { cleanupChangedFiles(); } - - private void undoChangesToFile(IFile file) throws CoreException, IOException { - String fileCache = fileContentCache.get(file); - if (fileCache != null) { - applyChangesToFile(fileCache, file); - } - fileContentCache.remove(file); - } } diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/FileToolBase.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/FileToolBase.java index 1bf6fc6e..8d545fd7 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/FileToolBase.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/FileToolBase.java @@ -9,10 +9,13 @@ import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; import org.eclipse.compare.CompareConfiguration; import org.eclipse.compare.CompareEditorInput; @@ -30,6 +33,7 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Status; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; @@ -49,8 +53,8 @@ * Abstract class for handling file change tool related actions. */ public abstract class FileToolBase extends BaseTool { - protected static Map compareEditorInputMap = new ConcurrentHashMap<>(); - protected static Map fileContentCache = new ConcurrentHashMap<>(); + protected static Map compareEditorInputMap = new ConcurrentHashMap<>(); + protected static Map fileContentCache = new ConcurrentHashMap<>(); @Override public abstract CompletableFuture invoke(Map input, ChatView chatView); @@ -59,7 +63,7 @@ public abstract class FileToolBase extends BaseTool { * Common method to handle cleanup of file changes. */ protected void cleanupChangedFiles() { - for (IFile file : compareEditorInputMap.keySet()) { + for (ChangedFile file : compareEditorInputMap.keySet()) { closeCompareEditor(file); } compareEditorInputMap.clear(); @@ -67,24 +71,62 @@ protected void cleanupChangedFiles() { } /** - * Caches the original content of the file to be compared with the proposed changes. + * Caches the original content of the changed file to be compared with the proposed changes. * - * @param file The file whose original content is to be cached. + * @param file The changed file whose original content is to be cached. */ - protected void cacheTheOriginalFileContent(IFile file) { + protected void cacheTheOriginalFileContent(ChangedFile file) { if (fileContentCache.containsKey(file)) { // We only need to cache the original file content once to keep the initial file content so that we can undo the // entire file edit even the file has been modified for multiple rounds. return; } - try (InputStream inputStream = file.getContents()) { - String content = new String(inputStream.readAllBytes(), PlatformUtils.getFileCharset(file)); - fileContentCache.put(file, content); + try { + fileContentCache.put(file, readCurrentFileContent(file)); } catch (IOException | CoreException e) { CopilotCore.LOGGER.error("Error caching original file content", e); } } + /** + * Caches the original content for a changed file if no baseline exists yet. + * + * @param file The file whose original content is to be cached. + * @param content The content to use as the original baseline. + */ + protected void cacheTheOriginalFileContent(ChangedFile file, String content) { + fileContentCache.putIfAbsent(file, content); + } + + private String readCurrentFileContent(ChangedFile file) throws IOException, CoreException { + if (file.isWorkspaceFile()) { + IFile workspaceFile = file.getWorkspaceFile(); + try (InputStream inputStream = workspaceFile.getContents()) { + return new String(inputStream.readAllBytes(), PlatformUtils.getFileCharset(workspaceFile)); + } + } + return Files.readString(file.getLocalPath(), StandardCharsets.UTF_8); + } + + /** + * Gets the cached original content for a changed file. + * + * @param file The changed file whose cached content should be returned. + * @return the cached content, or null if no content is cached. + */ + protected String getCachedFileContent(ChangedFile file) { + return fileContentCache.get(file); + } + + /** + * Removes the cached original content for a changed file. + * + * @param file The changed file whose cached content should be removed. + */ + protected void removeCachedFileContent(ChangedFile file) { + fileContentCache.remove(file); + } + /** * Validate the edit to ensure the files are writable. * @@ -105,14 +147,12 @@ public void run(IProgressMonitor monitor) throws CoreException { } /** - * Compares the given string with the content of the given file in a compare editor. + * Compares the given string with the content of a changed file in a compare editor. * * @param originalFileContent The original string content of the file to compare with. - * @param file The user's file with the proposed changes has been applied. - * @throws InvocationTargetException If the operation is canceled. - * @throws InterruptedException If the operation is canceled. + * @param file The changed file with the proposed changes applied. */ - protected void compareStringWithFile(String originalFileContent, IFile file) { + protected void compareStringWithFile(String originalFileContent, ChangedFile file) { try { CompareEditorInput input = createCompareEditorInput(originalFileContent, file); input.run(new NullProgressMonitor()); @@ -130,47 +170,12 @@ protected void compareStringWithFile(String originalFileContent, IFile file) { } /** - * Updates the current or creates a new compare editor with the given file content and file. - * - * @param originalFileContent The original string content of the file to compare with. - * @param file The user's file with the proposed changes has been applied. - */ - protected void updateOrCreateCompareStringWithFile(String fileContent, IFile file) { - if (fileContent == null) { - return; - } - - CompareEditorInput input = compareEditorInputMap.get(file); - if (input != null) { - if (fileContent.equals(fileContentCache.get(file))) { - SwtUtils.invokeOnDisplayThreadAsync(() -> { - CompareUI.reuseCompareEditor(input, (IReusableEditor) getCompareEditor(input)); - }); - } else { - CompareEditorInput newInput = createCompareEditorInput(fileContent, file); - compareEditorInputMap.put(file, newInput); - SwtUtils.invokeOnDisplayThreadAsync(() -> { - CompareEditorInput compareEditorInput = compareEditorInputMap.get(file); - if (compareEditorInput != null) { - CompareUI.reuseCompareEditor(compareEditorInput, (IReusableEditor) getCompareEditor(compareEditorInput)); - } - }); - } - bringCompareEditorToTop(input); - } else { - // If not, create a new compare editor - compareStringWithFile(fileContent, file); - } - } - - /** - * Refreshes the compare editor for the given file only if it is already open. Does not open a new editor or steal - * focus. + * Refreshes the compare editor for the given changed file only if it is already open. * * @param fileContent The original file content to compare against. - * @param file The file whose compare editor should be refreshed. + * @param file The changed file whose compare editor should be refreshed. */ - protected void refreshCompareEditorIfOpen(String fileContent, IFile file) { + protected void refreshCompareEditorIfOpen(String fileContent, ChangedFile file) { if (fileContent == null) { return; } @@ -184,11 +189,10 @@ protected void refreshCompareEditorIfOpen(String fileContent, IFile file) { // If the compare editor is closed, remove the input from the map and skip refreshing. compareEditorInputMap.remove(file); return; - } else { - CompareEditorInput compareEditorInput = compareEditorInputMap.get(file); - if (compareEditorInput != null) { - CompareUI.reuseCompareEditor(compareEditorInput, (IReusableEditor) editor); - } + } + CompareEditorInput compareEditorInput = compareEditorInputMap.get(file); + if (compareEditorInput != null) { + CompareUI.reuseCompareEditor(compareEditorInput, (IReusableEditor) editor); } }); } @@ -236,12 +240,11 @@ private IEditorPart getCompareEditor(CompareEditorInput input) { } /** - * Close the compare editor for the given file if it is open. + * Closes the compare editor for the given changed file if it is open. * - * @param file The file to check. - * @return true if the compare editor is open, false otherwise. + * @param file The changed file to check. */ - protected void closeCompareEditor(IFile file) { + protected void closeCompareEditor(ChangedFile file) { CompareEditorInput input = compareEditorInputMap.get(file); if (input != null) { SwtUtils.invokeOnDisplayThread(() -> { @@ -262,70 +265,137 @@ protected void closeCompareEditor(IFile file) { compareEditorInputMap.remove(file); } - private CompareEditorInput createCompareEditorInput(String comparedContent, IFile file) { - // Create a new CompareConfiguration - CompareConfiguration config = new CompareConfiguration(); - config.setLeftLabel(Messages.agent_tool_compareEditor_proposedChangesTitle.replaceAll("\"", "")); - config.setRightLabel(file.getName()); + /** + * Brings the compare editor for a changed file to the top if it is open. + * + * @param file The changed file whose compare editor should be shown. + * @return true if an open compare editor was found, false otherwise. + */ + protected boolean bringCompareEditorToTopIfOpen(ChangedFile file) { + CompareEditorInput input = compareEditorInputMap.get(file); + if (input == null) { + return false; + } + if (isCompareEditorOpen(input)) { + bringCompareEditorToTop(input); + return true; + } + compareEditorInputMap.remove(file); + return false; + } - // Enable editing on the proposed changes side and disable it on the original file side. Eclipse's original side - // and - // changes side are swapped, so we need to set the left side as editable to edit the proposed changes. - config.setLeftEditable(true); - config.setRightEditable(false); + /** + * Normalizes a local path for cache and map lookups. + * + * @param file the local file path + * @return the normalized absolute path + */ + protected Path normalizeLocalPath(Path file) { + return file.toAbsolutePath().normalize(); + } - // Set up the configuration to properly show differences - config.setProperty(CompareConfiguration.USE_OUTLINE_VIEW, Boolean.TRUE); - config.setProperty(CompareConfiguration.SHOW_PSEUDO_CONFLICTS, Boolean.TRUE); - config.setProperty(CompareConfiguration.IGNORE_WHITESPACE, Boolean.FALSE); + + + private CompareEditorInput createWorkspaceCompareEditorInput(String comparedContent, IFile file) { + ChangedFile changedFile = ChangedFile.workspace(file); + EditableFileCompareInput originalFile = new EditableFileCompareInput(file); + return createCompareEditorInputForTarget(comparedContent, originalFile.getName(), originalFile.getType(), + PlatformUtils.getFileCharset(file), () -> originalFile, (diffNode, monitor) -> { + EditableFileCompareInput inputToBeApplied = (EditableFileCompareInput) diffNode.getLeft(); + try (InputStream inputStream = inputToBeApplied.getContents()) { + file.setContents(inputStream, true, true, monitor); + } catch (IOException e) { + CopilotCore.LOGGER.error("Error saving compare editor changes to file", e); + } + CopilotUi.getPlugin().getChatServiceManager().getFileToolService().completeFile(changedFile); + removeCachedFileContent(changedFile); + }); + } + + private CompareEditorInput createLocalCompareEditorInput(String comparedContent, Path file) { + Path normalizedPath = normalizeLocalPath(file); + ChangedFile changedFile = ChangedFile.local(normalizedPath); + EditableFileCompareInput originalFile = new EditableFileCompareInput(normalizedPath); + return createCompareEditorInputForTarget(comparedContent, originalFile.getName(), originalFile.getType(), + StandardCharsets.UTF_8.name(), () -> originalFile, + (diffNode, monitor) -> { + EditableFileCompareInput inputToBeApplied = (EditableFileCompareInput) diffNode.getLeft(); + try (InputStream inputStream = inputToBeApplied.getContents()) { + Files.write(normalizedPath, inputStream.readAllBytes()); + } catch (IOException e) { + CopilotCore.LOGGER.error("Error saving compare editor changes to local file", e); + } + CopilotUi.getPlugin().getChatServiceManager().getFileToolService().completeFile(changedFile); + removeCachedFileContent(changedFile); + }); + } + + private CompareEditorInput createCompareEditorInput(String comparedContent, ChangedFile file) { + if (file.isWorkspaceFile()) { + return createWorkspaceCompareEditorInput(comparedContent, file.getWorkspaceFile()); + } + return createLocalCompareEditorInput(comparedContent, file.getLocalPath()); + } + + private CompareEditorInput createCompareEditorInputForTarget(String comparedContent, String fileName, + String fileExtension, String charset, Supplier originalFileSupplier, + CompareContentSaver contentSaver) { + CompareConfiguration config = createCompareConfiguration(fileName); return new CompareEditorInput(config) { @Override protected Object prepareInput(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask("Calculating differences", 10); - setTitle(Messages.agent_tool_compareEditor_titlePrefix + file.getName()); - // Keep proposedChanges virtual file's name and type same as the originalFile original file's name and type - EditableStringCompareInput proposedChanges = new EditableStringCompareInput(comparedContent, file.getName(), - file.getFileExtension(), PlatformUtils.getFileCharset(file)); - EditableFileCompareInput originalFile = new EditableFileCompareInput(file); - - // Create a diff node with proper configuration for text comparison - DiffNode diffNode = new DiffNode(null, Differencer.CHANGE, null, originalFile, proposedChanges); - + setTitle(Messages.agent_tool_compareEditor_titlePrefix + fileName); + EditableStringCompareInput proposedChanges = new EditableStringCompareInput(comparedContent, fileName, + fileExtension, charset); + DiffNode diffNode = new DiffNode(null, Differencer.CHANGE, null, originalFileSupplier.get(), proposedChanges); monitor.done(); return diffNode; } @Override public void saveChanges(IProgressMonitor monitor) throws CoreException { - // We need to set the right side as editable to save the changes made to the proposed changes. Otherwise, the - // changes won't be saved. if (isDirty()) { config.setRightEditable(true); super.saveChanges(monitor); - // Get the diff node which contains the comparison inputs DiffNode diffNode = (DiffNode) getCompareResult(); if (diffNode != null) { - // Get the right side input (the original file with any edits made) - EditableFileCompareInput inputToBeApplied = (EditableFileCompareInput) diffNode.getLeft(); - - // Save the modified content back to the file - try (InputStream inputStream = inputToBeApplied.getContents()) { - file.setContents(inputStream, true, true, monitor); - } catch (IOException e) { - CopilotCore.LOGGER.error("Error saving compare editor changes to file", e); - } + contentSaver.save(diffNode, monitor); } - - // If user keeps the changes with keyboard shortcut, we also need to complete the file. - CopilotUi.getPlugin().getChatServiceManager().getFileToolService().completeFile(file); - fileContentCache.remove(file); } } }; } + private CompareConfiguration createCompareConfiguration(String rightLabel) { + CompareConfiguration config = new CompareConfiguration(); + config.setLeftLabel(Messages.agent_tool_compareEditor_proposedChangesTitle.replaceAll("\"", "")); + config.setRightLabel(rightLabel); + config.setLeftEditable(true); + config.setRightEditable(false); + config.setProperty(CompareConfiguration.USE_OUTLINE_VIEW, Boolean.TRUE); + config.setProperty(CompareConfiguration.SHOW_PSEUDO_CONFLICTS, Boolean.TRUE); + config.setProperty(CompareConfiguration.IGNORE_WHITESPACE, Boolean.FALSE); + return config; + } + + /** + * Saves the editable compare content back to the target file type. + */ + @FunctionalInterface + private interface CompareContentSaver { + /** + * Saves the edited content represented by a compare diff node. + * + * @param diffNode The diff node containing the editable compare inputs. + * @param monitor The progress monitor for the save operation. + * @throws CoreException if saving through Eclipse APIs fails. + */ + void save(DiffNode diffNode, IProgressMonitor monitor) throws CoreException; + } + /** * Dispose the file change summary bar and related resources. */ @@ -342,8 +412,10 @@ protected void dispose() { /** * Editable file compare input class to handle file content editing on the compare editor. */ - public class EditableFileCompareInput implements ITypedElement, IEncodedStreamContentAccessor, IEditableContent { - private IFile file; + public static final class EditableFileCompareInput implements ITypedElement, IEncodedStreamContentAccessor, + IEditableContent { + private final IFile workspaceFile; + private final Path localFile; private byte[] modifiedContent = null; /** @@ -352,12 +424,27 @@ public class EditableFileCompareInput implements ITypedElement, IEncodedStreamCo * @param file The file to be edited. */ public EditableFileCompareInput(IFile file) { - this.file = file; + this.workspaceFile = file; + this.localFile = null; + } + + /** + * Constructor for EditableFileCompareInput. + * + * @param file The local file to be edited. + */ + EditableFileCompareInput(Path file) { + this.workspaceFile = null; + this.localFile = file.toAbsolutePath().normalize(); } @Override public String getName() { - return file.getName(); + if (workspaceFile != null) { + return workspaceFile.getName(); + } + Path fileName = localFile.getFileName(); + return fileName == null ? localFile.toString() : fileName.toString(); } @Override @@ -367,11 +454,19 @@ public Image getImage() { @Override public String getType() { - return file.getFileExtension(); + if (workspaceFile != null) { + return workspaceFile.getFileExtension(); + } + return getLocalFileExtension(localFile); } + /** + * Gets the workspace file represented by this compare input. + * + * @return the workspace file + */ public IFile getFile() { - return file; + return workspaceFile; } @Override @@ -379,12 +474,19 @@ public InputStream getContents() throws CoreException { if (modifiedContent != null) { return new ByteArrayInputStream(modifiedContent); } - return file.getContents(); + if (workspaceFile != null) { + return workspaceFile.getContents(); + } + try { + return Files.newInputStream(localFile); + } catch (IOException e) { + throw new CoreException(Status.error("Error reading local file", e)); + } } @Override public String getCharset() throws CoreException { - return file.getCharset(); + return workspaceFile == null ? StandardCharsets.UTF_8.name() : workspaceFile.getCharset(); } @Override @@ -401,7 +503,6 @@ public void setContent(byte[] newContent) { public ITypedElement replace(ITypedElement dest, ITypedElement src) { if (src instanceof IStreamContentAccessor sca) { try (InputStream is = sca.getContents()) { - // Just store changes in memory modifiedContent = is.readAllBytes(); } catch (IOException | CoreException e) { CopilotCore.LOGGER.error("Error occurred while replacing file content", e); @@ -409,6 +510,15 @@ public ITypedElement replace(ITypedElement dest, ITypedElement src) { } return this; } + + private static String getLocalFileExtension(Path file) { + String name = file.getFileName() == null ? file.toString() : file.getFileName().toString(); + int index = name.lastIndexOf('.'); + if (index < 0 || index == name.length() - 1) { + return ""; + } + return name.substring(index + 1); + } } /** diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/FileToolService.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/FileToolService.java index 1e57daa9..151cf791 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/FileToolService.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/FileToolService.java @@ -6,13 +6,11 @@ import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; -import java.util.List; import java.util.Map; import org.eclipse.core.databinding.observable.sideeffect.ISideEffect; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.WritableValue; -import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.e4.core.services.events.IEventBroker; import org.eclipse.lsp4j.FileChangeType; @@ -35,7 +33,7 @@ * the files to be created or edited and the enable state of the button. */ public class FileToolService extends ChatBaseService { - private IObservableValue> filesObservable; + private IObservableValue> filesObservable; private IObservableValue buttonEnableObservable; private WorkingSetBar workingSetBar; @@ -78,7 +76,7 @@ public void bindWorkingSetBar(ChatView chatView) { ensureRealm(() -> { unbindWorkingSetBar(); filesSideEffect = ISideEffect.create(() -> filesObservable.getValue(), - (Map filesMap) -> { + (Map filesMap) -> { if (filesMap.isEmpty()) { disposeWorkingSetBar(); } else { @@ -154,7 +152,7 @@ public void setWorkingSetBarButtonStatus(boolean status) { /** * Set the changed files for the working set bar. */ - public void setChangedFiles(Map files) { + public void setChangedFiles(Map files) { ensureRealm(() -> { filesObservable.setValue(files); }); @@ -163,7 +161,7 @@ public void setChangedFiles(Map files) { /** * Get the changed files for the working set bar. */ - public Map getChangedFiles() { + public Map getChangedFiles() { return filesObservable.getValue(); } @@ -175,11 +173,11 @@ public WorkingSetBar getWorkingSetBar() { } /** - * Add a newly created file to the working set bar. + * Add a changed file to the working set bar. */ - public void addChangedFile(IFile file, FileChangeType fileChangeType) { + public void addChangedFile(ChangedFile file, FileChangeType fileChangeType) { ensureRealm(() -> { - Map filesMap = new LinkedHashMap<>(filesObservable.getValue()); + Map filesMap = new LinkedHashMap<>(filesObservable.getValue()); if (filesMap.containsKey(file)) { return; } @@ -194,9 +192,9 @@ public void addChangedFile(IFile file, FileChangeType fileChangeType) { * * @param file the file to complete */ - public void completeFile(IFile file) { + public void completeFile(ChangedFile file) { ensureRealm(() -> { - Map filesMap = new LinkedHashMap<>(filesObservable.getValue()); + Map filesMap = new LinkedHashMap<>(filesObservable.getValue()); filesMap.remove(file); filesObservable.setValue(filesMap); @@ -212,7 +210,7 @@ public void completeFile(IFile file) { * @param file the file to get the change type for * @return the file change type, or null if the file is not in the list */ - public FileChangeType getFileChangeTypeOf(IFile file) { + private FileChangeType getFileChangeTypeInternal(ChangedFile file) { FileChangeProperty property = filesObservable.getValue().get(file); if (property != null) { return property.getChangeType(); @@ -226,10 +224,10 @@ public FileChangeType getFileChangeTypeOf(IFile file) { * * @param file the file to keep changes for */ - public void onKeepChange(IFile file) { - if (getFileChangeTypeOf(file) == FileChangeType.Created) { + public void onKeepChange(ChangedFile file) { + if (getFileChangeTypeInternal(file) == FileChangeType.Created) { this.createFileTool.onKeepChange(file); - } else if (getFileChangeTypeOf(file) == FileChangeType.Changed) { + } else if (getFileChangeTypeInternal(file) == FileChangeType.Changed) { this.editFileTool.onKeepChange(file); } this.completeFile(file); @@ -239,8 +237,13 @@ public void onKeepChange(IFile file) { * Handles the action of keeping all changes to files. */ public void onKeepAllChanges() { - this.createFileTool.onKeepAllChanges(getCreatedFiles()); - this.editFileTool.onKeepAllChanges(getEditedFiles()); + for (ChangedFile file : new ArrayList<>(filesObservable.getValue().keySet())) { + if (getFileChangeTypeInternal(file) == FileChangeType.Created) { + this.createFileTool.onKeepChange(file); + } else if (getFileChangeTypeInternal(file) == FileChangeType.Changed) { + this.editFileTool.onKeepChange(file); + } + } onResolveAllChanges(); } @@ -249,11 +252,11 @@ public void onKeepAllChanges() { * * @param file the file to undo changes for */ - public void onUndoChange(IFile file) { + public void onUndoChange(ChangedFile file) { try { - if (getFileChangeTypeOf(file) == FileChangeType.Created) { + if (getFileChangeTypeInternal(file) == FileChangeType.Created) { this.createFileTool.onUndoChange(file); - } else if (getFileChangeTypeOf(file) == FileChangeType.Changed) { + } else if (getFileChangeTypeInternal(file) == FileChangeType.Changed) { this.editFileTool.onUndoChange(file); } } catch (CoreException | IOException e) { @@ -267,8 +270,13 @@ public void onUndoChange(IFile file) { */ public void onUndoAllChanges() { try { - this.createFileTool.onUndoAllChanges(getCreatedFiles()); - this.editFileTool.onUndoAllChanges(getEditedFiles()); + for (ChangedFile file : new ArrayList<>(filesObservable.getValue().keySet())) { + if (getFileChangeTypeInternal(file) == FileChangeType.Created) { + this.createFileTool.onUndoChange(file); + } else if (getFileChangeTypeInternal(file) == FileChangeType.Changed) { + this.editFileTool.onUndoChange(file); + } + } } catch (CoreException | IOException e) { CopilotCore.LOGGER.error("Error undoing all changes for the files", e); } @@ -280,10 +288,14 @@ public void onUndoAllChanges() { * * @param file the file to view the diff for */ - public void onViewDiff(IFile file) { - if (getFileChangeTypeOf(file) == FileChangeType.Created) { + public void onViewDiff(ChangedFile file) { + FileChangeProperty property = filesObservable.getValue().get(file); + if (property == null) { + return; + } + if (property.getChangeType() == FileChangeType.Created) { this.createFileTool.onViewDiff(file); - } else if (getFileChangeTypeOf(file) == FileChangeType.Changed) { + } else if (property.getChangeType() == FileChangeType.Changed) { this.editFileTool.onViewDiff(file); } } @@ -313,29 +325,8 @@ public void disposeWorkingSetBar() { } } - private List getCreatedFiles() { - List createdFiles = new ArrayList<>(); - for (Map.Entry entry : this.filesObservable.getValue().entrySet()) { - if (entry.getValue().getChangeType() == FileChangeType.Created) { - createdFiles.add(entry.getKey()); - } - } - return createdFiles; - } - - private List getEditedFiles() { - List editedFiles = new ArrayList<>(); - for (Map.Entry entry : this.filesObservable.getValue().entrySet()) { - if (entry.getValue().getChangeType() == FileChangeType.Changed) { - editedFiles.add(entry.getKey()); - } - } - return editedFiles; - } - /** - * Class for file change properties. changeType - The type of file change (new or edited). isCompleted - Whether the - * file change is completed or not. + * Class for file change properties. */ public static class FileChangeProperty { private FileChangeType changeType; diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/RunInTerminalToolAdapter.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/RunInTerminalToolAdapter.java index 085d4913..2bfbdc11 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/RunInTerminalToolAdapter.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/RunInTerminalToolAdapter.java @@ -3,12 +3,17 @@ package com.microsoft.copilot.eclipse.ui.chat.tools; +import java.io.File; +import java.net.URI; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import org.apache.commons.lang3.StringUtils; +import org.eclipse.core.resources.IResource; +import org.eclipse.lsp4j.WorkspaceFolder; import com.microsoft.copilot.eclipse.core.lsp.protocol.ConfirmationMessages; import com.microsoft.copilot.eclipse.core.lsp.protocol.InputSchema; @@ -18,8 +23,13 @@ import com.microsoft.copilot.eclipse.core.lsp.protocol.LanguageModelToolResult.ToolInvocationStatus; import com.microsoft.copilot.eclipse.core.utils.PlatformUtils; import com.microsoft.copilot.eclipse.terminal.api.IRunInTerminalTool; +import com.microsoft.copilot.eclipse.terminal.api.TerminalCommandProcessor; import com.microsoft.copilot.eclipse.terminal.api.TerminalServiceManager; +import com.microsoft.copilot.eclipse.ui.CopilotUi; import com.microsoft.copilot.eclipse.ui.chat.ChatView; +import com.microsoft.copilot.eclipse.ui.chat.services.ChatServiceManager; +import com.microsoft.copilot.eclipse.ui.chat.services.ReferencedFileService; +import com.microsoft.copilot.eclipse.ui.utils.ResourceUtils; import com.microsoft.copilot.eclipse.ui.utils.UiUtils; /** @@ -38,18 +48,22 @@ public RunInTerminalToolAdapter() { private String buildToolDescription() { if (PlatformUtils.isWindows()) { return """ - Shell: cmd.exe + Shell: powershell.exe - This tool allows you to execute Windows Command Prompt commands in a persistent terminal session, \ + This tool allows you to execute PowerShell commands in a persistent terminal session, \ preserving environment variables, working directory, and other context across multiple commands. Use this tool instead of printing a shell codeblock and asking the user to run it. Command Execution: - - Use & to chain commands on one line (or && for conditional execution on success) - - Never create a sub-shell (e.g., cmd /c "command") unless explicitly asked - - Use pipelines | for data flow + - Use ; to chain commands on one line + - Never create a sub-shell (e.g., powershell -c "command") unless explicitly asked + - Prefer pipelines | for object-based data flow + - Multi-line commands must be complete and non-interactive. Do not run REPLs, continuation-prompt commands, + unmatched quotes or brackets, or commands that wait for stdin. For Python/Node scripts, create a file first, + then run it - Must use absolute paths to avoid navigation issues - If a command may use a pager, disable it with command flags (e.g., `git --no-pager`) + - Output returned to the model is automatically truncated to the last 1000 lines to prevent context overflow Background Processes: - For long-running tasks (e.g., servers), set isBackground=true @@ -58,19 +72,23 @@ private String buildToolDescription() { } if (PlatformUtils.isLinux()) { return """ - Shell: /bin/sh (POSIX shell) + Shell: /bin/bash - This tool allows you to execute POSIX shell commands in a persistent terminal session, \ + This tool allows you to execute Bash commands in a persistent terminal session, \ preserving environment variables, working directory, and other context across multiple commands. Use this tool instead of printing a shell codeblock and asking the user to run it. Command Execution: - - Use ; to chain commands on one line (or && for conditional execution on success) - - Never create a sub-shell (e.g., sh -c "command") unless explicitly asked + - Use && to chain commands on one line + - Never create a sub-shell (e.g., bash -c "command") unless explicitly asked - Prefer pipelines | for data flow + - Multi-line commands must be complete and non-interactive. Do not run REPLs, continuation-prompt commands, + unmatched quotes or brackets, or commands that wait for stdin. For Python/Node scripts, create a file first, + then run it - Must use absolute paths to avoid navigation issues - If a command may use a pager, disable it (e.g., `git --no-pager` or add `| cat`) - - Use POSIX-compliant syntax (avoid bash-specific features like arrays or [[ ]]) + - Bash syntax is supported, including arrays and [[ ]] + - Output returned to the model is automatically truncated to the last 1000 lines to prevent context overflow Background Processes: - For long-running tasks (e.g., servers), set isBackground=true @@ -87,8 +105,12 @@ private String buildToolDescription() { - Use && to chain commands on one line - Never create a sub-shell (e.g., bash -c "command") unless explicitly asked - Prefer pipelines | for data flow + - Multi-line commands must be complete and non-interactive. Do not run REPLs, continuation-prompt commands, + unmatched quotes or brackets, or commands that wait for stdin. For Python/Node scripts, create a file first, + then run it - Must use absolute paths to avoid navigation issues - If a command may use a pager, disable it (e.g., `git --no-pager` or add `| cat`) + - Output returned to the model is automatically truncated to the last 1000 lines to prevent context overflow Background Processes: - For long-running tasks (e.g., servers), set isBackground=true @@ -178,13 +200,55 @@ public CompletableFuture invoke(Map i } impl.setTerminalIconDescriptor(UiUtils.buildImageDescriptorFromPngPath("/icons/github_copilot.png")); + String workingDirectory = resolveWorkingDirectory(); - return impl.executeCommand(command, isBackground).thenApply( - result -> new LanguageModelToolResult[] { new LanguageModelToolResult(result, ToolInvocationStatus.success) }) + return impl.executeCommand(command, isBackground, workingDirectory) + .thenApply(result -> new LanguageModelToolResult[] { new LanguageModelToolResult( + TerminalCommandProcessor.prepareOutputForModel(result), ToolInvocationStatus.success) }) .exceptionally(throwable -> new LanguageModelToolResult[] { new LanguageModelToolResult( "Terminal execution failed: " + throwable.getMessage(), ToolInvocationStatus.error) }); } + static String resolveWorkingDirectoryFromResources(List resources) { + return ResourceUtils.deriveWorkspaceFoldersFrom(resources).stream() + .findFirst() + .map(RunInTerminalToolAdapter::toLocalPath) + .orElse(""); + } + + private static String resolveWorkingDirectory() { + ChatServiceManager manager = CopilotUi.getPlugin() != null ? CopilotUi.getPlugin().getChatServiceManager() : null; + if (manager != null) { + ReferencedFileService fileService = manager.getReferencedFileService(); + if (fileService != null) { + List resources = new ArrayList<>(); + if (fileService.getCurrentFile() != null) { + resources.add(fileService.getCurrentFile()); + } + if (fileService.getReferencedFiles() != null) { + resources.addAll(fileService.getReferencedFiles()); + } + String referencedLocation = resolveWorkingDirectoryFromResources(resources); + if (StringUtils.isNotBlank(referencedLocation)) { + return referencedLocation; + } + } + } + + return ""; + } + + private static String toLocalPath(WorkspaceFolder workspaceFolder) { + if (workspaceFolder == null || StringUtils.isBlank(workspaceFolder.getUri())) { + return ""; + } + try { + return new File(URI.create(workspaceFolder.getUri())).getPath(); + } catch (IllegalArgumentException e) { + return ""; + } + } + /** * Tool to retrieve the output of a terminal command that was previously started with run_in_terminal. */ @@ -204,7 +268,10 @@ public LanguageModelToolInformation getToolInformation() { // Set the name and description of the tool toolInfo.setName(TOOL_NAME); - toolInfo.setDescription("Get the output of a terminal command previous started with run_in_terminal."); + toolInfo.setDescription(""" + Get the output of a terminal command previously started with run_in_terminal. + Output returned to the model is automatically truncated to the last 1000 lines to prevent context overflow. + """); // Define the input schema for the tool InputSchema inputSchema = new InputSchema(); @@ -247,7 +314,7 @@ public CompletableFuture invoke(Map i toolResult.addContent("Invalid terminal ID " + id); } else { toolResult.setStatus(ToolInvocationStatus.success); - toolResult.addContent(output.toString()); + toolResult.addContent(TerminalCommandProcessor.prepareOutputForModel(output.toString())); } } resultFuture.complete(new LanguageModelToolResult[] { toolResult }); diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/WorkingSetHandler.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/WorkingSetHandler.java index c7619f7f..7176e9e2 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/WorkingSetHandler.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/tools/WorkingSetHandler.java @@ -4,9 +4,7 @@ package com.microsoft.copilot.eclipse.ui.chat.tools; import java.io.IOException; -import java.util.List; -import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; /** @@ -18,12 +16,7 @@ public interface WorkingSetHandler { * * @param file the file to keep changes for */ - void onKeepChange(IFile file) throws IOException, CoreException; - - /** - * Handles the action of keeping all changes to files. - */ - void onKeepAllChanges(List files) throws IOException, CoreException; + void onKeepChange(ChangedFile file) throws IOException, CoreException; /** * Handles the action of undoing changes to a file. @@ -33,22 +26,14 @@ public interface WorkingSetHandler { * @throws CoreException if an error occurs during the undo operation, such as a failure to delete a file * @throws IOException if an error occurs while writing to the file */ - void onUndoChange(IFile file) throws CoreException, IOException; - - /** - * Handles the action of undoing all changes to files. - * - * @throws CoreException if error occurs during the undo all operation, such as a failure to delete a file - * @throws IOException if an error occurs while writing to the file - */ - void onUndoAllChanges(List files) throws CoreException, IOException; + void onUndoChange(ChangedFile file) throws CoreException, IOException; /** * Handles the action of viewing the diff of a file. * * @param file the file to view the diff for */ - void onViewDiff(IFile file); + void onViewDiff(ChangedFile file); /** * Handles the action of click done button to resolve all changes. diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/dialogs/mcp/McpServerItem.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/dialogs/mcp/McpServerItem.java index f59f74ec..2c15179e 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/dialogs/mcp/McpServerItem.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/dialogs/mcp/McpServerItem.java @@ -45,6 +45,7 @@ import com.microsoft.copilot.eclipse.ui.dialogs.mcp.McpServerInstallManager.ActionType; import com.microsoft.copilot.eclipse.ui.dialogs.mcp.McpServerInstallManager.ButtonState; import com.microsoft.copilot.eclipse.ui.swt.CssConstants; +import com.microsoft.copilot.eclipse.ui.swt.SplitDropdownButton; import com.microsoft.copilot.eclipse.ui.utils.McpUtils; import com.microsoft.copilot.eclipse.ui.utils.UiUtils; @@ -301,15 +302,17 @@ public void widgetSelected(SelectionEvent e) { disabledInstallButton.setToolTipText(Messages.mcpServerItem_noInstallOptions); actionButton = disabledInstallButton; } else { - DropDownButton dropDownInstallButton = createDropDownInstallButton(actionComposite, initialState, + SplitDropdownButton dropDownInstallButton = createDropDownInstallButton(actionComposite, initialState, installOptions); actionButton = dropDownInstallButton.getButton(); } } } - private DropDownButton createDropDownInstallButton(Composite parent, ButtonState state, List options) { - DropDownButton dropDownInstallButton = new DropDownButton(parent, SWT.NONE); + private SplitDropdownButton createDropDownInstallButton( + Composite parent, ButtonState state, + List options) { + SplitDropdownButton dropDownInstallButton = new SplitDropdownButton(parent, SWT.NONE); dropDownInstallButton.setShowArrow(options.size() > 1); dropDownInstallButton.setText(state.getText()); diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/i18n/Messages.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/i18n/Messages.java index 1aef96fc..642b71b1 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/i18n/Messages.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/i18n/Messages.java @@ -199,10 +199,11 @@ public final class Messages extends NLS { public static String model_billing_multiplier_suffix; public static String model_billing_multiplier_variable; public static String model_preview_suffix; - public static String model_hover_contextSize; + public static String model_hover_contextWindow; public static String model_hover_cost; public static String model_hover_thinkingEffort; public static String model_hover_thinkingEffort_default_suffix; + public static String model_hover_customModelInfo; public static String model_reasoningEffort_none; public static String model_reasoningEffort_low; public static String model_reasoningEffort_medium; @@ -224,6 +225,7 @@ public final class Messages extends NLS { public static String context_window_messages; public static String context_window_files; public static String context_window_tool_results; + public static String chat_compacting_conversation; public static String chat_rateLimitBanner_getMoreInfo; public static String chat_rateLimitBanner_closeTooltip; diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/i18n/messages.properties b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/i18n/messages.properties index 4cb8235e..bb6b4400 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/i18n/messages.properties +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/i18n/messages.properties @@ -193,10 +193,11 @@ generateCommitMessage_noStagedFiles_message=There are no staged files to generat addToReference_addFile_title=Add File to Chat addToReference_addFolder_title=Add Folder to Chat -model_hover_contextSize=Context Size: +model_hover_contextWindow=Context Window: model_hover_cost=Cost: model_hover_thinkingEffort=Thinking Effort model_hover_thinkingEffort_default_suffix={0} (default) +model_hover_customModelInfo={0} is contributed by {1} using {2} model_reasoningEffort_none=None model_reasoningEffort_low=Low model_reasoningEffort_medium=Medium @@ -218,6 +219,7 @@ context_window_user_context=User Context context_window_messages=Messages context_window_files=Attached Files context_window_tool_results=Tool Results +chat_compacting_conversation=Compacting conversation... chat_rateLimitBanner_getMoreInfo=Get more info chat_rateLimitBanner_closeTooltip=Dismiss diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/AddFileOperationRuleDialog.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/AddFileOperationRuleDialog.java new file mode 100644 index 00000000..cbaa82c1 --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/AddFileOperationRuleDialog.java @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.preferences; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; + +/** + * Dialog for adding a file-operation auto-approve rule with pattern, description, and allow/deny. + */ +public class AddFileOperationRuleDialog extends Dialog { + + private Text patternText; + private Text descriptionText; + private Button allowRadio; + + private String pattern; + private String description; + private boolean autoApprove; + + /** + * Creates the dialog. + * + * @param parent the parent shell + */ + public AddFileOperationRuleDialog(Shell parent) { + super(parent); + } + + @Override + protected void configureShell(Shell shell) { + super.configureShell(shell); + shell.setText( + Messages.preferences_page_file_op_auto_approve_add_dialog_title); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite area = (Composite) super.createDialogArea(parent); + Composite container = new Composite(area, SWT.NONE); + container.setLayout(new GridLayout(2, false)); + container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + // Pattern * + Label patternLabel = new Label(container, SWT.NONE); + patternLabel.setText( + Messages.preferences_page_file_op_auto_approve_add_dialog_pattern + + " *"); + patternText = new Text(container, SWT.BORDER); + GridData patternData = new GridData(SWT.FILL, SWT.CENTER, true, false); + patternData.widthHint = 300; + patternText.setLayoutData(patternData); + patternText.setMessage( + Messages.preferences_page_file_op_auto_approve_add_dialog_pattern_hint); + patternText.addModifyListener(e -> updateOkButton()); + + // Description + Label descLabel = new Label(container, SWT.NONE); + descLabel.setText( + Messages.preferences_page_file_op_auto_approve_add_dialog_description); + descriptionText = new Text(container, SWT.BORDER); + descriptionText.setMessage( + Messages.preferences_page_file_op_auto_approve_add_dialog_description_hint); + descriptionText.setLayoutData( + new GridData(SWT.FILL, SWT.CENTER, true, false)); + + // Allow / Deny + Label approveLabel = new Label(container, SWT.NONE); + approveLabel.setText( + Messages.preferences_page_auto_approve_add_dialog_approve); + Composite radioGroup = new Composite(container, SWT.NONE); + radioGroup.setLayout(new GridLayout(2, false)); + allowRadio = new Button(radioGroup, SWT.RADIO); + allowRadio.setText(Messages.preferences_page_auto_approve_allow); + allowRadio.setSelection(true); + Button denyRadio = new Button(radioGroup, SWT.RADIO); + denyRadio.setText(Messages.preferences_page_auto_approve_deny); + + return area; + } + + @Override + protected void createButtonsForButtonBar(Composite parent) { + super.createButtonsForButtonBar(parent); + updateOkButton(); + } + + private void updateOkButton() { + Button ok = getButton(OK); + if (ok != null) { + ok.setEnabled( + patternText != null && !patternText.getText().trim().isEmpty()); + } + } + + @Override + protected void okPressed() { + pattern = patternText.getText().trim(); + description = descriptionText.getText().trim(); + autoApprove = allowRadio.getSelection(); + super.okPressed(); + } + + public String getPattern() { + return pattern; + } + + public String getDescription() { + return description; + } + + public boolean isAutoApprove() { + return autoApprove; + } +} diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/AddTerminalRuleDialog.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/AddTerminalRuleDialog.java new file mode 100644 index 00000000..aa4af5de --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/AddTerminalRuleDialog.java @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.preferences; + +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; + +/** + * Dialog for adding a terminal auto-approve rule with command and allow/deny. + */ +public class AddTerminalRuleDialog extends Dialog { + + private Text commandText; + private Button allowRadio; + + private String command; + private boolean autoApprove; + + /** + * Creates the dialog. + * + * @param parent the parent shell + */ + public AddTerminalRuleDialog(Shell parent) { + super(parent); + } + + @Override + protected void configureShell(Shell shell) { + super.configureShell(shell); + shell.setText(Messages.preferences_page_terminal_auto_approve_add_dialog_title); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite area = (Composite) super.createDialogArea(parent); + Composite container = new Composite(area, SWT.NONE); + container.setLayout(new GridLayout(2, false)); + container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + // Command * + Label commandLabel = new Label(container, SWT.NONE); + commandLabel.setText( + Messages.preferences_page_terminal_auto_approve_add_dialog_command + " *"); + commandText = new Text(container, SWT.BORDER); + GridData commandData = new GridData(SWT.FILL, SWT.CENTER, true, false); + commandData.widthHint = 300; + commandText.setLayoutData(commandData); + commandText.setMessage(Messages.preferences_page_terminal_auto_approve_add_dialog_placeholder); + commandText.addModifyListener(e -> updateOkButton()); + + // Allow / Deny + Label approveLabel = new Label(container, SWT.NONE); + approveLabel.setText( + Messages.preferences_page_auto_approve_add_dialog_approve); + Composite radioGroup = new Composite(container, SWT.NONE); + radioGroup.setLayout(new GridLayout(2, false)); + allowRadio = new Button(radioGroup, SWT.RADIO); + allowRadio.setText(Messages.preferences_page_auto_approve_allow); + allowRadio.setSelection(true); + Button denyRadio = new Button(radioGroup, SWT.RADIO); + denyRadio.setText(Messages.preferences_page_auto_approve_deny); + + return area; + } + + @Override + protected void createButtonsForButtonBar(Composite parent) { + super.createButtonsForButtonBar(parent); + updateOkButton(); + } + + private void updateOkButton() { + Button ok = getButton(OK); + if (ok != null) { + ok.setEnabled(commandText != null && !commandText.getText().trim().isEmpty()); + } + } + + @Override + protected void okPressed() { + command = commandText.getText().trim(); + autoApprove = allowRadio.getSelection(); + super.okPressed(); + } + + public String getCommand() { + return command; + } + + public boolean isAutoApprove() { + return autoApprove; + } +} diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/AutoApprovePreferencePage.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/AutoApprovePreferencePage.java new file mode 100644 index 00000000..fb0be2c0 --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/AutoApprovePreferencePage.java @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.preferences; + +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.ScrolledComposite; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.ui.ISharedImages; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; +import org.eclipse.ui.PlatformUI; + +import com.microsoft.copilot.eclipse.core.CopilotCore; +import com.microsoft.copilot.eclipse.core.FeatureFlags; +import com.microsoft.copilot.eclipse.ui.CopilotUi; +import com.microsoft.copilot.eclipse.ui.chat.services.ChatServiceManager; +import com.microsoft.copilot.eclipse.ui.chat.services.McpConfigService; + +/** + * Auto-Approve preference page for terminal and file operation auto-approval rules. + */ +public class AutoApprovePreferencePage extends PreferencePage + implements IWorkbenchPreferencePage { + + public static final String ID = + "com.microsoft.copilot.eclipse.ui.preferences.AutoApprovePreferencePage"; + + private TerminalAutoApproveSection terminalSection; + private FileOperationAutoApproveSection fileOperationSection; + private McpAutoApproveSection mcpSection; + private GlobalAutoApproveSection globalSection; + + @Override + public void init(IWorkbench workbench) { + setPreferenceStore(CopilotUi.getPlugin().getPreferenceStore()); + noDefaultAndApplyButton(); + } + + @Override + protected Control createContents(Composite parent) { + FeatureFlags flags = CopilotCore.getPlugin().getFeatureFlags(); + if (flags != null && !flags.isAutoApprovalEnabled()) { + return WrappableIconLink.createWithSharedImage(parent, + PlatformUI.getWorkbench().getSharedImages() + .getImage(ISharedImages.IMG_OBJS_INFO_TSK), + Messages.preferences_page_auto_approve_disabled_by_organization); + } + + // Wrap the sections in a height-capped ScrolledComposite. The override on + // computeSize bounds the height reported to the dialog's PageLayout so the + // Preferences shell stays stable; the real (taller) content scrolls here. + // This scroller is also the parent the section tables forward wheel events + // to (see forwardVerticalMouseWheelToParentScrollerAtBoundary). + ScrolledComposite scrolled = new ScrolledComposite(parent, SWT.V_SCROLL) { + @Override + public Point computeSize(int widthHint, int heightHint, boolean changed) { + Point size = super.computeSize(widthHint, heightHint, changed); + size.y = Math.min(size.y, PreferencePageUtils.STANDARD_CONTENT_HEIGHT); + return size; + } + }; + scrolled.setExpandHorizontal(true); + scrolled.setExpandVertical(true); + scrolled.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + + Composite root = new Composite(scrolled, SWT.NONE); + GridLayout layout = new GridLayout(1, false); + layout.marginWidth = 0; + layout.marginHeight = 0; + root.setLayout(layout); + + IPreferenceStore store = getPreferenceStore(); + terminalSection = new TerminalAutoApproveSection(root, SWT.NONE); + terminalSection.loadFromPreferences(store); + + fileOperationSection = new FileOperationAutoApproveSection(root, SWT.NONE); + fileOperationSection.loadFromPreferences(store); + + mcpSection = new McpAutoApproveSection(root, SWT.NONE); + mcpSection.loadFromPreferences(store); + bindMcpConfigService(); + + globalSection = new GlobalAutoApproveSection(root, SWT.NONE); + globalSection.loadFromPreferences(store); + + scrolled.setContent(root); + scrolled.setMinSize(root.computeSize(SWT.DEFAULT, SWT.DEFAULT)); + // Track width so wrapping labels reflow and only vertical scrolling occurs. + scrolled.addListener(SWT.Resize, e -> { + int width = scrolled.getClientArea().width; + scrolled.setMinSize(root.computeSize(width, SWT.DEFAULT)); + }); + + scrolled.addDisposeListener(e -> unbindMcpConfigService()); + + return scrolled; + } + + @Override + public boolean performOk() { + if (terminalSection == null) { + return true; + } + IPreferenceStore store = getPreferenceStore(); + terminalSection.saveToPreferences(store); + fileOperationSection.saveToPreferences(store); + mcpSection.saveToPreferences(store); + globalSection.saveToPreferences(store); + return true; + } + + private void bindMcpConfigService() { + ChatServiceManager chatServiceManager = + CopilotUi.getPlugin().getChatServiceManager(); + if (chatServiceManager != null) { + McpConfigService mcpConfigService = + chatServiceManager.getMcpConfigService(); + if (mcpConfigService != null) { + mcpConfigService.bindWithAutoApproveSection(mcpSection); + } + } + } + + private void unbindMcpConfigService() { + ChatServiceManager chatServiceManager = + CopilotUi.getPlugin().getChatServiceManager(); + if (chatServiceManager != null) { + McpConfigService mcpConfigService = + chatServiceManager.getMcpConfigService(); + if (mcpConfigService != null) { + mcpConfigService.unbindWithAutoApproveSection(); + } + } + } +} diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/CopilotPreferenceInitializer.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/CopilotPreferenceInitializer.java index 65d86abc..6b43717c 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/CopilotPreferenceInitializer.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/CopilotPreferenceInitializer.java @@ -3,6 +3,7 @@ package com.microsoft.copilot.eclipse.ui.preferences; +import com.google.gson.Gson; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.core.runtime.preferences.ConfigurationScope; import org.eclipse.core.runtime.preferences.IEclipsePreferences; @@ -11,6 +12,8 @@ import com.microsoft.copilot.eclipse.core.Constants; import com.microsoft.copilot.eclipse.core.chat.CustomInstructionsChatLoadScope; import com.microsoft.copilot.eclipse.ui.CopilotUi; +import com.microsoft.copilot.eclipse.ui.chat.confirmation.FileOperationConfirmationHandler; +import com.microsoft.copilot.eclipse.ui.chat.confirmation.TerminalConfirmationHandler; /** * A class to initialize the default preferences for the plugin. @@ -60,6 +63,18 @@ public void initializeDefaultPreferences() { """); pref.setDefault(Constants.MCP_TOOLS_STATUS, "{}"); + // Auto-approve defaults + pref.setDefault(Constants.AUTO_APPROVE_TERMINAL_RULES, + new Gson().toJson(TerminalConfirmationHandler.DEFAULT_RULES)); + pref.setDefault(Constants.AUTO_APPROVE_UNMATCHED_TERMINAL, false); + pref.setDefault(Constants.AUTO_APPROVE_FILE_OP_RULES, + new Gson().toJson(FileOperationConfirmationHandler.FALLBACK_DEFAULT_RULES)); + pref.setDefault(Constants.AUTO_APPROVE_UNMATCHED_FILE_OP, true); + pref.setDefault(Constants.AUTO_APPROVE_MCP_SERVERS, "[]"); + pref.setDefault(Constants.AUTO_APPROVE_MCP_TOOLS, "[]"); + pref.setDefault(Constants.AUTO_APPROVE_TRUST_TOOL_ANNOTATIONS, false); + pref.setDefault(Constants.AUTO_APPROVE_YOLO_MODE, false); + IEclipsePreferences configPrefs = ConfigurationScope.INSTANCE .getNode(CopilotUi.getPlugin().getBundle().getSymbolicName()); boolean autoShowWhatsNew = configPrefs.getBoolean(Constants.AUTO_SHOW_WHAT_IS_NEW, true); diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/CopilotPreferencesPage.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/CopilotPreferencesPage.java index 473c9313..a6e6da99 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/CopilotPreferencesPage.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/CopilotPreferencesPage.java @@ -38,6 +38,8 @@ protected Control createContents(Composite parent) { McpPreferencePage.ID); PreferencePageUtils.createPreferenceLink(getShell(), container, "Model Management", null, ByokPreferencePage.ID); + PreferencePageUtils.createPreferenceLink(getShell(), container, "Tool Auto Approve", null, + AutoApprovePreferencePage.ID); return container; } diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/CustomInstructionPreferencePage.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/CustomInstructionPreferencePage.java index 437d3aba..79b82234 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/CustomInstructionPreferencePage.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/CustomInstructionPreferencePage.java @@ -22,7 +22,6 @@ import org.eclipse.jface.text.ITextViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; @@ -269,18 +268,7 @@ private void createProjectInstructionsField(Composite parent, GridLayout gl) { // Set the file location column to take remaining width (table width - project name column width) fileLocationColumn.setWidth(tableGridData.widthHint > 0 ? tableGridData.widthHint - 150 : 400); - // Add resize listener to make the file location column take remaining width - table.addControlListener(new ControlAdapter() { - @Override - public void controlResized(org.eclipse.swt.events.ControlEvent e) { - int tableWidth = table.getClientArea().width; - int projectNameWidth = projectNameColumn.getWidth(); - int remainingWidth = tableWidth - projectNameWidth; - if (remainingWidth > 100) { // Minimum width for file location column - fileLocationColumn.setWidth(remainingWidth); - } - } - }); + SwtUtils.resizeColumnToFillTable(table, fileLocationColumn, 100, projectNameColumn); // Populate table with actual workspace projects populateProjectTable(table); diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/FileOperationAutoApproveSection.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/FileOperationAutoApproveSection.java new file mode 100644 index 00000000..c299d40a --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/FileOperationAutoApproveSection.java @@ -0,0 +1,499 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.preferences; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import org.apache.commons.lang3.StringUtils; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.viewers.ArrayContentProvider; +import org.eclipse.jface.viewers.ColumnLabelProvider; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.jface.viewers.TableViewerColumn; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Table; + +import com.microsoft.copilot.eclipse.core.Constants; +import com.microsoft.copilot.eclipse.core.CopilotCore; +import com.microsoft.copilot.eclipse.core.chat.FileOperationAutoApproveRule; +import com.microsoft.copilot.eclipse.core.lsp.CopilotLanguageServerConnection; +import com.microsoft.copilot.eclipse.core.lsp.protocol.FileSafetyRuleInfo; +import com.microsoft.copilot.eclipse.ui.chat.confirmation.FileOperationConfirmationHandler; +import com.microsoft.copilot.eclipse.ui.utils.SwtUtils; + +/** + * File-operation auto-approve section with a rule table, action buttons, and + * unmatched-file-operation checkbox. + * + *

Default rules are fetched from CLS asynchronously and merged with + * local fallback defaults + * ({@link FileOperationConfirmationHandler#FALLBACK_DEFAULT_RULES}). + * Default rules cannot be removed; only user-added rules can be removed.

+ */ +public class FileOperationAutoApproveSection extends Composite { + + private static final int TABLE_HEIGHT_HINT = 200; + private static final Type FILE_OP_RULES_TYPE = + new TypeToken>() {}.getType(); + + private TableViewer tableViewer; + private final List defaultRules = + new ArrayList<>(); + private final List userRules = + new ArrayList<>(); + /** Combined view (defaults + user) shown in the table. */ + private final List allRules = + new ArrayList<>(); + private boolean defaultRulesLoaded; + private Button removeButton; + private Button toggleButton; + private Button resetButton; + private Button unmatchedCheckbox; + + /** Creates the file-operation auto-approve section inside the given parent. */ + public FileOperationAutoApproveSection(Composite parent, int style) { + super(parent, style); + setLayout(new GridLayout(1, false)); + setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); + createContents(); + } + + private void createContents() { + Group group = new Group(this, SWT.NONE); + group.setText(Messages.preferences_page_file_op_auto_approve_title); + group.setLayout(new GridLayout(1, false)); + group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); + group.setBackgroundMode(SWT.INHERIT_FORCE); + + Label description = new Label(group, SWT.WRAP); + description.setText( + Messages.preferences_page_file_op_auto_approve_description); + GridData descData = new GridData(SWT.FILL, SWT.TOP, true, false); + descData.widthHint = 400; + description.setLayoutData(descData); + + Composite container = new Composite(group, SWT.NONE); + container.setLayout(new GridLayout(2, false)); + container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); + + createTable(container); + createButtons(container); + + unmatchedCheckbox = new Button(group, SWT.CHECK); + unmatchedCheckbox.setText( + Messages.preferences_page_file_op_auto_approve_unmatched); + unmatchedCheckbox.setLayoutData( + new GridData(SWT.FILL, SWT.TOP, true, false)); + + new WrappableNoteLabel(group, + Messages.preferences_page_note_prefix + " ", + Messages.preferences_page_file_op_auto_approve_unmatched_note); + } + + private void createTable(Composite parent) { + tableViewer = new TableViewer(parent, + SWT.BORDER | SWT.FULL_SELECTION | SWT.SINGLE | SWT.V_SCROLL); + Table table = tableViewer.getTable(); + GridData tableData = new GridData(SWT.FILL, SWT.FILL, true, false); + tableData.heightHint = TABLE_HEIGHT_HINT; + table.setLayoutData(tableData); + table.setHeaderVisible(true); + table.setLinesVisible(true); + SwtUtils.forwardVerticalMouseWheelToParentScrollerAtBoundary(table); + + TableViewerColumn patternCol = + new TableViewerColumn(tableViewer, SWT.NONE); + patternCol.getColumn().setText( + Messages.preferences_page_file_op_auto_approve_column_pattern); + patternCol.getColumn().setWidth(200); + patternCol.setLabelProvider(new ColumnLabelProvider() { + @Override + public String getText(Object element) { + return ((FileOperationAutoApproveRule) element).getPattern(); + } + + @Override + public Color getForeground(Object element) { + return ((FileOperationAutoApproveRule) element).isDefault() + ? Display.getDefault().getSystemColor(SWT.COLOR_DARK_GRAY) : null; + } + }); + + TableViewerColumn descCol = + new TableViewerColumn(tableViewer, SWT.NONE); + descCol.getColumn().setText( + Messages.preferences_page_file_op_auto_approve_column_description); + descCol.getColumn().setWidth(150); + descCol.setLabelProvider(new ColumnLabelProvider() { + @Override + public String getText(Object element) { + String desc = + ((FileOperationAutoApproveRule) element).getDescription(); + return desc != null ? desc : ""; + } + + @Override + public Color getForeground(Object element) { + return ((FileOperationAutoApproveRule) element).isDefault() + ? Display.getDefault().getSystemColor(SWT.COLOR_DARK_GRAY) : null; + } + }); + + TableViewerColumn statusCol = + new TableViewerColumn(tableViewer, SWT.NONE); + statusCol.getColumn().setText( + Messages.preferences_page_auto_approve_column_status); + statusCol.getColumn().setWidth(100); + statusCol.setLabelProvider(new ColumnLabelProvider() { + @Override + public String getText(Object element) { + return ((FileOperationAutoApproveRule) element).isAutoApprove() + ? Messages.preferences_page_auto_approve_allow + : Messages.preferences_page_auto_approve_deny; + } + + @Override + public Color getForeground(Object element) { + return ((FileOperationAutoApproveRule) element).isDefault() + ? Display.getDefault().getSystemColor(SWT.COLOR_DARK_GRAY) : null; + } + }); + SwtUtils.resizeColumnToFillTable(table, statusCol.getColumn(), 100, + patternCol.getColumn(), descCol.getColumn()); + + tableViewer.setContentProvider(ArrayContentProvider.getInstance()); + tableViewer.addSelectionChangedListener(e -> updateButtonState()); + } + + private void createButtons(Composite parent) { + Composite btnGroup = new Composite(parent, SWT.NONE); + btnGroup.setLayout(new GridLayout(1, false)); + btnGroup.setLayoutData( + new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false)); + + Button addButton = new Button(btnGroup, SWT.PUSH); + addButton.setText(Messages.preferences_page_auto_approve_add); + addButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); + addButton.addListener(SWT.Selection, e -> onAdd()); + + removeButton = new Button(btnGroup, SWT.PUSH); + removeButton.setText( + Messages.preferences_page_auto_approve_remove); + removeButton.setLayoutData( + new GridData(SWT.FILL, SWT.TOP, true, false)); + removeButton.setEnabled(false); + removeButton.addListener(SWT.Selection, e -> onRemove()); + + toggleButton = new Button(btnGroup, SWT.PUSH); + toggleButton.setText( + Messages.preferences_page_auto_approve_allow); + toggleButton.setLayoutData( + new GridData(SWT.FILL, SWT.TOP, true, false)); + toggleButton.setEnabled(false); + toggleButton.addListener(SWT.Selection, e -> onToggle()); + + resetButton = new Button(btnGroup, SWT.PUSH); + resetButton.setText( + Messages.preferences_page_auto_approve_reset); + resetButton.setLayoutData( + new GridData(SWT.FILL, SWT.TOP, true, false)); + resetButton.addListener(SWT.Selection, e -> onResetToDefaults()); + } + + private void onAdd() { + AddFileOperationRuleDialog dialog = + new AddFileOperationRuleDialog(getShell()); + if (dialog.open() == AddFileOperationRuleDialog.OK) { + String pattern = dialog.getPattern(); + if (isPatternExists(pattern)) { + MessageDialog.openWarning(getShell(), + Messages.preferences_page_file_op_auto_approve_duplicate_title, + Messages.preferences_page_file_op_auto_approve_duplicate_message); + return; + } + userRules.add(new FileOperationAutoApproveRule( + pattern, dialog.getDescription(), dialog.isAutoApprove())); + rebuildAllRules(); + tableViewer.refresh(); + updateButtonState(); + } + } + + private boolean isPatternExists(String pattern) { + return defaultRules.stream() + .anyMatch(r -> r.getPattern().equals(pattern)) + || userRules.stream() + .anyMatch(r -> r.getPattern().equals(pattern)); + } + + private void onRemove() { + IStructuredSelection sel = tableViewer.getStructuredSelection(); + if (!sel.isEmpty()) { + FileOperationAutoApproveRule rule = + (FileOperationAutoApproveRule) sel.getFirstElement(); + if (!rule.isDefault()) { + userRules.remove(rule); + rebuildAllRules(); + tableViewer.refresh(); + updateButtonState(); + } + } + } + + private void onToggle() { + IStructuredSelection sel = tableViewer.getStructuredSelection(); + if (!sel.isEmpty()) { + FileOperationAutoApproveRule rule = + (FileOperationAutoApproveRule) sel.getFirstElement(); + if (!rule.isDefault()) { + rule.setAutoApprove(!rule.isAutoApprove()); + tableViewer.refresh(); + updateButtonState(); + } + } + } + + private void onResetToDefaults() { + boolean confirmed = MessageDialog.openQuestion(getShell(), + Messages.preferences_page_file_op_auto_approve_reset_title, + Messages.preferences_page_auto_approve_reset_message); + if (confirmed) { + userRules.clear(); + resetDefaultRulesToOriginal(); + rebuildAllRules(); + tableViewer.refresh(); + updateButtonState(); + } + } + + /** + * Resets default rules' autoApprove to their original values. + * CLS defaults use {@code requiresConfirmation=true} → {@code autoApprove=false}. + * Local fallback defaults are already {@code autoApprove=false}. + */ + private void resetDefaultRulesToOriginal() { + for (FileOperationAutoApproveRule rule : defaultRules) { + rule.setAutoApprove(false); + } + } + + private void updateButtonState() { + boolean hasSelection = + !tableViewer.getStructuredSelection().isEmpty(); + FileOperationAutoApproveRule selected = hasSelection + ? (FileOperationAutoApproveRule) tableViewer + .getStructuredSelection().getFirstElement() + : null; + boolean isDefault = selected != null && selected.isDefault(); + + removeButton.setEnabled(hasSelection && !isDefault); + toggleButton.setEnabled(hasSelection && !isDefault); + if (hasSelection) { + toggleButton.setText(selected.isAutoApprove() + ? Messages.preferences_page_auto_approve_deny + : Messages.preferences_page_auto_approve_allow); + } else { + toggleButton.setText( + Messages.preferences_page_auto_approve_allow); + } + resetButton.setEnabled(!isMatchingDefaults()); + } + + /** + * Checks whether the current rule set matches defaults exactly + * (no user rules, all defaults at original autoApprove values). + */ + private boolean isMatchingDefaults() { + if (!userRules.isEmpty()) { + return false; + } + for (FileOperationAutoApproveRule rule : defaultRules) { + if (rule.isAutoApprove()) { + return false; + } + } + return true; + } + + /** Loads file-operation rules and unmatched-file-operation preference from the store. */ + public void loadFromPreferences(IPreferenceStore store) { + List savedRules = parseSavedRules(store); + + // Initialize with local fallback defaults + applyFallbackDefaults(); + + // Separate saved rules into defaults (override autoApprove) and user + Set defaultPatterns = defaultRules.stream() + .map(FileOperationAutoApproveRule::getPattern) + .collect(Collectors.toSet()); + userRules.clear(); + for (FileOperationAutoApproveRule saved : savedRules) { + if (defaultPatterns.contains(saved.getPattern())) { + // Restore toggled autoApprove for default rules + defaultRules.stream() + .filter(d -> d.getPattern().equals(saved.getPattern())) + .findFirst() + .ifPresent(d -> d.setAutoApprove(saved.isAutoApprove())); + } else { + userRules.add(saved); + } + } + + rebuildAllRules(); + tableViewer.setInput(allRules); + + unmatchedCheckbox.setSelection( + store.getBoolean(Constants.AUTO_APPROVE_UNMATCHED_FILE_OP)); + updateButtonState(); + + fetchDefaultRulesFromCls(); + } + + private List parseSavedRules( + IPreferenceStore store) { + String json = + store.getString(Constants.AUTO_APPROVE_FILE_OP_RULES); + if (StringUtils.isNotBlank(json) && !"[]".equals(json.trim())) { + try { + List loaded = + new Gson().fromJson(json, FILE_OP_RULES_TYPE); + if (loaded != null) { + return loaded; + } + } catch (Exception e) { + CopilotCore.LOGGER.error( + "Failed to parse file operation auto-approve rules", e); + } + } + return List.of(); + } + + private void applyFallbackDefaults() { + defaultRules.clear(); + for (FileOperationAutoApproveRule fallback + : FileOperationConfirmationHandler.FALLBACK_DEFAULT_RULES) { + defaultRules.add(new FileOperationAutoApproveRule( + fallback.getPattern(), fallback.getDescription(), + fallback.isAutoApprove(), true)); + } + } + + /** + * Fetches default file safety rules from CLS asynchronously. + * On success, merges CLS rules with local fallback and updates + * the table. On failure, keeps local fallback defaults. + */ + private void fetchDefaultRulesFromCls() { + CopilotLanguageServerConnection conn = + CopilotCore.getPlugin().getCopilotLanguageServer(); + if (conn == null) { + return; + } + conn.getDefaultFileSafetyRules().thenAccept(result -> { + if (result == null || result.getDefaultRules() == null) { + return; + } + SwtUtils.invokeOnDisplayThreadAsync(() -> { + if (isDisposed() || defaultRulesLoaded) { + return; + } + applyClsDefaults(result.getDefaultRules()); + }, FileOperationAutoApproveSection.this); + }).exceptionally(ex -> { + // CLS not available — keep local fallback defaults + CopilotCore.LOGGER.error( + "Failed to fetch default file safety rules from CLS", ex); + return null; + }); + } + + /** + * Applies CLS-provided default rules, merging with local fallback. + * CLS rules take priority; local fallbacks fill gaps. + */ + private void applyClsDefaults(List clsRules) { + // Preserve any user-toggled autoApprove on existing defaults + Map toggledDefaults = new HashMap<>(); + for (FileOperationAutoApproveRule existing : defaultRules) { + toggledDefaults.put(existing.getPattern(), existing.isAutoApprove()); + } + + defaultRules.clear(); + Set clsPatterns = new HashSet<>(); + for (FileSafetyRuleInfo clsRule : clsRules) { + String pattern = clsRule.getPattern(); + clsPatterns.add(pattern); + boolean autoApprove = !clsRule.isRequiresConfirmation(); + // Restore user toggle if they had changed this default + if (toggledDefaults.containsKey(pattern)) { + autoApprove = toggledDefaults.get(pattern); + } + String desc = clsRule.getDescription() != null + ? clsRule.getDescription() : ""; + defaultRules.add(new FileOperationAutoApproveRule( + pattern, desc, autoApprove, true)); + } + + // Add local fallbacks for patterns not in CLS + for (FileOperationAutoApproveRule fallback + : FileOperationConfirmationHandler.FALLBACK_DEFAULT_RULES) { + if (!clsPatterns.contains(fallback.getPattern())) { + boolean autoApprove = fallback.isAutoApprove(); + if (toggledDefaults.containsKey(fallback.getPattern())) { + autoApprove = toggledDefaults.get(fallback.getPattern()); + } + defaultRules.add(new FileOperationAutoApproveRule( + fallback.getPattern(), fallback.getDescription(), + autoApprove, true)); + } + } + + // Remove user rules that overlap with new defaults + Set allDefaultPatterns = defaultRules.stream() + .map(FileOperationAutoApproveRule::getPattern) + .collect(Collectors.toSet()); + userRules.removeIf(r -> allDefaultPatterns.contains(r.getPattern())); + + defaultRulesLoaded = true; + rebuildAllRules(); + tableViewer.refresh(); + updateButtonState(); + } + + /** Rebuilds the combined list shown in the table. */ + private void rebuildAllRules() { + allRules.clear(); + allRules.addAll(defaultRules); + allRules.addAll(userRules); + } + + /** Saves file-operation rules and unmatched-file-operation preference to the store. */ + public void saveToPreferences(IPreferenceStore store) { + // Save all rules (defaults + user) to preferences. + // On next load, defaults are re-identified by pattern matching. + store.setValue(Constants.AUTO_APPROVE_FILE_OP_RULES, + new Gson().toJson(allRules)); + store.setValue(Constants.AUTO_APPROVE_UNMATCHED_FILE_OP, + unmatchedCheckbox.getSelection()); + } +} diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/GlobalAutoApproveSection.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/GlobalAutoApproveSection.java new file mode 100644 index 00000000..3aaa8c7a --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/GlobalAutoApproveSection.java @@ -0,0 +1,122 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.preferences; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.ui.ISharedImages; +import org.eclipse.ui.PlatformUI; + +import com.microsoft.copilot.eclipse.core.Constants; + +/** + * Global auto-approve preference section with a YOLO mode checkbox + * that bypasses all confirmation dialogs when enabled. + */ +public class GlobalAutoApproveSection extends Composite { + + private static final int TOOLTIP_LINE_LENGTH = 90; + + private Button yoloCheckbox; + + /** Creates the global auto-approve section inside the given parent. */ + public GlobalAutoApproveSection(Composite parent, int style) { + super(parent, style); + setLayout(new GridLayout(1, false)); + setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); + createContents(); + } + + private void createContents() { + Group group = new Group(this, SWT.NONE); + group.setText(Messages.preferences_page_global_auto_approve_title); + group.setLayout(new GridLayout(1, false)); + group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); + group.setBackgroundMode(SWT.INHERIT_FORCE); + + Composite yoloRow = new Composite(group, SWT.NONE); + GridLayout yoloRowLayout = new GridLayout(2, false); + yoloRowLayout.marginWidth = 0; + yoloRowLayout.marginHeight = 0; + yoloRow.setLayout(yoloRowLayout); + yoloRow.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); + + yoloCheckbox = new Button(yoloRow, SWT.CHECK); + yoloCheckbox.setText( + Messages.preferences_page_global_auto_approve_label); + yoloCheckbox.setLayoutData( + new GridData(SWT.LEFT, SWT.CENTER, false, false)); + yoloCheckbox.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (yoloCheckbox.getSelection()) { + MessageDialog dialog = new MessageDialog( + getShell(), + Messages.preferences_page_global_auto_approve_confirm_title, + null, + Messages.preferences_page_global_auto_approve_confirm_message, + MessageDialog.WARNING, + new String[] { + Messages.preferences_page_global_auto_approve_confirm_button, + Messages.preferences_page_global_auto_approve_cancel_button + }, + 1); + int result = dialog.open(); + if (result != 0) { + yoloCheckbox.setSelection(false); + } + } + } + }); + + Label warningIcon = new Label(yoloRow, SWT.NONE); + warningIcon.setImage(PlatformUI.getWorkbench().getSharedImages() + .getImage(ISharedImages.IMG_OBJS_WARN_TSK)); + warningIcon.setToolTipText(wrapTooltip( + Messages.preferences_page_global_auto_approve_confirm_message)); + warningIcon.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); + + new WrappableNoteLabel(group, + Messages.preferences_page_note_prefix + " ", + Messages.preferences_page_global_auto_approve_confirm_message); + } + + /** Loads global auto-approve settings from the preference store. */ + public void loadFromPreferences(IPreferenceStore store) { + yoloCheckbox.setSelection( + store.getBoolean(Constants.AUTO_APPROVE_YOLO_MODE)); + } + + /** Saves global auto-approve settings to the preference store. */ + public void saveToPreferences(IPreferenceStore store) { + store.setValue(Constants.AUTO_APPROVE_YOLO_MODE, + yoloCheckbox.getSelection()); + } + + private static String wrapTooltip(String text) { + StringBuilder wrapped = new StringBuilder(text.length()); + int lineLength = 0; + for (String word : text.split(" ")) { + if (lineLength > 0 && lineLength + word.length() + 1 > TOOLTIP_LINE_LENGTH) { + wrapped.append('\n'); + lineLength = 0; + } else if (lineLength > 0) { + wrapped.append(' '); + lineLength++; + } + wrapped.append(word); + lineLength += word.length(); + } + return wrapped.toString(); + } +} diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/LanguageServerSettingManager.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/LanguageServerSettingManager.java index d04cc224..26b2c024 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/LanguageServerSettingManager.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/LanguageServerSettingManager.java @@ -5,10 +5,12 @@ import java.net.URI; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; +import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import org.apache.commons.lang3.StringUtils; @@ -27,6 +29,8 @@ import com.microsoft.copilot.eclipse.core.CopilotCore; import com.microsoft.copilot.eclipse.core.FeatureFlags; import com.microsoft.copilot.eclipse.core.chat.CustomChatModeManager; +import com.microsoft.copilot.eclipse.core.chat.FileOperationAutoApproveRule; +import com.microsoft.copilot.eclipse.core.chat.TerminalAutoApproveRule; import com.microsoft.copilot.eclipse.core.events.CopilotEventConstants; import com.microsoft.copilot.eclipse.core.lsp.CopilotLanguageServerConnection; import com.microsoft.copilot.eclipse.core.lsp.mcp.McpServerToolsStatusCollection; @@ -88,10 +92,20 @@ public LanguageServerSettingManager(CopilotLanguageServerConnection conn, IProxy .setAgentMaxRequests(preferenceStore.getInt(Constants.AGENT_MAX_REQUESTS)); getSettings().getGithubSettings().getCopilotSettings().getAgent() .setEnableSkills(PreferencesUtils.isSkillsEnabled()); + getSettings().getGithubSettings().getCopilotSettings().getAgent() + .setAutoCompress(true); // Set transcript directory for CLS session persistence and restoration getSettings().getGithubSettings().getCopilotSettings().getAgent() .setTranscriptDirectory(PlatformUtils.getTranscriptDirectory()); + getSettings().getGithubSettings().getCopilotSettings().getAgent() + .setAutoApproveUnmatchedTerminal( + preferenceStore.getBoolean(Constants.AUTO_APPROVE_UNMATCHED_TERMINAL)); + getSettings().getGithubSettings().getCopilotSettings().getAgent() + .setAutoApproveUnmatchedFileOp( + preferenceStore.getBoolean(Constants.AUTO_APPROVE_UNMATCHED_FILE_OP)); + syncTerminalRulesToCls(); + syncFileOperationRulesToCls(); // Set workspace context instructions when it is enabled if (preferenceStore.getBoolean(Constants.CUSTOM_INSTRUCTIONS_WORKSPACE_ENABLED)) { @@ -113,6 +127,8 @@ public LanguageServerSettingManager(CopilotLanguageServerConnection conn, IProxy syncMcpRegistrationConfiguration(); } }); + eventBroker.subscribe(CopilotEventConstants.TOPIC_MCP_EXTENSION_POINT_REGISTRATION_COMPLETED, + event -> syncMcpRegistrationConfiguration((String) event.getProperty(IEventBroker.DATA))); } /** @@ -150,7 +166,7 @@ public void propertyChange(PropertyChangeEvent event) { settings.getGithubEnterprise().setUri(preferenceStore.getString(Constants.GITHUB_ENTERPRISE)); singleSetting = new CopilotLanguageServerSettings(null, null, settings.getGithubEnterprise(), null); break; - case Constants.MCP, Constants.MCP_EXTENSION_POINT_CONTRIB: + case Constants.MCP: syncMcpRegistrationConfiguration(); return; case Constants.MCP_TOOLS_STATUS: @@ -183,6 +199,26 @@ public void propertyChange(PropertyChangeEvent event) { .setEnableSkills(PreferencesUtils.isSkillsEnabled()); singleSetting = new CopilotLanguageServerSettings(null, null, null, settings.getGithubSettings()); break; + case Constants.AUTO_APPROVE_UNMATCHED_TERMINAL: + settings.getGithubSettings().getCopilotSettings().getAgent() + .setAutoApproveUnmatchedTerminal( + preferenceStore.getBoolean(Constants.AUTO_APPROVE_UNMATCHED_TERMINAL)); + singleSetting = new CopilotLanguageServerSettings(null, null, null, settings.getGithubSettings()); + break; + case Constants.AUTO_APPROVE_TERMINAL_RULES: + syncTerminalRulesToCls(); + singleSetting = new CopilotLanguageServerSettings(null, null, null, settings.getGithubSettings()); + break; + case Constants.AUTO_APPROVE_UNMATCHED_FILE_OP: + settings.getGithubSettings().getCopilotSettings().getAgent() + .setAutoApproveUnmatchedFileOp( + preferenceStore.getBoolean(Constants.AUTO_APPROVE_UNMATCHED_FILE_OP)); + singleSetting = new CopilotLanguageServerSettings(null, null, null, settings.getGithubSettings()); + break; + case Constants.AUTO_APPROVE_FILE_OP_RULES: + syncFileOperationRulesToCls(); + singleSetting = new CopilotLanguageServerSettings(null, null, null, settings.getGithubSettings()); + break; default: return; } @@ -221,18 +257,93 @@ private void updateGithubPanicErrorReport() { * Sync MCP registration from both extension points and preference store. */ public void syncMcpRegistrationConfiguration() { + String approvedExtMcpServers = null; + if (CopilotCore.getPlugin().getFeatureFlags().isMcpContributionPointEnabled()) { + // Defensive null-chain: callers from very early startup paths (e.g. CopilotUi.start()) may + // run before the ChatServiceManager singleton field is assigned. The extension-point flow + // delivers its own state via TOPIC_MCP_EXTENSION_POINT_REGISTRATION_COMPLETED, so missing it + // here just means the LSP gets the manual MCP state for now and the verified state arrives + // shortly after via that subscription. + var chatServiceManager = CopilotUi.getPlugin().getChatServiceManager(); + if (chatServiceManager != null) { + McpExtensionPointManager mgr = chatServiceManager.getMcpExtensionPointManager(); + if (mgr != null) { + approvedExtMcpServers = mgr.getApprovedExtMcpServers(); + } + } + } + syncMcpRegistrationConfiguration(approvedExtMcpServers); + } + + /** + * Sync MCP registration to the language server using the supplied extension-contributed approved + * servers JSON. Used by callers that already have the approved JSON in hand - notably the + * subscriber to {@link CopilotEventConstants#TOPIC_MCP_EXTENSION_POINT_REGISTRATION_COMPLETED} - + * so they do not need to traverse {@code CopilotUi.getChatServiceManager()} to look it up. + * + * @param approvedExtMcpServers JSON for the approved extension-contributed MCP servers, or + * {@code null} when none are approved or the contribution point is disabled. + */ + public void syncMcpRegistrationConfiguration(String approvedExtMcpServers) { // From manual configuration settings.setMcpServers(preferenceStore.getString(Constants.MCP)); // From McpRegistration extension point if (CopilotCore.getPlugin().getFeatureFlags().isMcpContributionPointEnabled()) { - McpExtensionPointManager mgr = CopilotUi.getPlugin().getChatServiceManager().getMcpExtensionPointManager(); - settings.addMcpServers(mgr.getApprovedExtMcpServers()); + settings.addMcpServers(approvedExtMcpServers); } syncSingleConfiguration(new CopilotLanguageServerSettings(null, null, null, settings.getGithubSettings())); } + /** + * Converts terminal auto-approve rules from preference store JSON to the Map format + * expected by CLS and syncs them. + */ + private void syncTerminalRulesToCls() { + String json = preferenceStore.getString(Constants.AUTO_APPROVE_TERMINAL_RULES); + Map rulesMap = new LinkedHashMap<>(); + if (StringUtils.isNotBlank(json)) { + try { + List rules = + new Gson().fromJson(json, + new TypeToken>() { + }.getType()); + if (rules != null) { + rules.forEach(r -> rulesMap.put(r.getCommand(), r.isAutoApprove())); + } + } catch (Exception e) { + CopilotCore.LOGGER.error("Failed to parse terminal rules for CLS sync", e); + } + } + settings.getGithubSettings().getCopilotSettings().getAgent() + .getTools().getTerminal().setAutoApprove(rulesMap); + } + + /** + * Converts file-operation auto-approve rules from preference store JSON to the Map format + * expected by CLS and syncs them. + */ + private void syncFileOperationRulesToCls() { + String json = preferenceStore.getString(Constants.AUTO_APPROVE_FILE_OP_RULES); + Map rulesMap = new LinkedHashMap<>(); + if (StringUtils.isNotBlank(json)) { + try { + List rules = + new Gson().fromJson(json, + new TypeToken>() { + }.getType()); + if (rules != null) { + rules.forEach(r -> rulesMap.put(r.getPattern(), r.isAutoApprove())); + } + } catch (Exception e) { + CopilotCore.LOGGER.error("Failed to parse file-operation rules for CLS sync", e); + } + } + settings.getGithubSettings().getCopilotSettings().getAgent() + .getTools().getEdit().setAutoApprove(rulesMap); + } + /** * Initializes the MCP tools status from the preference store for built-in agent mode only. * Custom agent modes get their tool configuration from the LSP/file, not from preferences. diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/McpAutoApproveSection.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/McpAutoApproveSection.java new file mode 100644 index 00000000..357234b4 --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/McpAutoApproveSection.java @@ -0,0 +1,383 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.preferences; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import org.apache.commons.lang3.StringUtils; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.viewers.CheckStateChangedEvent; +import org.eclipse.jface.viewers.CheckboxTreeViewer; +import org.eclipse.jface.viewers.ICheckStateListener; +import org.eclipse.jface.viewers.ITreeContentProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; + +import com.microsoft.copilot.eclipse.core.Constants; +import com.microsoft.copilot.eclipse.core.CopilotCore; +import com.microsoft.copilot.eclipse.core.lsp.mcp.McpServerToolsCollection; +import com.microsoft.copilot.eclipse.core.lsp.mcp.McpToolInformation; +import com.microsoft.copilot.eclipse.ui.utils.SwtUtils; + +/** + * MCP auto-approve preference section with a trust-annotations checkbox + * and a tree viewer for per-server/tool approval management. + */ +public class McpAutoApproveSection extends Composite { + + private static final int TREE_HEIGHT_HINT = 200; + private static final Type STRING_LIST_TYPE = + new TypeToken>() {}.getType(); + + private Button trustAnnotationsCheckbox; + private CheckboxTreeViewer treeViewer; + private Group group; + + private List serverCollections = + new ArrayList<>(); + + // Current check state (lowercased for case-insensitive matching) + private final Set checkedServers = new HashSet<>(); + private final Set checkedTools = new HashSet<>(); + + /** Creates the MCP auto-approve section inside the given parent. */ + public McpAutoApproveSection(Composite parent, int style) { + super(parent, style); + setLayout(new GridLayout(1, false)); + setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); + createContents(); + } + + private void createContents() { + group = new Group(this, SWT.NONE); + group.setText(Messages.preferences_page_mcp_auto_approve_title); + group.setLayout(new GridLayout(1, false)); + group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); + group.setBackgroundMode(SWT.INHERIT_FORCE); + + // Trust annotations checkbox + trustAnnotationsCheckbox = new Button(group, SWT.CHECK); + trustAnnotationsCheckbox.setText( + Messages.preferences_page_mcp_auto_approve_trust_annotations); + trustAnnotationsCheckbox.setLayoutData( + new GridData(SWT.FILL, SWT.TOP, true, false)); + + new WrappableNoteLabel(group, + Messages.preferences_page_note_prefix + " ", + Messages.preferences_page_mcp_auto_approve_trust_annotations_note); + + // Server/tool approval label + Label serverToolsLabel = new Label(group, SWT.NONE); + serverToolsLabel.setText( + Messages.preferences_page_mcp_auto_approve_server_tools_label); + GridData labelData = new GridData(SWT.FILL, SWT.TOP, true, false); + serverToolsLabel.setLayoutData(labelData); + + // Tree viewer for server/tool approval + treeViewer = new CheckboxTreeViewer(group, + SWT.BORDER | SWT.FULL_SELECTION | SWT.V_SCROLL); + GridData treeData = new GridData(SWT.FILL, SWT.FILL, true, false); + treeData.heightHint = TREE_HEIGHT_HINT; + treeViewer.getTree().setLayoutData(treeData); + SwtUtils.forwardVerticalMouseWheelToParentScrollerAtBoundary(treeViewer.getTree()); + + treeViewer.setContentProvider(new McpTreeContentProvider()); + treeViewer.setLabelProvider(new McpTreeLabelProvider()); + treeViewer.addCheckStateListener(new McpCheckStateListener()); + treeViewer.setInput(serverCollections); + } + + /** Loads MCP auto-approve settings from the preference store. */ + public void loadFromPreferences(IPreferenceStore store) { + trustAnnotationsCheckbox.setSelection( + store.getBoolean(Constants.AUTO_APPROVE_TRUST_TOOL_ANNOTATIONS)); + + checkedServers.clear(); + checkedTools.clear(); + + List servers = loadJsonList(store, + Constants.AUTO_APPROVE_MCP_SERVERS); + for (String s : servers) { + checkedServers.add(s.toLowerCase(Locale.ROOT)); + } + + List tools = loadJsonList(store, + Constants.AUTO_APPROVE_MCP_TOOLS); + for (String t : tools) { + checkedTools.add(t.toLowerCase(Locale.ROOT)); + } + + refreshTreeCheckState(); + } + + /** Saves MCP auto-approve settings to the preference store. */ + public void saveToPreferences(IPreferenceStore store) { + store.setValue(Constants.AUTO_APPROVE_TRUST_TOOL_ANNOTATIONS, + trustAnnotationsCheckbox.getSelection()); + + store.setValue(Constants.AUTO_APPROVE_MCP_SERVERS, + new Gson().toJson(new ArrayList<>(checkedServers))); + store.setValue(Constants.AUTO_APPROVE_MCP_TOOLS, + new Gson().toJson(new ArrayList<>(checkedTools))); + } + + /** + * Updates the server/tool collections displayed in the tree viewer. + * Called from the MCP config service when server data changes. + */ + public void updateServerCollections( + List collections) { + if (isDisposed()) { + return; + } + SwtUtils.invokeOnDisplayThreadAsync(() -> { + if (isDisposed()) { + return; + } + this.serverCollections = collections != null + ? collections : Collections.emptyList(); + treeViewer.setInput(serverCollections); + refreshTreeCheckState(); + requestLayout(); + }, this); + } + + private void refreshTreeCheckState() { + if (treeViewer.getTree().isDisposed()) { + return; + } + for (McpServerToolsCollection server : serverCollections) { + // Expand to ensure child TreeItems exist before setChecked + treeViewer.expandToLevel(server, 1); + + String serverLower = server.getName() != null + ? server.getName().toLowerCase(Locale.ROOT) : ""; + boolean serverChecked = checkedServers.contains(serverLower); + + List tools = server.getTools(); + if (tools == null) { + tools = Collections.emptyList(); + } + + if (serverChecked) { + // Server is approved: check server and all its tools + treeViewer.setChecked(server, true); + treeViewer.setGrayed(server, false); + for (McpToolInformation tool : tools) { + treeViewer.setChecked(tool, true); + } + } else { + // Check individual tools + int checkedCount = 0; + for (McpToolInformation tool : tools) { + String toolKey = serverLower + "::" + + (tool.getName() != null + ? tool.getName().toLowerCase(Locale.ROOT) : ""); + boolean toolChecked = checkedTools.contains(toolKey); + treeViewer.setChecked(tool, toolChecked); + if (toolChecked) { + checkedCount++; + } + } + // Update parent check/gray state + if (checkedCount == 0) { + treeViewer.setChecked(server, false); + treeViewer.setGrayed(server, false); + } else if (checkedCount == tools.size()) { + treeViewer.setChecked(server, true); + treeViewer.setGrayed(server, false); + } else { + treeViewer.setChecked(server, true); + treeViewer.setGrayed(server, true); + } + } + } + } + + private static List loadJsonList(IPreferenceStore store, + String key) { + String json = store.getString(key); + if (StringUtils.isBlank(json) || "[]".equals(json.trim())) { + return Collections.emptyList(); + } + try { + List list = new Gson().fromJson(json, STRING_LIST_TYPE); + return list != null ? list : Collections.emptyList(); + } catch (Exception e) { + CopilotCore.LOGGER.error( + "Failed to parse MCP auto-approve list: " + key, e); + return Collections.emptyList(); + } + } + + /** Content provider for the server/tool tree. */ + private static class McpTreeContentProvider + implements ITreeContentProvider { + + @Override + public Object[] getElements(Object inputElement) { + if (inputElement instanceof List list) { + return list.toArray(); + } + return new Object[0]; + } + + @Override + public Object[] getChildren(Object parentElement) { + if (parentElement instanceof McpServerToolsCollection server) { + List tools = server.getTools(); + return tools != null ? tools.toArray() : new Object[0]; + } + return new Object[0]; + } + + @Override + public Object getParent(Object element) { + return null; + } + + @Override + public boolean hasChildren(Object element) { + if (element instanceof McpServerToolsCollection server) { + List tools = server.getTools(); + return tools != null && !tools.isEmpty(); + } + return false; + } + } + + /** Label provider for the server/tool tree. */ + private static class McpTreeLabelProvider extends LabelProvider { + @Override + public String getText(Object element) { + if (element instanceof McpServerToolsCollection server) { + return server.getName() != null ? server.getName() : ""; + } + if (element instanceof McpToolInformation tool) { + return tool.getName() != null ? tool.getName() : ""; + } + return ""; + } + } + + /** Handles check state changes in the server/tool tree. */ + private class McpCheckStateListener implements ICheckStateListener { + @Override + public void checkStateChanged(CheckStateChangedEvent event) { + Object element = event.getElement(); + boolean checked = event.getChecked(); + + if (element instanceof McpServerToolsCollection server) { + handleServerCheckChanged(server, checked); + } else if (element instanceof McpToolInformation tool) { + handleToolCheckChanged(tool, checked); + } + } + + private void handleServerCheckChanged( + McpServerToolsCollection server, boolean checked) { + String serverLower = server.getName() != null + ? server.getName().toLowerCase(Locale.ROOT) : ""; + treeViewer.setGrayed(server, false); + + if (checked) { + checkedServers.add(serverLower); + } else { + checkedServers.remove(serverLower); + } + + // Check/uncheck all children + List tools = server.getTools(); + if (tools != null) { + for (McpToolInformation tool : tools) { + treeViewer.setChecked(tool, checked); + String toolKey = serverLower + "::" + + (tool.getName() != null + ? tool.getName().toLowerCase(Locale.ROOT) : ""); + if (checked) { + checkedTools.add(toolKey); + } else { + checkedTools.remove(toolKey); + } + } + } + } + + private void handleToolCheckChanged( + McpToolInformation tool, boolean checked) { + // Find parent server + McpServerToolsCollection parentServer = findParentServer(tool); + if (parentServer == null) { + return; + } + String serverLower = parentServer.getName() != null + ? parentServer.getName().toLowerCase(Locale.ROOT) : ""; + String toolKey = serverLower + "::" + + (tool.getName() != null + ? tool.getName().toLowerCase(Locale.ROOT) : ""); + + if (checked) { + checkedTools.add(toolKey); + } else { + checkedTools.remove(toolKey); + } + + // Update parent check/gray state + updateParentState(parentServer); + } + + private void updateParentState(McpServerToolsCollection server) { + String serverLower = server.getName() != null + ? server.getName().toLowerCase(Locale.ROOT) : ""; + List tools = server.getTools(); + if (tools == null || tools.isEmpty()) { + return; + } + int checkedCount = 0; + for (McpToolInformation tool : tools) { + if (treeViewer.getChecked(tool)) { + checkedCount++; + } + } + if (checkedCount == 0) { + treeViewer.setChecked(server, false); + treeViewer.setGrayed(server, false); + checkedServers.remove(serverLower); + } else if (checkedCount == tools.size()) { + treeViewer.setChecked(server, true); + treeViewer.setGrayed(server, false); + checkedServers.add(serverLower); + } else { + treeViewer.setChecked(server, true); + treeViewer.setGrayed(server, true); + checkedServers.remove(serverLower); + } + } + + private McpServerToolsCollection findParentServer( + McpToolInformation tool) { + for (McpServerToolsCollection server : serverCollections) { + List tools = server.getTools(); + if (tools != null && tools.contains(tool)) { + return server; + } + } + return null; + } + } +} diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/McpPreferencePage.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/McpPreferencePage.java index a3682cf9..c41975d0 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/McpPreferencePage.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/McpPreferencePage.java @@ -83,7 +83,7 @@ public class McpPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { public static final String ID = "com.microsoft.copilot.eclipse.ui.preferences.McpPreferencePage"; - private static final int GROUP_HEIGHT_HINT = 260; + private static final int GROUP_HEIGHT_HINT = PreferencePageUtils.STANDARD_CONTENT_HEIGHT / 2; private static final Gson GSON = new Gson(); private Group toolsGroup; @@ -431,11 +431,7 @@ private void createExtMcpRegistrationArea(Composite parent) { extMcpButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - String res = CopilotUi.getPlugin().getChatServiceManager().getMcpExtensionPointManager() - .approveExtMcpRegistration(); - if (StringUtils.isNotBlank(res)) { - CopilotUi.getPlugin().getLanguageServerSettingManager().syncMcpRegistrationConfiguration(); - } + CopilotUi.getPlugin().getChatServiceManager().getMcpExtensionPointManager().approveExtMcpRegistration(); } }); } diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/Messages.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/Messages.java index 918b1e74..7582fd7a 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/Messages.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/Messages.java @@ -154,6 +154,60 @@ public class Messages extends NLS { public static String setting_managed_by_organization; public static String setting_disabled_by_organization; + // Shared Auto-Approve strings + public static String preferences_page_auto_approve_disabled_by_organization; + public static String preferences_page_auto_approve_column_status; + public static String preferences_page_auto_approve_add; + public static String preferences_page_auto_approve_remove; + public static String preferences_page_auto_approve_reset; + public static String preferences_page_auto_approve_reset_message; + public static String preferences_page_auto_approve_allow; + public static String preferences_page_auto_approve_deny; + public static String preferences_page_auto_approve_add_dialog_approve; + + // Terminal Auto-Approve + public static String preferences_page_terminal_auto_approve_title; + public static String preferences_page_terminal_auto_approve_description; + public static String preferences_page_terminal_auto_approve_column_command; + public static String preferences_page_terminal_auto_approve_reset_title; + public static String preferences_page_terminal_auto_approve_unmatched; + public static String preferences_page_terminal_auto_approve_unmatched_note; + public static String preferences_page_terminal_auto_approve_add_dialog_title; + public static String preferences_page_terminal_auto_approve_add_dialog_message; + public static String preferences_page_terminal_auto_approve_add_dialog_command; + public static String preferences_page_terminal_auto_approve_add_dialog_placeholder; + + // File Operations Auto Approve + public static String preferences_page_file_op_auto_approve_title; + public static String preferences_page_file_op_auto_approve_description; + public static String preferences_page_file_op_auto_approve_column_pattern; + public static String preferences_page_file_op_auto_approve_column_description; + public static String preferences_page_file_op_auto_approve_reset_title; + public static String preferences_page_file_op_auto_approve_unmatched; + public static String preferences_page_file_op_auto_approve_unmatched_note; + public static String preferences_page_file_op_auto_approve_add_dialog_title; + public static String preferences_page_file_op_auto_approve_add_dialog_message; + public static String preferences_page_file_op_auto_approve_add_dialog_pattern; + public static String preferences_page_file_op_auto_approve_add_dialog_description; + public static String preferences_page_file_op_auto_approve_add_dialog_pattern_hint; + public static String preferences_page_file_op_auto_approve_add_dialog_description_hint; + public static String preferences_page_file_op_auto_approve_duplicate_title; + public static String preferences_page_file_op_auto_approve_duplicate_message; + + // MCP Auto-Approve + public static String preferences_page_mcp_auto_approve_title; + public static String preferences_page_mcp_auto_approve_trust_annotations; + public static String preferences_page_mcp_auto_approve_trust_annotations_note; + public static String preferences_page_mcp_auto_approve_server_tools_label; + + // Global Auto-Approve + public static String preferences_page_global_auto_approve_title; + public static String preferences_page_global_auto_approve_label; + public static String preferences_page_global_auto_approve_confirm_title; + public static String preferences_page_global_auto_approve_confirm_message; + public static String preferences_page_global_auto_approve_confirm_button; + public static String preferences_page_global_auto_approve_cancel_button; + static { // initialize resource bundle NLS.initializeMessages(BUNDLE_NAME, Messages.class); diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/PreferencePageUtils.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/PreferencePageUtils.java index ab676ebf..13ed7ea9 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/PreferencePageUtils.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/PreferencePageUtils.java @@ -25,6 +25,15 @@ */ public final class PreferencePageUtils { + /** + * Target content height, in pixels, for Copilot preference pages. JFace grows the shared Preferences dialog to + * the tallest page's preferred height and never shrinks it, so each page keeps its scrollable content within + * this height to hold the dialog at a stable size while the user navigates. Pages enforce it differently: + * {@code McpPreferencePage} divides it across two stacked groups; {@code AutoApprovePreferencePage} caps its + * {@code ScrolledComposite} at this height. + */ + public static final int STANDARD_CONTENT_HEIGHT = 520; + // Private constructor to prevent instantiation private PreferencePageUtils() { } diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/TerminalAutoApproveSection.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/TerminalAutoApproveSection.java new file mode 100644 index 00000000..46664360 --- /dev/null +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/TerminalAutoApproveSection.java @@ -0,0 +1,279 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package com.microsoft.copilot.eclipse.ui.preferences; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import org.apache.commons.lang3.StringUtils; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.viewers.ArrayContentProvider; +import org.eclipse.jface.viewers.ColumnLabelProvider; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.jface.viewers.TableViewerColumn; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Table; + +import com.microsoft.copilot.eclipse.core.Constants; +import com.microsoft.copilot.eclipse.core.CopilotCore; +import com.microsoft.copilot.eclipse.core.chat.TerminalAutoApproveRule; +import com.microsoft.copilot.eclipse.ui.chat.confirmation.TerminalConfirmationHandler; +import com.microsoft.copilot.eclipse.ui.utils.SwtUtils; + +/** + * Terminal auto-approve section with a rule table, action buttons, and + * unmatched-command checkbox. + */ +public class TerminalAutoApproveSection extends Composite { + + private static final int TABLE_HEIGHT_HINT = 200; + private static final Type TERMINAL_RULES_TYPE = + new TypeToken>() {}.getType(); + + private TableViewer tableViewer; + private List rules = new ArrayList<>(); + private Button removeButton; + private Button toggleButton; + private Button resetButton; + private Button unmatchedCheckbox; + + /** Creates the terminal auto-approve section inside the given parent. */ + public TerminalAutoApproveSection(Composite parent, int style) { + super(parent, style); + setLayout(new GridLayout(1, false)); + setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); + createContents(); + } + + private void createContents() { + Group group = new Group(this, SWT.NONE); + group.setText(Messages.preferences_page_terminal_auto_approve_title); + group.setLayout(new GridLayout(1, false)); + group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); + group.setBackgroundMode(SWT.INHERIT_FORCE); + + Label description = new Label(group, SWT.WRAP); + description.setText( + Messages.preferences_page_terminal_auto_approve_description); + GridData descData = new GridData(SWT.FILL, SWT.TOP, true, false); + descData.widthHint = 400; + description.setLayoutData(descData); + + Composite container = new Composite(group, SWT.NONE); + container.setLayout(new GridLayout(2, false)); + container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); + + createTable(container); + createButtons(container); + + unmatchedCheckbox = new Button(group, SWT.CHECK); + unmatchedCheckbox.setText( + Messages.preferences_page_terminal_auto_approve_unmatched); + unmatchedCheckbox.setLayoutData( + new GridData(SWT.FILL, SWT.TOP, true, false)); + + new WrappableNoteLabel(group, + Messages.preferences_page_note_prefix + " ", + Messages.preferences_page_terminal_auto_approve_unmatched_note); + } + + private void createTable(Composite parent) { + tableViewer = new TableViewer(parent, + SWT.BORDER | SWT.FULL_SELECTION | SWT.SINGLE | SWT.V_SCROLL); + Table table = tableViewer.getTable(); + GridData tableData = new GridData(SWT.FILL, SWT.FILL, true, false); + tableData.heightHint = TABLE_HEIGHT_HINT; + table.setLayoutData(tableData); + table.setHeaderVisible(true); + table.setLinesVisible(true); + SwtUtils.forwardVerticalMouseWheelToParentScrollerAtBoundary(table); + + TableViewerColumn commandCol = + new TableViewerColumn(tableViewer, SWT.NONE); + commandCol.getColumn().setText( + Messages.preferences_page_terminal_auto_approve_column_command); + commandCol.getColumn().setWidth(300); + commandCol.setLabelProvider(new ColumnLabelProvider() { + @Override + public String getText(Object element) { + return ((TerminalAutoApproveRule) element).getCommand(); + } + }); + + TableViewerColumn statusCol = + new TableViewerColumn(tableViewer, SWT.NONE); + statusCol.getColumn().setText( + Messages.preferences_page_auto_approve_column_status); + statusCol.getColumn().setWidth(100); + statusCol.setLabelProvider(new ColumnLabelProvider() { + @Override + public String getText(Object element) { + return ((TerminalAutoApproveRule) element).isAutoApprove() + ? Messages.preferences_page_auto_approve_allow + : Messages.preferences_page_auto_approve_deny; + } + }); + SwtUtils.resizeColumnToFillTable(table, statusCol.getColumn(), 100, + commandCol.getColumn()); + + tableViewer.setContentProvider(ArrayContentProvider.getInstance()); + tableViewer.addSelectionChangedListener(e -> updateButtonState()); + } + + private void createButtons(Composite parent) { + Composite btnGroup = new Composite(parent, SWT.NONE); + btnGroup.setLayout(new GridLayout(1, false)); + btnGroup.setLayoutData( + new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false)); + + Button addButton = new Button(btnGroup, SWT.PUSH); + addButton.setText(Messages.preferences_page_auto_approve_add); + addButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); + addButton.addListener(SWT.Selection, e -> onAdd()); + + removeButton = new Button(btnGroup, SWT.PUSH); + removeButton.setText( + Messages.preferences_page_auto_approve_remove); + removeButton.setLayoutData( + new GridData(SWT.FILL, SWT.TOP, true, false)); + removeButton.setEnabled(false); + removeButton.addListener(SWT.Selection, e -> onRemove()); + + toggleButton = new Button(btnGroup, SWT.PUSH); + toggleButton.setText( + Messages.preferences_page_auto_approve_allow); + toggleButton.setLayoutData( + new GridData(SWT.FILL, SWT.TOP, true, false)); + toggleButton.setEnabled(false); + toggleButton.addListener(SWT.Selection, e -> onToggle()); + + resetButton = new Button(btnGroup, SWT.PUSH); + resetButton.setText( + Messages.preferences_page_auto_approve_reset); + resetButton.setLayoutData( + new GridData(SWT.FILL, SWT.TOP, true, false)); + resetButton.addListener(SWT.Selection, e -> onResetToDefaults()); + } + + private void onAdd() { + AddTerminalRuleDialog dialog = new AddTerminalRuleDialog(getShell()); + if (dialog.open() == AddTerminalRuleDialog.OK) { + String command = dialog.getCommand(); + // Remove existing rule with same command, then add at end + rules.removeIf(r -> r.getCommand().equals(command)); + rules.add(new TerminalAutoApproveRule(command, dialog.isAutoApprove())); + tableViewer.refresh(); + updateButtonState(); + } + } + + private void onRemove() { + IStructuredSelection sel = tableViewer.getStructuredSelection(); + if (!sel.isEmpty()) { + rules.remove(sel.getFirstElement()); + tableViewer.refresh(); + updateButtonState(); + } + } + + private void onToggle() { + IStructuredSelection sel = tableViewer.getStructuredSelection(); + if (!sel.isEmpty()) { + TerminalAutoApproveRule rule = + (TerminalAutoApproveRule) sel.getFirstElement(); + rule.setAutoApprove(!rule.isAutoApprove()); + tableViewer.refresh(); + updateButtonState(); + } + } + + private void onResetToDefaults() { + boolean confirmed = MessageDialog.openQuestion(getShell(), + Messages.preferences_page_terminal_auto_approve_reset_title, + Messages.preferences_page_auto_approve_reset_message); + if (confirmed) { + rules.clear(); + rules.addAll(TerminalConfirmationHandler.DEFAULT_RULES.stream() + .map(r -> new TerminalAutoApproveRule( + r.getCommand(), r.isAutoApprove())) + .toList()); + tableViewer.refresh(); + updateButtonState(); + } + } + + private void updateButtonState() { + boolean hasSelection = + !tableViewer.getStructuredSelection().isEmpty(); + removeButton.setEnabled(hasSelection); + toggleButton.setEnabled(hasSelection); + if (hasSelection) { + TerminalAutoApproveRule rule = (TerminalAutoApproveRule) + tableViewer.getStructuredSelection().getFirstElement(); + toggleButton.setText(rule.isAutoApprove() + ? Messages.preferences_page_auto_approve_deny + : Messages.preferences_page_auto_approve_allow); + } else { + toggleButton.setText( + Messages.preferences_page_auto_approve_allow); + } + resetButton.setEnabled(!isMatchingDefaults()); + } + + private boolean isMatchingDefaults() { + List defaults = TerminalConfirmationHandler.DEFAULT_RULES; + if (rules.size() != defaults.size()) { + return false; + } + for (int i = 0; i < rules.size(); i++) { + if (!rules.get(i).getCommand().equals(defaults.get(i).getCommand()) + || rules.get(i).isAutoApprove() != defaults.get(i).isAutoApprove()) { + return false; + } + } + return true; + } + + /** Loads terminal rules and unmatched-command preference from the store. */ + public void loadFromPreferences(IPreferenceStore store) { + String json = store.getString(Constants.AUTO_APPROVE_TERMINAL_RULES); + rules.clear(); + if (StringUtils.isNotBlank(json) && !"[]".equals(json.trim())) { + try { + List loaded = + new Gson().fromJson(json, TERMINAL_RULES_TYPE); + if (loaded != null) { + rules.addAll(loaded); + } + } catch (Exception e) { + CopilotCore.LOGGER.error( + "Failed to parse terminal auto-approve rules from preferences", e); + } + } + tableViewer.setInput(rules); + + unmatchedCheckbox.setSelection( + store.getBoolean(Constants.AUTO_APPROVE_UNMATCHED_TERMINAL)); + updateButtonState(); + } + + /** Saves terminal rules and unmatched-command preference to the store. */ + public void saveToPreferences(IPreferenceStore store) { + store.setValue(Constants.AUTO_APPROVE_TERMINAL_RULES, + new Gson().toJson(rules)); + store.setValue(Constants.AUTO_APPROVE_UNMATCHED_TERMINAL, + unmatchedCheckbox.getSelection()); + } +} diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/messages.properties b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/messages.properties index cec6e395..f041db59 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/messages.properties +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/messages.properties @@ -143,3 +143,59 @@ preferences_page_skills_enabled_note_content=Controls whether agent skills can b # enterprise support setting_disabled_by_organization=This setting is disabled by your organization. setting_managed_by_organization=This setting is managed by your organization. + + +preferences_page_auto_approve_disabled_by_organization=Tool auto-approval rules are disabled by your organization's administrator. Please contact your organization's administrator for more information. + +# Shared Auto Approve strings (reusable by all auto-approve sections) +preferences_page_auto_approve_column_status=Auto Approve +preferences_page_auto_approve_add=Add... +preferences_page_auto_approve_remove=Remove +preferences_page_auto_approve_reset=Reset to Defaults +preferences_page_auto_approve_reset_message=This will replace all current rules with the defaults. Continue? +preferences_page_auto_approve_allow=Allow +preferences_page_auto_approve_deny=Deny +preferences_page_auto_approve_add_dialog_approve=Auto Approve: + +# Terminal Auto Approve +preferences_page_terminal_auto_approve_title=Terminal Auto Approve +preferences_page_terminal_auto_approve_description=Controls whether chat-initiated terminal commands are automatically approved. Set to Allow to auto approve matching commands; set to Deny to always require explicit approval. +preferences_page_terminal_auto_approve_column_command=Command +preferences_page_terminal_auto_approve_reset_title=Reset Terminal Auto Approve Rules +preferences_page_terminal_auto_approve_unmatched=Auto approve commands not covered by rules +preferences_page_terminal_auto_approve_unmatched_note=When enabled, terminal commands not covered by the rules above are automatically approved. Use this setting at your own discretion. +preferences_page_terminal_auto_approve_add_dialog_title=Add Terminal Command Rule +preferences_page_terminal_auto_approve_add_dialog_message=Enter the command name or regex pattern (e.g., npm, git, /^apt-get\\b/) +preferences_page_terminal_auto_approve_add_dialog_command=Command or Regex: +preferences_page_terminal_auto_approve_add_dialog_placeholder=e.g., npm, git, /^apt-get\\b/ + +# File Operations Auto Approve +preferences_page_file_op_auto_approve_title=File Operations Auto Approve +preferences_page_file_op_auto_approve_description=Controls whether file operations generated by Copilot are approved automatically. Rules only apply to files within the workspace; operations on files outside the workspace always require confirmation. Set to Allow to auto approve operations on matching files; set to Deny to always require explicit approval. +preferences_page_file_op_auto_approve_column_pattern=Pattern +preferences_page_file_op_auto_approve_column_description=Description +preferences_page_file_op_auto_approve_reset_title=Reset File Operations Auto Approve Rules +preferences_page_file_op_auto_approve_unmatched=Auto approve file operations not covered by rules +preferences_page_file_op_auto_approve_unmatched_note=When enabled, file operations not covered by the rules above are automatically approved. File operations outside the workspace always require confirmation. +preferences_page_file_op_auto_approve_add_dialog_title=Add File Operation Auto Approve Rule +preferences_page_file_op_auto_approve_add_dialog_message=Enter the glob pattern (e.g., **/.idea/**/* or **/*.config) +preferences_page_file_op_auto_approve_add_dialog_pattern=Pattern: +preferences_page_file_op_auto_approve_add_dialog_description=Description: +preferences_page_file_op_auto_approve_add_dialog_pattern_hint=e.g., **/.idea/**/* or **/*.config +preferences_page_file_op_auto_approve_add_dialog_description_hint=Optional description +preferences_page_file_op_auto_approve_duplicate_title=Duplicate Pattern +preferences_page_file_op_auto_approve_duplicate_message=A rule for this pattern already exists. + +# MCP Auto Approve +preferences_page_mcp_auto_approve_title=MCP Auto Approve +preferences_page_mcp_auto_approve_trust_annotations=Trust MCP tool annotations +preferences_page_mcp_auto_approve_trust_annotations_note=When enabled, Copilot uses MCP tool annotations to automatically approve read-only tool calls without confirmation. +preferences_page_mcp_auto_approve_server_tools_label=MCP Server and Tool Approval + +# Global Auto Approve +preferences_page_global_auto_approve_title=Global Auto Approve +preferences_page_global_auto_approve_label=Auto approve all tool calls +preferences_page_global_auto_approve_confirm_title=Enable Global Auto Approve? +preferences_page_global_auto_approve_confirm_message=Global auto-approve disables manual approval completely for all tools. When enabled, ALL tool calls (terminal commands, file edits, built-in tools, and MCP tools) will be automatically approved without any confirmation. This is extremely dangerous and is never recommended. +preferences_page_global_auto_approve_confirm_button=Confirm +preferences_page_global_auto_approve_cancel_button=Cancel diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/swt/DropdownPopup.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/swt/DropdownPopup.java index 7b9dc2f0..344eb79c 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/swt/DropdownPopup.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/swt/DropdownPopup.java @@ -28,6 +28,7 @@ import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; +import com.microsoft.copilot.eclipse.core.utils.PlatformUtils; import com.microsoft.copilot.eclipse.ui.utils.SwtUtils; import com.microsoft.copilot.eclipse.ui.utils.UiUtils; @@ -219,6 +220,7 @@ void open(Point location, List groups, String selectedItemId, shell.pack(); constrainHeightIfNeeded(); + reserveScrollbarSpaceIfNeeded(contentSize); adjustBounds(location, anchorHeight); scrollToFocusedItem(); shell.setVisible(true); @@ -234,14 +236,71 @@ private void constrainHeightIfNeeded() { Rectangle lastBounds = lastVisible.getBounds(); int maxContentHeight = lastBounds.y + lastBounds.height; - int scrollBarWidth = 0; - if (scrolledComposite.getVerticalBar() != null) { - scrollBarWidth = scrolledComposite.getVerticalBar().getSize().x; - } - Point shellSize = shell.getSize(); int newHeight = maxContentHeight + 2 * POPUP_MARGIN; - shell.setSize(shellSize.x + scrollBarWidth, newHeight); + shell.setSize(shellSize.x, newHeight); + } + + /** + * Ensures the vertical scrollbar never hides item content, which manifests differently across platforms. + * + *
    + *
  • Classic (space-reserving) scrollbars (typical on Windows and many GTK themes) shrink the + * {@link ScrolledComposite} client area. With {@link ScrolledComposite#setExpandHorizontal(boolean)} the + * content is stretched to that reduced width, so the shell must be widened by the reserved trough width to + * restore the full natural content width.
  • + *
  • Overlay scrollbars (the default on modern GNOME, e.g. RHEL 9) do not reduce the client + * area; the scrollbar is painted on top of the right edge of the content, covering the right-aligned suffix + * labels. Widening the shell alone does not help because the suffix stays pinned to the (new) right edge, + * still under the overlay. Instead we stop horizontal expansion, keep the content at its natural width, and + * widen the shell so an empty scrollbar-width strip is left on the right for the overlay to paint over.
  • + *
+ * + * @param contentSize the natural (unconstrained) size of the item container + */ + private void reserveScrollbarSpaceIfNeeded(Point contentSize) { + if (items.size() <= MAX_VISIBLE_ITEMS || items.isEmpty()) { + return; + } + + if (scrolledComposite == null || scrolledComposite.isDisposed() || scrolledComposite.getVerticalBar() == null) { + return; + } + + // Fix #113: We adapt the drop-down dialog's size only for Linux (where the issue appeared), + // in order to avoid potential regressions, + // see https://github.com/microsoft/copilot-for-eclipse/pull/285#issuecomment-4686907980 + if (PlatformUtils.isLinux()) { + // Force a layout so the client area reflects the constrained height before we measure it. + // The layout operation doesn't lead to flickering, since it is not user-visible at this point. + shell.layout(true, true); + int scrollBarWidth = scrolledComposite.getVerticalBar().getSize().x; + if (scrollBarWidth <= 0) { + return; + } + Rectangle clientArea = scrolledComposite.getClientArea(); + Point shellSize = shell.getSize(); + if (clientArea.width < contentSize.x) { + // Classic scrollbar: the trough shrank the client area. Widen the shell to restore full content width. + int deficit = contentSize.x - clientArea.width; + shell.setSize(shellSize.x + deficit, shellSize.y); + } else { + // Overlay scrollbar: client area was not reduced, so the bar paints over the content's right edge. Pin the + // content to its natural width and reserve just enough room on the right for the overlay. + scrolledComposite.setExpandHorizontal(false); + Control content = scrolledComposite.getContent(); + if (content != null && !content.isDisposed()) { + content.setSize(contentSize); + } + int extraWidth = Math.max(0, scrollBarWidth - ITEM_H_PADDING); + shell.setSize(shellSize.x + extraWidth, shellSize.y); + } + } else { + // Behavior before fixing #113 + int scrollBarWidth = scrolledComposite.getVerticalBar().getSize().x; + Point shellSize = shell.getSize(); + shell.setSize(shellSize.x + scrollBarWidth, shellSize.y); + } } private void adjustBounds(Point location, int anchorHeight) { diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/swt/ModelHoverContentProvider.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/swt/ModelHoverContentProvider.java index a1698ffe..425a6b54 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/swt/ModelHoverContentProvider.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/swt/ModelHoverContentProvider.java @@ -19,7 +19,6 @@ import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; @@ -27,8 +26,8 @@ import org.eclipse.ui.PlatformUI; import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel; -import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel.CopilotModelCapabilitiesLimits; import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel.CopilotModelCapabilitiesSupports; +import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel.CopilotModelCustomModel; import com.microsoft.copilot.eclipse.ui.CopilotUi; import com.microsoft.copilot.eclipse.ui.chat.services.ModelService; import com.microsoft.copilot.eclipse.ui.i18n.Messages; @@ -37,7 +36,7 @@ /** * Renders the full hover UI for model items in the model picker dropdown. The layout consists of the bold title header, - * an optional category badge, an optional degradation warning, and model-specific details such as context size and + * an optional category badge, an optional degradation warning, and model-specific details such as context window and * token pricing. */ public class ModelHoverContentProvider implements IDropdownItemHoverProvider { @@ -50,8 +49,6 @@ public class ModelHoverContentProvider implements IDropdownItemHoverProvider { /** Vertical padding inside a thinking effort row, so the hover background has breathing room. */ private static final int THINKING_EFFORT_ROW_V_PADDING = 2; - private static Image arrowUpIcon; - private static Image arrowDownIcon; private static Image effortCheckIcon; private final CopilotModel model; @@ -80,9 +77,9 @@ public void configureHover(Composite parent, DropdownItem item, Runnable closeRe addWarningRow(parent, model.getDegradationReason()); } - CopilotModelCapabilitiesLimits limits = model.getCapabilities() != null ? model.getCapabilities().limits() : null; + addCustomModelInfoSection(parent, item.getLabel()); - addContextSizeSection(parent, limits); + addContextWindowSection(parent); addPricingSection(parent, model.getModelPickerPriceCategory()); addThinkingEffortSection(parent, closeRequest); } @@ -95,49 +92,44 @@ private void renderHeader(Composite parent, DropdownItem item) { titleLabel.setLayoutData(headerGd); } - private void addContextSizeSection(Composite parent, CopilotModelCapabilitiesLimits limits) { - if (limits == null) { + /** + * Renders the "contributed by" line for organization/enterprise-contributed custom (BYOK) models. Mirrors the + * IntelliJ model tooltip: the row only appears when the model carries custom-model metadata with a non-blank owner + * and key name, communicating that the model was provided by an owner through a specific key. + * + * @param parent the hover composite to render into + * @param displayedName the model name as shown in the hover header + */ + private void addCustomModelInfoSection(Composite parent, String displayedName) { + CopilotModelCustomModel customModel = model.getCustomModel(); + if (customModel == null) { return; } - boolean hasInput = isPositive(limits.maxInputTokens()); - boolean hasOutput = isPositive(limits.maxOutputTokens()); - if (!hasInput && !hasOutput) { + String ownerName = StringUtils.trimToNull(customModel.ownerName()); + String keyName = StringUtils.trimToNull(customModel.keyName()); + if (ownerName == null || keyName == null) { return; } - addSeparator(parent); - - Composite row = createKeyValueRow(parent); - ((GridData) row.getLayoutData()).verticalIndent = SECTION_SPACING; + String modelLabel = StringUtils.defaultIfBlank(displayedName, model.getModelName()); + String infoText = NLS.bind(Messages.model_hover_customModelInfo, + new Object[] { modelLabel, ownerName, keyName }); + Label infoLabel = new Label(parent, SWT.WRAP); + infoLabel.setText(infoText); + setCssClass(infoLabel, POPUP_SECONDARY_TEXT_CLASS); + GridData gd = new GridData(SWT.FILL, SWT.NONE, true, false); + gd.verticalIndent = SECTION_SPACING; + infoLabel.setLayoutData(gd); + } - // Context Size: - Label keyLabel = createSecondaryTextLabel(row, Messages.model_hover_contextSize); - keyLabel.setLayoutData(new GridData(SWT.LEFT, SWT.NONE, false, false)); - - Composite valueComp = new Composite(row, SWT.NONE); - valueComp.setLayoutData(new GridData(SWT.RIGHT, SWT.NONE, true, false)); - RowLayout valueLayout = new RowLayout(SWT.HORIZONTAL); - valueLayout.marginTop = 0; - valueLayout.marginBottom = 0; - valueLayout.marginLeft = 0; - valueLayout.marginRight = 0; - - // Add spacing between input and output token labels if both are present - if (hasInput && hasOutput) { - valueLayout.spacing = 4; - } else { - valueLayout.spacing = 0; + private void addContextWindowSection(Composite parent) { + String contextWindowText = ModelUtils.getContextWindowText(model); + if (StringUtils.isBlank(contextWindowText)) { + return; } - valueComp.setLayout(valueLayout); - // ex. ↑128K - if (hasInput) { - addArrowTokenLabel(valueComp, true, ModelUtils.formatTokenCount(limits.maxInputTokens())); - } - // ex. ↓16K - if (hasOutput) { - addArrowTokenLabel(valueComp, false, ModelUtils.formatTokenCount(limits.maxOutputTokens())); - } + addSeparator(parent); + addKeyValueRow(parent, Messages.model_hover_contextWindow, contextWindowText); } private void addPricingSection(Composite parent, String priceCategory) { @@ -325,42 +317,7 @@ private Composite createKeyValueRow(Composite parent) { return row; } - private void addArrowTokenLabel(Composite parent, boolean isInput, String tokenText) { - GridLayout pairLayout = new GridLayout(2, false); - pairLayout.marginWidth = 0; - pairLayout.marginHeight = 0; - pairLayout.horizontalSpacing = 0; - Composite pairComp = new Composite(parent, SWT.NONE); - pairComp.setLayout(pairLayout); - - initArrowIcons(pairComp); - Label arrowLabel = new Label(pairComp, SWT.NONE); - Image arrowImage = isInput ? arrowUpIcon : arrowDownIcon; - arrowLabel.setImage(arrowImage); - - createSecondaryTextLabel(pairComp, tokenText); - } - - private static void initArrowIcons(Composite parent) { - if (arrowUpIcon == null || arrowUpIcon.isDisposed()) { - boolean isDark = UiUtils.isDarkTheme(); - arrowUpIcon = UiUtils.buildImageFromPngPath(isDark ? "/icons/dropdown/context_size_arrow_up_dark.png" - : "/icons/dropdown/context_size_arrow_up_light.png"); - arrowDownIcon = UiUtils.buildImageFromPngPath(isDark ? "/icons/dropdown/context_size_arrow_down_dark.png" - : "/icons/dropdown/context_size_arrow_down_light.png"); - parent.getDisplay().addListener(SWT.Dispose, e -> disposeStaticIcons()); - } - } - private static void disposeStaticIcons() { - if (arrowUpIcon != null && !arrowUpIcon.isDisposed()) { - arrowUpIcon.dispose(); - arrowUpIcon = null; - } - if (arrowDownIcon != null && !arrowDownIcon.isDisposed()) { - arrowDownIcon.dispose(); - arrowDownIcon = null; - } if (effortCheckIcon != null && !effortCheckIcon.isDisposed()) { effortCheckIcon.dispose(); effortCheckIcon = null; diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/dialogs/mcp/DropDownButton.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/swt/SplitDropdownButton.java similarity index 89% rename from com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/dialogs/mcp/DropDownButton.java rename to com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/swt/SplitDropdownButton.java index 55aa6301..c1e908d8 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/dialogs/mcp/DropDownButton.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/swt/SplitDropdownButton.java @@ -14,7 +14,7 @@ * The Eclipse Foundation - initial API and implementation *******************************************************************************/ -package com.microsoft.copilot.eclipse.ui.dialogs.mcp; +package com.microsoft.copilot.eclipse.ui.swt; import java.util.ArrayList; import java.util.List; @@ -36,12 +36,18 @@ import org.eclipse.swt.widgets.Shell; /** - * A drop down button from Eclipse Foundation that can show a menu when the arrow is clicked. + * A split button that distinguishes between clicking the label area (primary action) + * and clicking the arrow area (opens a dropdown menu). Originally from Eclipse Foundation. + * + *

Selection listeners receive {@code e.detail == SWT.ARROW} when the arrow + * area is clicked, and {@code e.detail == 0} for the primary area. */ -public class DropDownButton { +public class SplitDropdownButton { private boolean showArrow; + private Color separatorColor; + private Rectangle arrowBounds; private String padding = null; @@ -71,9 +77,10 @@ public void paintControl(PaintEvent e) { try { int inset = 3; int lineX = arrowBounds.x; + Color lineColor = separatorColor != null ? separatorColor : shadowColor; gc.setLineWidth(1); - gc.setForeground(shadowColor); - gc.setBackground(shadowColor); + gc.setForeground(lineColor); + gc.setBackground(lineColor); gc.drawLine(lineX, arrowBounds.y + inset - 1, lineX, e.y + buttonBounds.height - inset); Color arrowColor = button.getForeground(); @@ -93,12 +100,12 @@ public void paintControl(PaintEvent e) { }; /** - * Creates a new DropDownButton. + * Creates a new SplitButton. * * @param parent the parent composite * @param style the style of button */ - public DropDownButton(Composite parent, int style) { + public SplitDropdownButton(Composite parent, int style) { button = new Button(parent, SWT.PUSH); } @@ -125,6 +132,17 @@ public boolean isShowArrow() { return showArrow; } + /** + * Overrides the separator line color. When {@code null} (default), + * the system shadow color is used. + * + * @param color the color for the separator, or {@code null} for the default + */ + public void setSeparatorColor(Color color) { + this.separatorColor = color; + button.redraw(); + } + /** * Sets the text of the button. * @@ -291,7 +309,8 @@ private DropDownSelectionListenerWrapper findWrapper(final SelectionListener lis * @param listener the listener to remove */ public void removeSelectionListener(SelectionListener listener) { - DropDownSelectionListenerWrapper wrapper = findWrapper(listener); + DropDownSelectionListenerWrapper wrapper = + findWrapper(listener); if (wrapper != null) { button.removeSelectionListener(wrapper); } diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/ModelUtils.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/ModelUtils.java index e7d18484..5919742d 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/ModelUtils.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/ModelUtils.java @@ -14,6 +14,7 @@ import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel.CopilotModelCapabilities; import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel.CopilotModelCapabilitiesLimits; import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel.CopilotModelCapabilitiesSupports; +import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotModel.CopilotModelTokenPriceTier; import com.microsoft.copilot.eclipse.core.lsp.protocol.CopilotScope; import com.microsoft.copilot.eclipse.core.lsp.protocol.byok.ByokModel; import com.microsoft.copilot.eclipse.core.lsp.protocol.byok.ByokModelCapabilities; @@ -100,6 +101,11 @@ public static String getModelSuffix(CopilotModel model, String reasoningEffort) if (model.getProviderName() != null) { return model.getProviderName(); } + // Organization/enterprise-contributed custom models arrive through copilot/models without a providerName, but + // still carry their underlying provider in the custom-model metadata. Surface it so they read like BYOK models. + if (model.getCustomModel() != null && StringUtils.isNotBlank(model.getCustomModel().provider())) { + return model.getCustomModel().provider(); + } if (isAutoModel(model)) { return Messages.model_billing_multiplier_variable; } @@ -162,15 +168,62 @@ public static String formatPriceCategory(String priceCategory) { /** * Returns the formatted context window size for the model, or {@code null} if unavailable. */ - private static String getContextWindowText(CopilotModel model) { + public static String getContextWindowText(CopilotModel model) { + Integer contextWindow = resolveContextWindowSize(model); + if (contextWindow == null || contextWindow <= 0) { + return null; + } + return formatTokenCount(contextWindow); + } + + /** + * Resolves the user-facing context window size for the model, mirroring the language-server / IntelliJ behavior. + * + *

When the model advertises a {@code default} price tier with its own {@code maxContext} (the input budget), the + * full window is {@code maxContext + maxOutputTokens}. Otherwise, token-based billing models fall back to + * {@code maxInputTokens + maxOutputTokens}, and finally to the advertised {@code maxContextWindowTokens}. + * + * @param model the model + * @return the context window size in tokens, or {@code null} when it cannot be determined + */ + public static Integer resolveContextWindowSize(CopilotModel model) { if (model.getCapabilities() == null || model.getCapabilities().limits() == null) { return null; } - Integer maxContextWindowTokens = model.getCapabilities().limits().maxContextWindowTokens(); - if (maxContextWindowTokens == null || maxContextWindowTokens <= 0) { + CopilotModelCapabilitiesLimits limits = model.getCapabilities().limits(); + Integer maxOutputTokens = limits.maxOutputTokens(); + int output = maxOutputTokens == null ? 0 : maxOutputTokens; + + CopilotModelTokenPriceTier defaultTier = getDefaultTokenPriceTier(model); + if (defaultTier != null && defaultTier.maxContext() != null) { + return defaultTier.maxContext() + output; + } + + // TODO: Remove this legacy fallback after TBB is officially released. + if (isTokenBasedBillingEnabled(model)) { + Integer maxInputTokens = limits.maxInputTokens(); + if (maxInputTokens != null && maxOutputTokens != null) { + return maxInputTokens + maxOutputTokens; + } + } + + return limits.maxContextWindowTokens(); + } + + // TODO: Remove this legacy fallback after TBB is officially released. + private static boolean isTokenBasedBillingEnabled(CopilotModel model) { + return model.getBilling() != null && model.getBilling().tokenBasedBillingEnabled(); + } + + /** + * Returns the model's {@code default} token price tier, or {@code null} when the model carries no token-based + * pricing. + */ + private static CopilotModelTokenPriceTier getDefaultTokenPriceTier(CopilotModel model) { + if (model.getBilling() == null || model.getBilling().tokenPrices() == null) { return null; } - return formatTokenCount(maxContextWindowTokens); + return model.getBilling().tokenPrices().defaultTier(); } /** diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/PreferencesUtils.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/PreferencesUtils.java index 016bbb2a..20f0285d 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/PreferencesUtils.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/PreferencesUtils.java @@ -12,6 +12,7 @@ import com.microsoft.copilot.eclipse.core.FeatureFlags; import com.microsoft.copilot.eclipse.core.chat.CustomInstructionsChatLoadScope; import com.microsoft.copilot.eclipse.ui.CopilotUi; +import com.microsoft.copilot.eclipse.ui.preferences.AutoApprovePreferencePage; import com.microsoft.copilot.eclipse.ui.preferences.ByokPreferencePage; import com.microsoft.copilot.eclipse.ui.preferences.ChatPreferencesPage; import com.microsoft.copilot.eclipse.ui.preferences.CompletionsPreferencesPage; @@ -33,7 +34,7 @@ private PreferencesUtils() { public static String[] getAllPreferenceIds() { return new String[] { CopilotPreferencesPage.ID, GeneralPreferencesPage.ID, ChatPreferencesPage.ID, CompletionsPreferencesPage.ID, CustomInstructionPreferencePage.ID, CustomModesPreferencePage.ID, - McpPreferencePage.ID, ByokPreferencePage.ID }; + McpPreferencePage.ID, ByokPreferencePage.ID, AutoApprovePreferencePage.ID }; } /** diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/SwtUtils.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/SwtUtils.java index ea44da6f..73180b8c 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/SwtUtils.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/SwtUtils.java @@ -12,15 +12,25 @@ import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.ITextViewer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; +import org.eclipse.swt.events.ControlAdapter; +import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.ScrollBar; +import org.eclipse.swt.widgets.Scrollable; import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; @@ -38,8 +48,30 @@ private SwtUtils() { } private static final String INLINE_ANNOTATION_COLOR_KEY = "org.eclipse.ui.editors.inlineAnnotationColor"; + private static final int DEFAULT_GHOST_TEXT_SCALE = 128; + /** + * Walks up the parent chain of the given control and returns the first ancestor that is an instance of the specified + * type, or {@code null} if none is found. + * + * @param the target type + * @param control the starting control (may be {@code null}) + * @param type the class to search for + * @return the first matching ancestor, or {@code null} + */ + @Nullable + public static T findParentOfType(Control control, Class type) { + Control current = control; + while (current != null) { + if (type.isInstance(current)) { + return type.cast(current); + } + current = current.getParent(); + } + return null; + } + /** * Invokes the given runnable on the display thread. */ @@ -272,6 +304,88 @@ public static Color getDefaultGhostTextColor(Display display) { return new Color(display, new RGB(DEFAULT_GHOST_TEXT_SCALE, DEFAULT_GHOST_TEXT_SCALE, DEFAULT_GHOST_TEXT_SCALE)); } + /** + * Forwards vertical mouse wheel scrolling from a nested scrollable to its nearest parent scroller when the nested + * control is already at the scroll boundary. + */ + public static void forwardVerticalMouseWheelToParentScrollerAtBoundary(Scrollable scrollable) { + scrollable.addListener(SWT.MouseWheel, event -> { + if (event.count == 0 || scrollable.isDisposed() + || canScrollVertically(scrollable.getVerticalBar(), event.count)) { + return; + } + + ScrolledComposite parentScroller = findParentScroller(scrollable); + if (parentScroller != null + && canScrollVertically(parentScroller.getVerticalBar(), event.count)) { + event.doit = false; + scrollParentVertically(parentScroller, event.count); + } + }); + } + + private static ScrolledComposite findParentScroller(Scrollable scrollable) { + Composite parent = scrollable.getParent(); + while (parent != null) { + if (parent instanceof ScrolledComposite scrolledComposite) { + return scrolledComposite; + } + parent = parent.getParent(); + } + return null; + } + + private static void scrollParentVertically(ScrolledComposite scrolledComposite, int wheelCount) { + ScrollBar verticalBar = scrolledComposite.getVerticalBar(); + if (verticalBar == null || verticalBar.isDisposed()) { + return; + } + + Point origin = scrolledComposite.getOrigin(); + int minimum = verticalBar.getMinimum(); + int maximum = Math.max(minimum, + verticalBar.getMaximum() - verticalBar.getThumb()); + int delta = -wheelCount * Math.max(1, verticalBar.getIncrement()); + int nextY = Math.max(minimum, Math.min(maximum, origin.y + delta)); + scrolledComposite.setOrigin(origin.x, nextY); + } + + private static boolean canScrollVertically(ScrollBar verticalBar, int wheelCount) { + if (verticalBar == null || verticalBar.isDisposed() + || !verticalBar.getEnabled()) { + return false; + } + + int minimum = verticalBar.getMinimum(); + int maximum = Math.max(minimum, + verticalBar.getMaximum() - verticalBar.getThumb()); + int selection = Math.max(minimum, + Math.min(maximum, verticalBar.getSelection())); + if (wheelCount > 0) { + return selection > minimum; + } + return selection < maximum; + } + + /** + * Resizes a table column to fill the table client area not occupied by the fixed-width columns. + */ + public static void resizeColumnToFillTable(Table table, TableColumn fillColumn, + int minWidth, TableColumn... fixedColumns) { + table.addControlListener(new ControlAdapter() { + @Override + public void controlResized(ControlEvent e) { + int remainingWidth = table.getClientArea().width; + for (TableColumn fixedColumn : fixedColumns) { + remainingWidth -= fixedColumn.getWidth(); + } + if (remainingWidth > minWidth) { + fillColumn.setWidth(remainingWidth); + } + } + }); + } + /** * Copy the given text to the clipboard. */ diff --git a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/UiUtils.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/UiUtils.java index 7370d76f..5d1ab2a9 100644 --- a/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/UiUtils.java +++ b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/utils/UiUtils.java @@ -8,6 +8,8 @@ import java.io.InputStream; import java.net.URI; import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; @@ -29,6 +31,8 @@ import org.eclipse.core.commands.NotHandledException; import org.eclipse.core.commands.ParameterizedCommand; import org.eclipse.core.commands.common.NotDefinedException; +import org.eclipse.core.filesystem.EFS; +import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.preferences.InstanceScope; @@ -221,6 +225,27 @@ public static IEditorPart openInEditor(IFile file) { return null; } + /** + * Opens the given local filesystem file in an editor. + */ + public static IEditorPart openLocalFileInEditor(Path file) { + if (file == null || !Files.exists(file)) { + CopilotCore.LOGGER.error(new IllegalArgumentException("Cannot open editor: local file is null or doesn't exist")); + return null; + } + + try { + IWorkbenchPage page = getActivePage(); + if (page != null) { + IFileStore fileStore = EFS.getLocalFileSystem().getStore(file.toUri()); + return IDE.openEditorOnFileStore(page, fileStore); + } + } catch (PartInitException e) { + CopilotCore.LOGGER.error(e); + } + return null; + } + /** * Opens the file in the editor. */ diff --git a/pom.xml b/pom.xml index b49c8076..2a9b33d6 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ ${base.name} - 0.18.0-SNAPSHOT + 0.20.0-SNAPSHOT GitHub Copilot 4.0.13 3.6.0