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..e58cf111 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,26 @@ 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.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..f4eb15ed 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.19.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..a9bdb552 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.19.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..3de71350 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.19.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..b340fbec 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.19.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..4674eab8 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.19.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..4bffe01f 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.19.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..f42e08b2 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.19.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.19.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..024935d8 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.19.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/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 1e40287a..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); } } @@ -366,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 8f74d5dd..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,10 +29,10 @@ 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; @@ -51,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; @@ -146,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. 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 85e26f98..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,10 +46,10 @@ 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; @@ -72,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; @@ -374,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. */ @@ -708,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 e9412e2f..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 @@ -17,6 +17,7 @@ public class CopilotAgentSettings { @SerializedName("maxToolCallingLoop") private int agentMaxRequests; private boolean enableSkills; + private boolean autoCompress; private String transcriptDirectory; @@ -178,6 +179,14 @@ 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; } @@ -212,7 +221,7 @@ public ToolsSettings getTools() { @Override public int hashCode() { - return Objects.hash(agentMaxRequests, enableSkills, transcriptDirectory, + return Objects.hash(agentMaxRequests, enableSkills, autoCompress, transcriptDirectory, editorHandlesAllConfirmation, autoApproveUnmatchedTerminal, autoApproveUnmatchedFileOp, tools); } @@ -229,6 +238,7 @@ public boolean equals(Object obj) { } CopilotAgentSettings other = (CopilotAgentSettings) obj; return agentMaxRequests == other.agentMaxRequests && enableSkills == other.enableSkills + && autoCompress == other.autoCompress && Objects.equals(transcriptDirectory, other.transcriptDirectory) && editorHandlesAllConfirmation == other.editorHandlesAllConfirmation && autoApproveUnmatchedTerminal == other.autoApproveUnmatchedTerminal @@ -241,6 +251,7 @@ 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); 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/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/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/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..2418d3ba 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..628567ee 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..ee703343 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.19.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 index 2a76f5f9..e5ddf4e8 100644 --- 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 @@ -340,3 +340,76 @@ approval #### 📸 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/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/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..ffca534c 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.19.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.19.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..eed9986d 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.19.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.19.0", + com.microsoft.copilot.eclipse.ui;bundle-version="0.19.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..71145643 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.19.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.19.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..b961e910 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.19.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.19.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..6d01be66 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.19.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.19.0", + com.microsoft.copilot.eclipse.ui;bundle-version="0.19.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.19.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 index 5d9b9573..ba60a62e 100644 --- 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 @@ -9,15 +9,18 @@ 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; @@ -46,6 +49,9 @@ class FileOperationConfirmationHandlerTests { private AttachedFileRegistry attachedFileRegistry; private FileOperationConfirmationHandler handler; + @TempDir + private Path customizationBase; + @BeforeEach void setUp() { attachedFileRegistry = new AttachedFileRegistry(); @@ -677,6 +683,90 @@ void evaluate_priorityOrder_sessionFolderBeatsOutsideWorkspace() { 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) { 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 2892f521..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 @@ -58,6 +58,7 @@ 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() @@ -92,6 +93,7 @@ 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() @@ -130,6 +132,7 @@ 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() @@ -169,6 +172,7 @@ 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() 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 066f4400..ca0e9872 100644 --- a/com.microsoft.copilot.eclipse.ui/META-INF/MANIFEST.MF +++ b/com.microsoft.copilot.eclipse.ui/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ 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.19.0.qualifier Bundle-Vendor: GitHub Copilot Bundle-Localization: plugin Export-Package: com.microsoft.copilot.eclipse.ui, @@ -25,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.19.0", + com.microsoft.copilot.eclipse.terminal.api;bundle-version="0.19.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/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.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/WHATISNEW.md b/com.microsoft.copilot.eclipse.ui/intro/whatsnew/WHATISNEW.md index 653837f7..12433a4a 100644 --- a/com.microsoft.copilot.eclipse.ui/intro/whatsnew/WHATISNEW.md +++ b/com.microsoft.copilot.eclipse.ui/intro/whatsnew/WHATISNEW.md @@ -1,3 +1,35 @@ +# GitHub Copilot 0.19.0 Release Notes + +### 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. + +![Tool Auto Approve](0.19.0/auto-approve.png) + +--- + +### 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. + +The chat view also shows compression status while Copilot is compacting the conversation, making long-running sessions easier to follow. + +--- + +### 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. + +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. + +--- + +### 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. + +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. + +--- + # GitHub Copilot 0.18.0 Release Notes ### Prepare for the Upcoming Usage-Based Billing @@ -65,35 +97,3 @@ Bring Your Own Key (BYOK) is now available to GitHub Copilot Business and Enterp ### 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. - ---- - -### - -# 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. - -![Tool Calling in Ask Mode](0.16.0/tool_calling_in_ask_mode.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. - -![New Selector](0.16.0/new_selector.png) - -- **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) - ---- - -### Syntax Highlighting in Chat - -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. - -![Syntax Highlighting](0.16.0/syntax_highlighting.png) - diff --git a/com.microsoft.copilot.eclipse.ui/plugin.xml b/com.microsoft.copilot.eclipse.ui/plugin.xml index a3d4a20a..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">

0) { this.processMessageLine(messageBuffer.toString()); messageBuffer.setLength(0); @@ -603,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; @@ -626,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; } /** @@ -650,11 +655,34 @@ public CompletableFuture requestToolExecuti reset(); 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().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 c8bff236..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 @@ -4,7 +4,9 @@ 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; @@ -32,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; @@ -60,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; @@ -79,6 +83,8 @@ 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; @@ -146,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"; @@ -159,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; @@ -396,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(); } @@ -473,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(); + } } }; @@ -1207,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.) @@ -1361,6 +1425,7 @@ public void onCancel() { this.subagentConversationId = null; this.lastRunSubagentToolCallId = null; + cancelCurrentTerminalCommand(); if (persistenceManager != null && StringUtils.isNotBlank(this.conversationId)) { persistenceManager.markRunningToolCallsCancelledAndPersist(this.conversationId); @@ -1374,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 @@ -1550,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) { @@ -1625,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 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. */ - public void layout(boolean changed, boolean all) { - parent.layout(changed, all); + 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); } /** @@ -1741,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); } /** @@ -1769,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); } } @@ -1806,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 ebc307a0..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 @@ -119,10 +119,7 @@ public void cancelConfirmation() { && StringUtils.isNotEmpty(this.cancelMessage)) { new AgentToolCancelLabel(parent, SWT.NONE, this.cancelMessage); } - this.dispose(); - if (parent != null && !parent.isDisposed()) { - parent.requestLayout(); - } + disposeAndRequestParentLayout(); }, this); } } @@ -318,6 +315,10 @@ private void acceptAndDispose(ConfirmationAction action) { new LanguageModelToolConfirmationResult( ToolConfirmationResult.ACCEPT)); + disposeAndRequestParentLayout(); + } + + private void disposeAndRequestParentLayout() { Composite parent = this.getParent(); this.dispose(); if (parent != null && !parent.isDisposed()) { 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/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/FileOperationConfirmationHandler.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/confirmation/FileOperationConfirmationHandler.java index 313c56c2..ba861ed4 100644 --- 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 @@ -28,8 +28,11 @@ 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; /** @@ -171,6 +174,17 @@ private ConfirmationResult evaluateAutoApprovalEnabled( } } + // 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)); @@ -338,6 +352,39 @@ private boolean isOutsideWorkspace(InvokeClientToolConfirmationParams params) { 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); 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/services/AgentToolService.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/chat/services/AgentToolService.java index be236d9c..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 @@ -294,7 +294,7 @@ public CompletableFuture onToolConfirmation SwtUtils.invokeOnDisplayThread(() -> { ref.set(activeTurnWidget.requestToolExecutionConfirmation( content, params.getInput())); - boundChatView.getChatContentViewer().refreshScrollerLayout(); + boundChatView.getChatContentViewer().refreshLayoutFull(); }); CompletableFuture future = ref.get(); 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/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/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/AutoApprovePreferencePage.java b/com.microsoft.copilot.eclipse.ui/src/com/microsoft/copilot/eclipse/ui/preferences/AutoApprovePreferencePage.java index b4b8b3f9..fb0be2c0 100644 --- 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 @@ -6,6 +6,8 @@ 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; @@ -51,12 +53,28 @@ protected Control createContents(Composite parent) { Messages.preferences_page_auto_approve_disabled_by_organization); } - Composite root = new Composite(parent, SWT.NONE); + // 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); - root.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); IPreferenceStore store = getPreferenceStore(); terminalSection = new TerminalAutoApproveSection(root, SWT.NONE); @@ -72,9 +90,17 @@ protected Control createContents(Composite parent) { globalSection = new GlobalAutoApproveSection(root, SWT.NONE); globalSection.loadFromPreferences(store); - root.addDisposeListener(e -> unbindMcpConfigService()); + 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 root; + return scrolled; } @Override 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 index 93bc9d21..c299d40a 100644 --- 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 @@ -112,13 +112,14 @@ private void createContents() { private void createTable(Composite parent) { tableViewer = new TableViewer(parent, - SWT.BORDER | SWT.FULL_SELECTION | SWT.SINGLE); + 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); @@ -177,6 +178,8 @@ public Color getForeground(Object element) { ? 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()); 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 e3b78dad..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 @@ -92,6 +92,8 @@ 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() @@ -125,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))); } /** @@ -162,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: @@ -253,13 +257,40 @@ 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())); 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 index bc52d63e..357234b4 100644 --- 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 @@ -90,10 +90,11 @@ private void createContents() { // Tree viewer for server/tool approval treeViewer = new CheckboxTreeViewer(group, - SWT.BORDER | SWT.FULL_SELECTION); + 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()); 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/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 index db41cb10..46664360 100644 --- 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 @@ -30,6 +30,7 @@ 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 @@ -90,13 +91,14 @@ private void createContents() { private void createTable(Composite parent) { tableViewer = new TableViewer(parent, - SWT.BORDER | SWT.FULL_SELECTION | SWT.SINGLE); + 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); @@ -123,6 +125,8 @@ public String getText(Object element) { : Messages.preferences_page_auto_approve_deny; } }); + SwtUtils.resizeColumnToFillTable(table, statusCol.getColumn(), 100, + commandCol.getColumn()); tableViewer.setContentProvider(ArrayContentProvider.getInstance()); tableViewer.addSelectionChangedListener(e -> updateButtonState()); 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/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/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..7795edfa 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ ${base.name} - 0.18.0-SNAPSHOT + 0.19.0-SNAPSHOT GitHub Copilot 4.0.13 3.6.0