From 2cc54b35f6e74ab022b5a36c06d52d892a9c5f2d Mon Sep 17 00:00:00 2001 From: akshathayadav378-boop Date: Fri, 20 Nov 2026 11:04:36 +0800 Subject: [PATCH 1/6] test(markdown): allow large render test to finish (#4664) The large Markdown re-render test renders plugins/README.md repeatedly and can exceed Vitest's default 5 s timeout under full-suite load; it gets a 20 s timeout like other heavy tests. Co-authored-by: akshathayadav378-boop <287247196+akshathayadav378-boop@users.noreply.github.com> --- src/features/viewers/markdown/render.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/features/viewers/markdown/render.test.ts b/src/features/viewers/markdown/render.test.ts index 20cc5efc0..a6bb1daf3 100644 --- a/src/features/viewers/markdown/render.test.ts +++ b/src/features/viewers/markdown/render.test.ts @@ -332,7 +332,7 @@ describe("markdown preview re-rendering", () => { same(render, doc(blocks)); }); - it("renders a large document as a whole, sanitizing only what an edit changed", () => { + it("renders a large document as a whole, sanitizing only what an edit changed", { timeout: 20_000 }, () => { const asWritten = readFileSync(resolve(import.meta.dirname, "../../../../plugins/README.md"), "utf8"); // As written, a bare `` swallows the rest of the file, so it is rendered as a whole. for (const [readme, reuses] of [ From da79a73def80b08dc7b4f91fe170e6fc5e5e0c81 Mon Sep 17 00:00:00 2001 From: HEOJUNFO <100739943+HEOJUNFO@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:04:44 +0900 Subject: [PATCH 2/6] fix(http-client): keep the whole value of a Spring params/headers condition (#4666) Spring params/headers conditions were split with split("=", 2), which drops everything after a second '='; only the first '=' divides name and value now, as in Spring. Verified with http-client vitest. Co-authored-by: HEOJUNFO <100739943+HEOJUNFO@users.noreply.github.com> --- src/features/http-client/spring/endpoints.ts | 10 +++++-- .../http-client/spring/spring.test.ts | 26 +++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/features/http-client/spring/endpoints.ts b/src/features/http-client/spring/endpoints.ts index 22dbb32f8..72fe1e815 100644 --- a/src/features/http-client/spring/endpoints.ts +++ b/src/features/http-client/spring/endpoints.ts @@ -237,6 +237,12 @@ function annotation(p: Param, name: string): Annotation | undefined { const isMap = (type: string) => /^(java\.util\.)?(Map|MultiValueMap|HttpHeaders|LinkedMultiValueMap|HashMap)\b/.test(type); +/** `name=value` of a `params`/`headers` condition. Only the first "=" divides it: `Accept=text/plain;charset=UTF-8`. */ +function condition(cond: string): [name: string, value: string | undefined] { + const at = cond.indexOf("="); + return at < 0 ? [cond, undefined] : [cond.slice(0, at), cond.slice(at + 1)]; +} + function endpoint(cls: ClassDecl, method: ClassDecl["methods"][number], c: Constants): Endpoint | null { const m = mapping(method.annotations); if (!m) return null; @@ -267,12 +273,12 @@ function endpoint(cls: ClassDecl, method: ClassDecl["methods"][number], c: Const } // `params = "a=1"` / `headers = "X-Api=1"` narrow the mapping: the request must carry them. for (const cond of [...c.strings(classMapping?.args.get("params")), ...c.strings(m.ann.args.get("params"))]) { - const [name, value] = cond.split("=", 2); + const [name, value] = condition(cond); if (name && !cond.includes("!") && !query.some((q) => q.name === name.trim())) query.push({ name: name.trim(), value: value?.trim() ?? null }); } for (const cond of [...c.strings(classMapping?.args.get("headers")), ...c.strings(m.ann.args.get("headers"))]) { - const [name, value] = cond.split("=", 2); + const [name, value] = condition(cond); if (name && !cond.includes("!") && value !== undefined) headers.push({ name: name.trim(), value: value.trim() }); } const first = (key: string) => diff --git a/src/features/http-client/spring/spring.test.ts b/src/features/http-client/spring/spring.test.ts index ac0cbb974..9fdc00660 100644 --- a/src/features/http-client/spring/spring.test.ts +++ b/src/features/http-client/spring/spring.test.ts @@ -198,6 +198,32 @@ describe("Spring mappings (Kotlin)", () => { }); }); +describe("mapping conditions", () => { + it("keeps a value that has its own '='", () => { + const [controller] = springControllers(`package demo; +import org.springframework.web.bind.annotation.*; + +@RestController +public class ReportController { + @GetMapping(path = "/report", headers = "Accept=text/plain;charset=UTF-8", params = "range=a=b") + public String report() { return ""; } + + @PostMapping(path = "/upload", headers = {"Content-Type=multipart/form-data; boundary=xyz", "X-Token=YWJj=="}) + public void upload() {} +} +`); + const [report, upload] = controller!.endpoints; + expect(report).toMatchObject({ + query: [{ name: "range", value: "a=b" }], + headers: [{ name: "Accept", value: "text/plain;charset=UTF-8" }], + }); + expect(upload!.headers).toEqual([ + { name: "Content-Type", value: "multipart/form-data; boundary=xyz" }, + { name: "X-Token", value: "YWJj==" }, + ]); + }); +}); + describe("non-controllers", () => { it("ignores classes that are not controllers and files without any", () => { expect(springControllers('@Service class A { @GetMapping("/x") void a() {} }')).toEqual([]); From c483c3b76ff58d93ffeb17debbcb58420cff7e7e Mon Sep 17 00:00:00 2001 From: C3B6 <93749947+0xC3B6@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:05:24 +0800 Subject: [PATCH 3/6] perf(http-client): limit cached response details to four (#4659) The HTTP Client kept every exchange's full request and response in memory for the whole session, even after its row left the backend's 100-entry history. The history list is capped at 100 like the backend, and only the four most recently viewed exchanges keep their details; older rows reload theirs from the saved history (which stores the full exchange) when selected. Verified with http-client vitest and typecheck. Co-authored-by: 0xC3B6 <93749947+0xC3B6@users.noreply.github.com> --- src/features/http-client/HttpClientView.tsx | 2 +- .../http-client/responseFind.test.tsx | 4 +- src/features/http-client/store.test.ts | 40 ++++++++++++++++++- src/features/http-client/store.ts | 31 +++++++++----- 4 files changed, 64 insertions(+), 13 deletions(-) diff --git a/src/features/http-client/HttpClientView.tsx b/src/features/http-client/HttpClientView.tsx index 7e811e46b..e6a97a99f 100644 --- a/src/features/http-client/HttpClientView.tsx +++ b/src/features/http-client/HttpClientView.tsx @@ -265,7 +265,7 @@ function HeaderTable({ headers }: { headers: Array<[string, string]> }) { export function HttpClientView() { const history = useHttpClient((s) => s.history); const selected = useHttpClient((s) => s.selected); - const exchange = useHttpClient((s) => (s.selected ? s.exchanges[s.selected] : undefined)); + const exchange = useHttpClient((s) => s.exchanges.find((e) => e.entry.id === s.selected)); const running = useHttpClient((s) => s.running); useEffect(() => { void refreshHistory(); diff --git a/src/features/http-client/responseFind.test.tsx b/src/features/http-client/responseFind.test.tsx index fc45a32e1..d22111182 100644 --- a/src/features/http-client/responseFind.test.tsx +++ b/src/features/http-client/responseFind.test.tsx @@ -39,11 +39,11 @@ const exchange: HttpExchange = { }; describe("HTTP response find", () => { - afterEach(() => useHttpClient.setState({ history: [], exchanges: {}, selected: null })); + afterEach(() => useHttpClient.setState({ history: [], exchanges: [], selected: null })); it("opens a find bar with ⌘F in the response and marks the matches", () => { Element.prototype.scrollIntoView ??= () => {}; - useHttpClient.setState({ history: [exchange.entry], exchanges: { e1: exchange }, selected: "e1" }); + useHttpClient.setState({ history: [exchange.entry], exchanges: [exchange], selected: "e1" }); render(<HttpClientView />); const body = screen.getByLabelText("Response body"); fireEvent.keyDown(body, { key: "f", metaKey: true, ctrlKey: true }); diff --git a/src/features/http-client/store.test.ts b/src/features/http-client/store.test.ts index aaedff599..e4153357c 100644 --- a/src/features/http-client/store.test.ts +++ b/src/features/http-client/store.test.ts @@ -1,10 +1,11 @@ import { beforeEach, expect, it, vi } from "vitest"; import type { HttpExchange, HttpRequestBlock } from "@/platform/ipc"; -import { runAll, runRequest, setEnvironment, useHttpClient } from "./store"; +import { runAll, runRequest, selectEntry, setEnvironment, useHttpClient } from "./store"; const backend = vi.hoisted(() => ({ httpEnvironments: vi.fn(), httpExecute: vi.fn(), + httpHistoryGet: vi.fn(), httpRequests: vi.fn(), })); vi.mock("@/platform/ipc", async (importOriginal) => { @@ -95,3 +96,40 @@ it.each(["A", "missing"])("validates the starting choice %s once when environmen expect(backend.httpExecute).toHaveBeenNthCalledWith(1, expect.any(Number), path, text, 0, environment); expect(backend.httpExecute).toHaveBeenNthCalledWith(2, expect.any(Number), path, text, 1, environment); }); + +function response(id: string): HttpExchange { + return { ...exchange, entry: { ...exchange.entry, id } }; +} + +it("keeps 100 history rows and the four most recently used exchanges", async () => { + for (let n = 0; n < 101; n++) { + backend.httpExecute.mockResolvedValueOnce(ok(response(String(n)))); + await runRequest(null, text, 0); + } + const state = useHttpClient.getState(); + expect(state.history).toHaveLength(100); + expect(state.history.at(-1)?.id).toBe("1"); + expect(state.exchanges).toHaveLength(4); + + await selectEntry("97"); // Touch the oldest resident before opening a cold row. + backend.httpHistoryGet.mockResolvedValueOnce(ok(response("1"))); + await selectEntry("1"); + await selectEntry("97"); + expect(backend.httpHistoryGet.mock.calls).toEqual([["1"]]); + expect(useHttpClient.getState().exchanges.map((e) => e.entry.id)).toEqual(["97", "1", "100", "99"]); +}); + +it("keeps the latest selection when two cold reads finish out of order", async () => { + let finishFirst!: (result: ReturnType<typeof ok<HttpExchange>>) => void; + const first = new Promise<ReturnType<typeof ok<HttpExchange>>>((resolve) => { + finishFirst = resolve; + }); + backend.httpHistoryGet.mockReturnValueOnce(first).mockResolvedValueOnce(ok(response("b"))); + const pending = selectEntry("a"); + await selectEntry("b"); + finishFirst(ok(response("a"))); + await pending; + const { selected, exchanges } = useHttpClient.getState(); + expect(selected).toBe("b"); + expect(exchanges).toEqual([response("b")]); +}); diff --git a/src/features/http-client/store.ts b/src/features/http-client/store.ts index 57576bba0..38b456e5f 100644 --- a/src/features/http-client/store.ts +++ b/src/features/http-client/store.ts @@ -14,6 +14,9 @@ import { writeClipboardText } from "@/platform/clipboard"; import { editorService, notifications, showServiceView, showStatusInfo } from "@/workbench/contributions"; export const SERVICE_VIEW = "httpClient"; +// Same bound as ide_http::history::MAX_ENTRIES. Only recent rows keep their bodies in the UI. +const HISTORY_LIMIT = 100; +const EXCHANGE_LIMIT = 4; const ENV_KEY = "openidea.httpClient.environments"; function readEnvChoices(): Record<string, string> { @@ -41,8 +44,8 @@ interface HttpClientState { environments: Record<string, string[]>; /** History entries, newest first (this session's runs included). */ history: HttpHistoryEntry[]; - /** Loaded exchanges by entry id. */ - exchanges: Record<string, HttpExchange>; + /** Loaded exchanges, most recently viewed first. */ + exchanges: HttpExchange[]; selected: string | null; running: Running | null; } @@ -51,7 +54,7 @@ export const useHttpClient = create<HttpClientState>(() => ({ envByFile: readEnvChoices(), environments: {}, history: [], - exchanges: {}, + exchanges: [], selected: null, running: null, })); @@ -96,6 +99,10 @@ function effectiveEnvironment(path: string | null, selection?: string | null): s return null; } +function rememberExchange(exchange: HttpExchange, recent: HttpExchange[]) { + return [exchange, ...recent.filter((e) => e.entry.id !== exchange.entry.id)].slice(0, EXCHANGE_LIMIT); +} + export async function refreshHistory() { try { const history = await call(commands.httpHistory()); @@ -106,12 +113,18 @@ export async function refreshHistory() { } export async function selectEntry(id: string) { + const { exchanges } = useHttpClient.getState(); + const cached = exchanges.find((e) => e.entry.id === id); + if (cached) { + useHttpClient.setState({ selected: id, exchanges: rememberExchange(cached, exchanges) }); + return; + } useHttpClient.setState({ selected: id }); - if (useHttpClient.getState().exchanges[id]) return; try { const ex = await call(commands.httpHistoryGet(id)); - useHttpClient.setState((s) => ({ exchanges: { ...s.exchanges, [id]: ex } })); + useHttpClient.setState((s) => (s.selected === id ? { exchanges: rememberExchange(ex, s.exchanges) } : s)); } catch (e) { + if (useHttpClient.getState().selected !== id) return; notifications().notify({ level: "error", title: "Cannot open the response", @@ -122,7 +135,7 @@ export async function selectEntry(id: string) { export async function clearHistory() { await call(commands.httpHistoryClear()); - useHttpClient.setState({ history: [], exchanges: {}, selected: null }); + useHttpClient.setState({ history: [], exchanges: [], selected: null }); } export function parseRequests(text: string): Promise<HttpRequestBlock[]> { @@ -159,8 +172,8 @@ export async function runRequest( const env = batchEnvironment === undefined ? effectiveEnvironment(path) : batchEnvironment; const ex = await call(commands.httpExecute(request, path, text, index, env)); useHttpClient.setState((s) => ({ - history: [ex.entry, ...s.history.filter((h) => h.id !== ex.entry.id)], - exchanges: { ...s.exchanges, [ex.entry.id]: ex }, + history: [ex.entry, ...s.history.filter((h) => h.id !== ex.entry.id)].slice(0, HISTORY_LIMIT), + exchanges: rememberExchange(ex, s.exchanges), selected: ex.entry.id, })); return true; @@ -235,5 +248,5 @@ export function cancelRunning() { /** The window switched projects: history, responses and environments belong to the previous one. */ export function resetHttpClient() { cancelRunning(); - useHttpClient.setState({ environments: {}, history: [], exchanges: {}, selected: null, running: null }); + useHttpClient.setState({ environments: {}, history: [], exchanges: [], selected: null, running: null }); } From dbef3cdc9645360590d128864b6ef1bd7dd2e485 Mon Sep 17 00:00:00 2001 From: Deng Liu <deng@sesame.com> Date: Thu, 19 Nov 2026 19:06:32 -0800 Subject: [PATCH 4/6] fix(agents): support Auto-only Copilot catalogs (#4661) Copilot can return an enabled Auto tier with an empty direct-model list; the catalog parser treated that as an empty catalog and forced the fallback transport. An enabled Auto tier now yields the auto model. Verified with cargo test -p ide-agent copilot and clippy. Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com> --- crates/ide-agent/src/native/copilot/models.rs | 16 ++++- crates/ide-agent/src/native/copilot/tests.rs | 66 +++++++++++++++++++ 2 files changed, 80 insertions(+), 2 deletions(-) diff --git a/crates/ide-agent/src/native/copilot/models.rs b/crates/ide-agent/src/native/copilot/models.rs index 95154a2ad..d6d0ace9f 100644 --- a/crates/ide-agent/src/native/copilot/models.rs +++ b/crates/ide-agent/src/native/copilot/models.rs @@ -312,7 +312,7 @@ impl Settings { } /// Parses `models.list` + optional `models.listTokenPriceUnits` into catalog entries, -/// prepending `"auto"` when not already in the list. +/// prepending `"auto"` when direct models are present or Copilot advertises an enabled Auto tier. pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<ModelEntry> { let units = parse_price_units(price_units); let raw = list @@ -322,7 +322,7 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo .map(Vec::as_slice) .unwrap_or_default(); let mut out = Vec::new(); - if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && !raw.is_empty() { + if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && (!raw.is_empty() || auto_model_available(list)) { out.push(ModelEntry { id: "auto".into(), name: "Auto".into(), @@ -344,6 +344,18 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo out } +fn auto_model_available(list: &Value) -> bool { + let Some(auto) = list.get("auto") else { return false }; + if auto.get("enabled").or_else(|| auto.pointer("/status/enabled")).and_then(Value::as_bool) == Some(false) { + return false; + } + let Some(tiers) = auto.get("tiers").and_then(Value::as_array) else { return auto.is_object() }; + tiers.is_empty() + || tiers.iter().any(|tier| { + tier.get("enabled").or_else(|| tier.pointer("/status/enabled")).and_then(Value::as_bool) != Some(false) + }) +} + fn parse_model(m: &Value, units: &HashMap<String, PriceUnit>) -> Option<ModelEntry> { let id = str_of(m, "id")?.to_owned(); if m.get("model_picker_enabled").and_then(Value::as_bool) == Some(false) diff --git a/crates/ide-agent/src/native/copilot/tests.rs b/crates/ide-agent/src/native/copilot/tests.rs index a4de2ca99..bc50f0ff7 100644 --- a/crates/ide-agent/src/native/copilot/tests.rs +++ b/crates/ide-agent/src/native/copilot/tests.rs @@ -110,6 +110,72 @@ fn sample_price_units() -> Value { }) } +#[test] +fn parses_an_enabled_auto_only_catalog() { + let list = json!({ + "models": [], + "auto": { + "defaultTier": "balance", + "tiers": [ + { + "id": "balance", + "displayName": "Standard", + "type": "auto", + "fusionTier": "standard", + "status": { "enabled": true, "pickerVisible": true } + }, + { + "id": "hydrafusion", + "displayName": "High", + "type": "fusion", + "fusionTier": "high", + "status": { + "enabled": false, + "pickerVisible": true, + "reason": "user_not_eligible" + } + }, + { + "id": "fast", + "displayName": "Fast", + "type": "auto", + "status": { "enabled": true, "pickerVisible": false } + } + ], + "providerId": "copilot" + }, + "imageModels": [] + }); + + let catalog = models::parse_catalog(&list, None); + assert_eq!(catalog.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["auto"]); + assert_eq!(Settings::new(&catalog, &UserDefaults::default()).model, "auto"); + + let options = + config::parse_options(&models::config_options(&catalog, &Settings::new(&catalog, &UserDefaults::default()))); + let model = options.iter().find(|option| option.id == MODEL).unwrap(); + assert_eq!(model.current.as_deref(), Some("auto")); + assert_eq!(model.values.iter().map(|value| value.value.as_str()).collect::<Vec<_>>(), ["auto"]); +} + +#[test] +fn rejects_an_auto_only_catalog_when_every_tier_is_disabled() { + let list = json!({ + "models": [], + "auto": { + "defaultTier": "balance", + "tiers": [ + { + "id": "balance", + "status": { "enabled": false, "pickerVisible": true } + } + ] + } + }); + + assert!(models::parse_catalog(&list, None).is_empty()); +} + #[test] fn parses_tiered_context_windows_pricing_and_uses_copilots_own_defaults() { let catalog = models::parse_catalog(&sample_models_list(), Some(&sample_price_units())); From d86ff872af886af638950ba0945c4932b84e6c3e Mon Sep 17 00:00:00 2001 From: Deng Liu <deng@sesame.com> Date: Thu, 19 Nov 2026 19:07:37 -0800 Subject: [PATCH 5/6] fix(agents): recover model controls for fallback sessions (#4662) A session whose agent fell back to a configuration without a model option kept a stale model label and offered no way to pick another model. The composer rebuilds the model control from the provider's catalog and set_config accepts a model from that catalog, switching through the same path as other discovered models. Verified with cargo test -p ide-agent, clippy, agents vitest and typecheck. Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com> --- crates/ide-agent/src/lib.rs | 28 ++++++++--- crates/ide-agent/src/tests.rs | 50 +++++++++++++++++++ src/features/agents/ConfigPickers.tsx | 2 +- src/features/agents/modelRefresh.test.tsx | 38 ++++++++++++++ .../agents/session/SessionComposer.tsx | 33 +++++++++--- src/features/agents/store.ts | 2 +- 6 files changed, 136 insertions(+), 17 deletions(-) diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 06e0a92e6..1ce2b170b 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -1126,6 +1126,16 @@ impl AgentManager { /// Changes a session setting (model, mode…): right away when the agent runs, else when it next starts. pub async fn set_config(&self, id: &str, option: &str, value: String) -> IdeResult<()> { let task = self.task(id)?; + let provider = task.state.lock().task.provider.clone(); + let discovered = self + .shared + .paths + .catalogs + .cached(&self.shared, &provider) + .config + .iter() + .find(|o| o.id == option && o.category.as_deref() == Some("model")) + .cloned(); let (target, change) = { let mut s = task.state.lock(); let busy = s.busy; @@ -1146,17 +1156,19 @@ impl AgentManager { task.emit_task(); return Ok(()); } - let target = s - .task - .config - .iter() - .find(|o| o.id == option) - .ok_or_else(|| IdeError::not_found("no such setting"))? - .clone(); + let session_target = s.task.config.iter().find(|o| o.id == option).cloned(); + let recovered_model = session_target.is_none(); + let target = match session_target { + Some(target) => target, + None if discovered.is_some() => discovered.unwrap(), + None => return Err(IdeError::not_found("no such setting")), + }; if s.pending_model.is_some() && config::is_per_model_option(&target) { return Err(IdeError::invalid("This setting is not available on the selected model")); } - if !target.values.iter().any(|v| v.value == value) { + if recovered_model { + (target, None) + } else if !target.values.iter().any(|v| v.value == value) { if target.category.as_deref() != Some("model") { return Err(IdeError::invalid(format!("{} has no value {value}", target.name))); } diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index 7308f39f1..95d65b435 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -2333,6 +2333,56 @@ async fn idle_model_switches_discover_controls_and_no_control_models_without_ano restored.shutdown(); } +#[tokio::test(flavor = "multi_thread")] +async fn session_without_a_model_option_can_select_from_a_recovered_catalog() { + let tmp = tempfile::tempdir().unwrap(); + let agent = Arc::new(FakeAgent::default()); + *agent.model_options.lock() = HashMap::from([ + ("big".into(), effort_options(&["low", "high"], "high")), + ("small".into(), effort_options(&["minimal", "medium"], "minimal")), + ]); + let mgr = manager(tmp.path(), agent); + let task = mgr + .create(NewAgentTask { + prompt: text("again"), + provider: "claude-acp".into(), + isolation: Isolation::Local, + ..Default::default() + }) + .await + .unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + + let spec = mgr.shared.spec("claude-acp").unwrap(); + let (_, flight) = mgr.shared.paths.catalogs.request(&mgr.shared, spec, true, None); + if let Some(mut ready) = flight { + tokio::time::timeout(Duration::from_secs(5), async { + while !*ready.borrow_and_update() { + ready.changed().await.unwrap(); + } + }) + .await + .unwrap(); + } + { + let task = mgr.task(&task.id).unwrap(); + let mut state = task.state.lock(); + state.task.config.retain(|option| option.category.as_deref() != Some("model")); + state.task.model = Some("stale-model".into()); + } + + mgr.set_config(&task.id, "model", "small".into()).await.unwrap(); + let task = mgr.task(&task.id).unwrap(); + { + let state = task.state.lock(); + assert_eq!(state.task.model.as_deref(), Some("small")); + let model = state.task.config.iter().find(|option| option.category.as_deref() == Some("model")).unwrap(); + assert_eq!(model.current.as_deref(), Some("small")); + assert!(model.values.iter().any(|value| value.value == "small")); + } + mgr.shutdown(); +} + #[tokio::test(flavor = "multi_thread")] async fn idle_model_discovery_failure_restores_the_previous_choice_without_claiming_no_controls() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/features/agents/ConfigPickers.tsx b/src/features/agents/ConfigPickers.tsx index f6d514452..58ff1cba6 100644 --- a/src/features/agents/ConfigPickers.tsx +++ b/src/features/agents/ConfigPickers.tsx @@ -284,7 +284,7 @@ function ModelPicker({ const pinnedModels = useAgents((s) => s.pinnedModels); const anchor = useRef<HTMLButtonElement>(null); const selectedModel = selected(model, modelValue); - const unavailable = modelRefresh?.draft && modelValue !== null && !selectedModel; + const unavailable = !!modelRefresh && modelValue !== null && !selectedModel; const modelName = unavailable ? tx`${modelValue} (unavailable)` : (selectedModel?.name ?? (modelRefresh ? modelValue : null) ?? tx("Default")); diff --git a/src/features/agents/modelRefresh.test.tsx b/src/features/agents/modelRefresh.test.tsx index abc61b9a0..2ae959f8f 100644 --- a/src/features/agents/modelRefresh.test.tsx +++ b/src/features/agents/modelRefresh.test.tsx @@ -251,6 +251,44 @@ it("refreshes an existing chat's searchable model choices and switches through i expect(useAgents.getState().draft).toBe(draft); }); +it("recovers a model picker after a Copilot ACP fallback removed the session option", async () => { + const task: AgentTask = { + id: "fallback-task", + title: "Recovered chat", + provider: "first", + status: "ready", + isolation: "local", + model: "stale-model", + cwd: "/models", + branch: null, + base: null, + baseCommit: null, + error: null, + createdMs: 0, + updatedMs: 0, + config: [{ ...option("mode", "mode", ["plan", "act"]), name: "Mode" }], + commands: [], + usage: null, + queue: [], + }; + const input = { kind: SESSION_KIND, key: sessionKey(task.id), data: { task: task.id } }; + backend.providers[0]!.config = []; + backend.tasks = [task]; + backend.activeInput = input; + await connect(); + backend.refresh.mockResolvedValueOnce(ok(catalog("first", { config: [option("model", "model", ["auto"])] }))); + + render(<SessionEditor input={input} />); + const modelButton = screen.getByRole("button", { name: "Model" }); + expect(modelButton).toHaveTextContent("stale-model (unavailable)"); + fireEvent.click(modelButton); + expect(await screen.findByRole("option", { name: "auto" })).toBeVisible(); + fireEvent.click(screen.getByRole("option", { name: "auto" })); + + expect(backend.refresh).toHaveBeenCalledWith("first", false, null); + expect(backend.setConfig).toHaveBeenCalledExactlyOnceWith("fallback-task", "model", "auto"); +}); + it("keeps cached choices usable while refreshing and shares the completion/cooldown from another window", async () => { backend.refresh.mockImplementation(async (id: string) => ok(catalog(id, { refreshing: true }))); render(<HomeEditor />); diff --git a/src/features/agents/session/SessionComposer.tsx b/src/features/agents/session/SessionComposer.tsx index 8401cfdcd..3a72085b7 100644 --- a/src/features/agents/session/SessionComposer.tsx +++ b/src/features/agents/session/SessionComposer.tsx @@ -1,4 +1,4 @@ -import type { AgentChange, AgentCommit, AgentEntry, AgentTask } from "@/bindings"; +import type { AgentChange, AgentCommit, AgentConfigOption, AgentEntry, AgentTask } from "@/bindings"; import { executeAction } from "@/platform/actions"; import { tx, useTx } from "@/platform/i18n"; import { useProject } from "@/platform/project"; @@ -161,18 +161,37 @@ export function SessionComposer({ const catalog = useAgents((s) => s.modelCatalogs.get(task.provider)); const requestingModels = useAgents((s) => s.modelRequests.has(task.provider)); const model = task.config.find((o) => o.category === "model"); - const canRefreshModels = task.status !== "archived" && !!model && !!provider?.installed && project?.trusted !== false; - const candidateModels = canRefreshModels - ? (catalog?.config ?? provider?.config)?.find((o) => o.category === "model")?.values - : undefined; + const catalogModel = (catalog?.config ?? provider?.config)?.find((o) => o.category === "model"); + const canRefreshModels = + task.status !== "archived" && + (!!model || !!task.model || !!catalogModel) && + !!provider?.installed && + project?.trusted !== false; const pickerConfig = useMemo(() => { - if (!model || !candidateModels?.length) return task.config; + if (!canRefreshModels) return task.config; + if (!model) { + const recovered: AgentConfigOption = + catalogModel === undefined + ? { + id: "model", + name: "Model", + description: null, + category: "model", + current: task.model, + values: [], + via: "option", + } + : { ...catalogModel, current: task.model ?? catalogModel.current }; + return [...task.config, recovered]; + } + const candidateModels = catalogModel?.values; + if (!candidateModels?.length) return task.config; const sessionModels = new Set(model.values.map((v) => v.value)); const extra = candidateModels.filter((v) => !sessionModels.has(v.value)); if (!extra.length) return task.config; const pickerModel = { ...model, values: [...model.values, ...extra] }; return task.config.map((o) => (o === model ? pickerModel : o)); - }, [task.config, model, candidateModels]); + }, [task.config, task.model, model, catalogModel, canRefreshModels]); const [sending, setSending] = useState(false); const configChange = useRef<{ loadingModel: boolean } | null>(null); const [configuring, setConfiguring] = useState<typeof configChange.current>(null); diff --git a/src/features/agents/store.ts b/src/features/agents/store.ts index 457a11d98..b1504b6be 100644 --- a/src/features/agents/store.ts +++ b/src/features/agents/store.ts @@ -421,7 +421,7 @@ export async function refreshModels( export async function refreshTaskModels(id: string, force = true): Promise<void> { const { tasks, providers } = useAgents.getState(); const task = tasks.get(id); - if (!task || task.status === "archived" || !task.config.some((o) => o.category === "model")) return; + if (!task || task.status === "archived" || (!task.model && !task.config.some((o) => o.category === "model"))) return; const provider = providers.find((p) => p.id === task.provider); if (!provider?.installed || useProject.getState().project?.trusted === false) return; await refreshProviderModels(provider, force, null, null); From b0d0ea868b2393c6f840a3025fadbb9e8460c875 Mon Sep 17 00:00:00 2001 From: Deng Liu <deng@sesame.com> Date: Thu, 19 Nov 2026 19:11:05 -0800 Subject: [PATCH 6/6] feat(agents): configure GitHub Copilot authentication account (#4663) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Copilot launched with whichever GitHub CLI account was active outside the IDE. GitHub Copilot's settings get a GitHub account field: at launch the IDE asks gh for that account's token and passes it as COPILOT_GITHUB_TOKEN, without storing it; the account (not a credential) is kept with the agent's settings and scopes the catalog cache. Also adds the field's text to the en/zh catalog. Verified with cargo test -p ide-agent, clippy, agents and locale vitest, typecheck, and the field in Settings › Agents › Coding Agents. Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com> --- crates/ide-agent/src/acp/discover.rs | 2 +- crates/ide-agent/src/lib.rs | 11 +- crates/ide-agent/src/native/copilot/mod.rs | 3 +- crates/ide-agent/src/provider.rs | 131 ++++++++++++++++++++- crates/ide-agent/src/registry.rs | 8 ++ src/features/agents/AgentList.tsx | 42 ++++++- src/features/agents/agentRegistry.test.tsx | 36 +++++- src/platform/locales/text/en.json | 5 +- src/platform/locales/text/zh.json | 5 +- 9 files changed, 230 insertions(+), 13 deletions(-) diff --git a/crates/ide-agent/src/acp/discover.rs b/crates/ide-agent/src/acp/discover.rs index 7335b8679..0926e31c0 100644 --- a/crates/ide-agent/src/acp/discover.rs +++ b/crates/ide-agent/src/acp/discover.rs @@ -51,7 +51,7 @@ async fn run_once( move || launch.resolve_for_launch_with_copilot_env(&root, strip_ambient) }) .await - .map_err(|e| e.to_string())?; + .map_err(|e| e.to_string())??; let cwd = dunce::canonicalize(&root).unwrap_or(root); let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() }); let client = Dialect::wrap(updates.clone()); diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 1ce2b170b..79d081f69 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -132,6 +132,7 @@ pub type McpExecutableFn = dyn Fn() -> Option<PathBuf> + Send + Sync; #[derive(Clone, Debug, PartialEq, Eq, Hash)] struct CopilotBinaryKey { command: String, + github_account: Option<String>, modified: Option<std::time::SystemTime>, len: Option<u64>, } @@ -193,6 +194,7 @@ impl Shared { let metadata = std::fs::metadata(&executable).ok(); CopilotBinaryKey { command: executable.to_string_lossy().into_owned(), + github_account: provider::copilot_github_account(&spec.env), modified: metadata.as_ref().and_then(|m| m.modified().ok()), len: metadata.as_ref().map(std::fs::Metadata::len), } @@ -2811,9 +2813,12 @@ impl Task { pending_model: Option<&PendingModel>, ) -> Result<Live, SessionOpenError> { let launch_cwd = cwd.to_path_buf(); - let mut spec = tokio::task::spawn_blocking(move || spec.resolve_for_launch(&launch_cwd)) - .await - .map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?; + let mut spec = tokio::task::spawn_blocking(move || { + spec.resolve_for_launch_with_copilot_env(&launch_cwd, provider::prefer_stored_copilot_auth()) + }) + .await + .map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })? + .map_err(|e| SessionOpenError { message: e, allow_acp_fallback: false })?; if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(provider_id) { let mcp_overrides = self.state.lock().task.mcp_overrides.clone(); for name in self.shared.mcp_servers_off_for_session(provider_id, &mcp_overrides) { diff --git a/crates/ide-agent/src/native/copilot/mod.rs b/crates/ide-agent/src/native/copilot/mod.rs index 1421972b3..bdea39d8d 100644 --- a/crates/ide-agent/src/native/copilot/mod.rs +++ b/crates/ide-agent/src/native/copilot/mod.rs @@ -144,7 +144,8 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) -> move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient) }) .await - .map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })?; + .map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })? + .map_err(|e| DiscoverError { message: e, allow_acp_fallback: false })?; let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd); let args = headless_args(&launch.args); let peer = Peer::spawn_framed( diff --git a/crates/ide-agent/src/provider.rs b/crates/ide-agent/src/provider.rs index 8db709499..a8f4370d4 100644 --- a/crates/ide-agent/src/provider.rs +++ b/crates/ide-agent/src/provider.rs @@ -9,6 +9,8 @@ use serde_json::Value; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; +pub(crate) const COPILOT_GITHUB_ACCOUNT_ENV: &str = "OPENIDEA_COPILOT_GITHUB_ACCOUNT"; + /// The protocol an agent speaks. Native ones run behind an in-process ACP endpoint /// (`native`), so tasks see every agent as ACP and read features from its capabilities. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -138,15 +140,31 @@ impl ProviderSpec { /// Resolve once before connecting, so authentication guidance names that same install. pub(crate) fn resolve_for_launch(self, cwd: &Path) -> Self { let strip = prefer_stored_copilot_auth(); - self.resolve_for_launch_with_copilot_env(cwd, strip) + self.resolve_for_launch_base(cwd, strip) } - pub(crate) fn resolve_for_launch_with_copilot_env(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self { + pub(crate) fn resolve_for_launch_with_copilot_env( + self, + cwd: &Path, + strip_ambient_tokens: bool, + ) -> Result<Self, String> { + let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten(); + let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some()); + if let Some(account) = account { + let token = github_token_for_account(&account)?; + resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str())); + resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token)); + } + Ok(resolved) + } + + fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self { if self.driver != Driver::Acp { self.command = crate::native::newest_install(&self.command); } if is_copilot_provider(&self.id) { self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens); + self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV); } let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env); self.command = @@ -164,6 +182,50 @@ pub(crate) fn is_copilot_provider(id: &str) -> bool { id == "copilot" || id.starts_with("copilot-") } +pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String> { + env.iter() + .rev() + .find(|(name, _)| name == COPILOT_GITHUB_ACCOUNT_ENV) + .map(|(_, value)| value.trim()) + .filter(|value| !value.is_empty()) + .map(str::to_owned) +} + +fn github_token_for_account(account: &str) -> Result<String, String> { + let path = ide_core::process::shell_env() + .find(|(name, _)| name == "PATH") + .map(|(_, value)| value) + .or_else(|| ide_core::process::host_var_os("PATH")); + let program = path + .as_deref() + .and_then(|path| ide_core::process::find_executable("gh", path)) + .ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?; + let mut command = std::process::Command::new(program); + command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env()); + for name in AMBIENT_COPILOT_AUTH_VARS { + command.env_remove(name); + } + let output = command + .output() + .map_err(|error| format!("Couldn't read GitHub authentication for account {account}: {error}"))?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let detail = stderr.trim(); + return Err(if detail.is_empty() { + format!("GitHub CLI has no authenticated account named {account}") + } else { + format!("Couldn't use GitHub account {account}: {detail}") + }); + } + let token = String::from_utf8(output.stdout) + .map_err(|_| format!("GitHub CLI returned a non-text token for account {account}"))?; + let token = token.trim(); + if token.is_empty() { + return Err(format!("GitHub CLI returned no token for account {account}")); + } + Ok(token.to_owned()) +} + pub(crate) fn prefer_stored_copilot_auth() -> bool { PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire) } @@ -339,6 +401,31 @@ pub(crate) fn set_builtin_env( id: &str, env: BTreeMap<String, String>, ) -> IdeResult<()> { + if id == "copilot" { + let file = custom_dir.join("copilot.toml"); + if file.try_exists()? + && let mut agent = CustomAgent::read_with(&file, id, secrets).map_err(IdeError::invalid)? + && agent.registry.is_some() + { + let existing = agent.env.clone(); + let mut existing_launch_env = existing.clone(); + let mut next_launch_env = env.clone(); + existing_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV); + next_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV); + if existing_launch_env != next_launch_env { + return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry"))); + } + match env.get(COPILOT_GITHUB_ACCOUNT_ENV).filter(|value| !value.trim().is_empty()) { + Some(account) => { + agent.env.insert(COPILOT_GITHUB_ACCOUNT_ENV.into(), account.trim().into()); + } + None => { + agent.env.remove(COPILOT_GITHUB_ACCOUNT_ENV); + } + } + return agent.write(&file).map_err(Into::into); + } + } update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env) } @@ -955,6 +1042,46 @@ mod tests { set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err(); } + #[test] + fn registry_copilot_allows_only_the_github_account_override() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("copilot.toml"); + CustomAgent { + name: Some("GitHub Copilot".into()), + driver: Driver::Acp, + command: "/tools/copilot".into(), + args: vec!["--acp".into()], + env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]), + registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }), + } + .write(&file) + .unwrap(); + + set_builtin_env( + dir.path(), + None, + "copilot", + BTreeMap::from([ + ("REGISTRY_SETTING".into(), "kept".into()), + (COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()), + ]), + ) + .unwrap(); + let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap(); + assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft")); + + set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())])) + .unwrap_err(); + } + + #[test] + fn launch_metadata_never_passes_the_github_account_control_to_copilot() { + let mut spec = builtin_spec("copilot").unwrap(); + spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into())); + let resolved = spec.resolve_for_launch(Path::new(".")); + assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV)); + } + #[test] fn acp_adapters_of_native_agents_are_unlisted_until_customized() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-agent/src/registry.rs b/crates/ide-agent/src/registry.rs index ed8148851..212ebc8fc 100644 --- a/crates/ide-agent/src/registry.rs +++ b/crates/ide-agent/src/registry.rs @@ -537,6 +537,14 @@ fn install_entry_with( return Err(e); } }; + let github_account = (entry.id == "copilot") + .then(|| CustomAgent::read(&file).ok()) + .flatten() + .and_then(|agent| agent.env.get(provider::COPILOT_GITHUB_ACCOUNT_ENV).cloned()); + let mut env = env; + if let Some(account) = github_account { + env.insert(provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account); + } let agent = CustomAgent { name: Some(entry.name.clone()), driver: Driver::Acp, diff --git a/src/features/agents/AgentList.tsx b/src/features/agents/AgentList.tsx index 965342d37..b0a083155 100644 --- a/src/features/agents/AgentList.tsx +++ b/src/features/agents/AgentList.tsx @@ -35,6 +35,10 @@ import { import styles from "./AgentList.module.css"; const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e)); +const COPILOT_GITHUB_ACCOUNT_ENV = "OPENIDEA_COPILOT_GITHUB_ACCOUNT"; + +const launchEnv = (env: Record<string, string>) => + Object.fromEntries(Object.entries(env).filter(([name]) => name !== COPILOT_GITHUB_ACCOUNT_ENV)); /** How often the page checks on installs it did not start. */ const BACKGROUND_POLL_MS = 1500; @@ -819,13 +823,26 @@ function ProviderSettings({ onChanged?.(); return command === agent.defaultProgram ? "" : (command ?? ""); }); - const envBase = formatEnv(agent.env); + const accountBase = agent.env[COPILOT_GITHUB_ACCOUNT_ENV] ?? ""; + const account = form.useExternal(`agents.${agent.id}.githubAccount`, accountBase, async (draft) => { + const next = { ...agent.env }; + const value = draft.trim(); + if (value) next[COPILOT_GITHUB_ACCOUNT_ENV] = value; + else delete next[COPILOT_GITHUB_ACCOUNT_ENV]; + await backend.setEnv(agent.id, next); + await refresh(); + onChanged?.(); + return value; + }); + const envBase = formatEnv(launchEnv(agent.env)); const env = form.useExternal(`agents.${agent.id}.env`, envBase, async (draft) => { const parsed = parseEnv(draft); + const account = agent.env[COPILOT_GITHUB_ACCOUNT_ENV]; + if (account) parsed[COPILOT_GITHUB_ACCOUNT_ENV] = account; await backend.setEnv(agent.id, parsed); await refresh(); onChanged?.(); - return formatEnv(parsed); + return formatEnv(launchEnv(parsed)); }); const [error, setError] = useState<string | null>(null); // An edit can have been staged by a previous page instance. Its Apply callback @@ -849,6 +866,27 @@ function ProviderSettings({ </Section> <Section title="Launch"> <div className={styles.form}> + {agent.id === "copilot" && ( + <Row + label={<T>GitHub account</T>} + htmlFor={`agent-github-account-${agent.id}`} + hint={ + <T> + Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never + stores it. + </T> + } + > + <Input + id={`agent-github-account-${agent.id}`} + mono + value={account.value} + disabled={account.saving} + placeholder="github-username" + onChange={(e) => account.set(e.target.value)} + /> + </Row> + )} <Row label={<T>Command</T>}> <code className={styles.launch} title={launch}> {launch} diff --git a/src/features/agents/agentRegistry.test.tsx b/src/features/agents/agentRegistry.test.tsx index 975782be4..6f09154f7 100644 --- a/src/features/agents/agentRegistry.test.tsx +++ b/src/features/agents/agentRegistry.test.tsx @@ -469,7 +469,7 @@ describe("Built-in executable overrides", () => { dispose(); }); - const openCommands = async (commands: FakeCommands, onChanged = vi.fn()) => { + const openCommands = async (commands: FakeCommands, onChanged = vi.fn(), name = "Claude Code") => { const backend = new FakeBackend(); dispose = registerSettingsPage({ id: REGISTRY_PAGE, @@ -478,7 +478,7 @@ describe("Built-in executable overrides", () => { component: () => <RegistryPage backend={backend} commandBackend={commands} onChanged={onChanged} />, }); render(<SettingsDialog />); - return screen.findByRole("region", { name: "Claude Code" }); + return screen.findByRole("region", { name }); }; const apply = () => screen.getByRole("button", { name: "Apply" }); const field = () => screen.getByRole("textbox", { name: "Executable" }); @@ -564,6 +564,38 @@ describe("Built-in executable overrides", () => { expect(commands.savedEnv.at(-1)).toEqual(["claude", {}]); }); + it("writes a Copilot GitHub account without storing a token or exposing the control variable", async () => { + const commands = new FakeCommands(); + commands.list = [ + { + ...claudeProvider("copilot"), + id: "copilot", + name: "GitHub Copilot", + command: "copilot --acp", + defaultProgram: "copilot", + commandReadOnlyReason: "registry", + env: { COPILOT_TELEMETRY_OPTOUT: "1" }, + }, + ]; + await openCommands(commands, vi.fn(), "GitHub Copilot"); + const account = screen.getByRole("textbox", { name: "GitHub account" }); + expect(screen.queryByRole("textbox", { name: "Environment variables" })).toBeNull(); + fireEvent.change(account, { target: { value: "dengliu_microsoft" } }); + + await act(async () => fireEvent.click(apply())); + + expect(commands.savedEnv).toEqual([ + [ + "copilot", + { + COPILOT_TELEMETRY_OPTOUT: "1", + OPENIDEA_COPILOT_GITHUB_ACCOUNT: "dengliu_microsoft", + }, + ], + ]); + expect(JSON.stringify(commands.savedEnv)).not.toMatch(/gho_|ghp_|token/i); + }); + it("Cancel discards command edits without writing", async () => { const commands = new FakeCommands(); commands.list = [ diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index b011d5e9e..b22fbdf44 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2712,5 +2712,8 @@ "Shelve Silently": "Shelve Silently", "Unshelve Silently": "Unshelve Silently", "Fold Lines Like This": "Fold Lines Like This", - "Remove All Watches": "Remove All Watches" + "Remove All Watches": "Remove All Watches", + "GitHub account": "GitHub account", + "Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.", + "github-username": "github-username" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index e3564a00b..2d271a7ea 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -9078,5 +9078,8 @@ "Database and schema": "数据库和 schema", "Shelve Silently": "静默搁置", "Unshelve Silently": "静默取消搁置", - "Remove All Watches": "移除所有监视" + "Remove All Watches": "移除所有监视", + "GitHub account": "GitHub 账号", + "Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "留空则使用 GitHub CLI 当前登录的账号。OpenIDEA 在启动时获取令牌,不会保存它。", + "github-username": "GitHub 用户名" }