Compare commits

..
Author SHA1 Message Date
l0ng-ai 481a92d315 fix(database): connect without TLS when a Prefer handshake fails
With SSL mode Prefer, a MySQL or PostgreSQL server whose TLS handshake fails
(e.g. one limited to TLS 1.0/1.1) failed with "received fatal alert:
HandshakeFailure": sqlx only skips TLS when the server doesn't offer it.
Prefer now retries once without TLS after a failed handshake, as libpq's
sslmode=prefer does; the pool keeps the plain options.
2026-11-19 17:30:39 +08:00
58 changed files with 167 additions and 1826 deletions

No files matched your search

-3
View File
@@ -1535,9 +1535,6 @@ pub struct MavenSettings {
/// project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand
/// from a library class's Download Sources banner.
pub download_sources: bool,
/// Always update snapshots (`-U`): Maven checks remote repositories for newer SNAPSHOT
/// dependencies on every sync, build and run, and jdtls on import (`java.maven.updateSnapshots`).
pub update_snapshots: bool,
}
impl MavenSettings {
-13
View File
@@ -170,12 +170,6 @@ pub struct CommitSettings {
pub double_click_opens_diff: Option<bool>,
/// Team conventions for Generate Commit Message with Agent, added to its prompt.
pub agent_instructions: String,
/// The coding agent Generate Commit Message with Agent uses; empty follows the latest task's agent.
pub agent: String,
/// That agent's model for commit messages; empty keeps the model the agent would use.
pub agent_model: String,
/// That model's thinking level for commit messages; empty keeps the agent's.
pub agent_effort: String,
}
impl Default for CommitSettings {
@@ -198,9 +192,6 @@ impl Default for CommitSettings {
disabled_plugin_checks: Vec::new(),
double_click_opens_diff: None,
agent_instructions: String::new(),
agent: String::new(),
agent_model: String::new(),
agent_effort: String::new(),
}
}
}
@@ -457,9 +448,6 @@ pub struct TerminalSettings {
/// Shell command line; empty = the login shell.
pub shell_path: String,
pub tab_name: String,
/// Title a program sets (OSC 0/2) as the tab's name: `running` (while a command runs),
/// `always`, or `off`.
pub app_title_as_tab_name: String,
pub audible_bell: bool,
pub close_on_exit: bool,
pub mouse_reporting: bool,
@@ -495,7 +483,6 @@ impl Default for TerminalSettings {
env: BTreeMap::new(),
shell_path: String::new(),
tab_name: "Local".into(),
app_title_as_tab_name: "running".into(),
audible_bell: true,
close_on_exit: true,
mouse_reporting: true,
+1 -47
View File
@@ -119,29 +119,6 @@ fn php_cs_fixer_edits(
.collect())
}
/// Some language servers (Vue's, for one) answer Reformat Code with one edit replacing the
/// whole file; applied as is, it moves the caret and the view to the top of the file. The same
/// result as one edit per changed region keeps them where they were.
fn minimal_edits(text: &str, edits: Vec<TextEdit>) -> Vec<TextEdit> {
if !edits.iter().any(|e| e.range.end.line > e.range.start.line) {
return edits;
}
let original = ide_text::Document::new(text);
let mut formatted = original.clone();
if formatted.apply_edits(&edits).is_err() {
return edits;
}
original
.diff(&formatted.text())
.changes
.into_iter()
.map(|c| TextEdit {
range: Range::new(original.offset_to_pos(c.from), original.offset_to_pos(c.to)),
new_text: c.insert,
})
.collect()
}
pub async fn format(
host: &Host,
window: &str,
@@ -315,11 +292,7 @@ async fn provider_edits(
if options.on_save && !settings.editor.format_on_save {
return Ok(None);
}
let edits = project.lsp.format(doc, range, options).await?;
let text = snap.text;
return tokio::task::spawn_blocking(move || Some(minimal_edits(&text, edits)))
.await
.map_err(|e| IdeError::internal(e.to_string()));
return project.lsp.format(doc, range, options).await.map(Some);
};
let tool_settings = settings.languages.formatter(selected);
if options.on_save && !tool_settings.run_on_save {
@@ -550,25 +523,6 @@ mod tests {
const ALIGN: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true };
#[test]
fn a_whole_file_edit_becomes_one_edit_per_changed_region() {
let text = "a\n b\nc\nd\n e\n";
let formatted = "a\nb\nc\nd\ne\n";
let whole = vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(5, 0)), new_text: formatted.into() }];
let edits = minimal_edits(text, whole);
assert_eq!(
edits,
[
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() },
TextEdit { range: Range::new(Pos::new(4, 0), Pos::new(4, 2)), new_text: String::new() },
]
);
assert_eq!(after(text, &edits), formatted);
// Single-line edits are already minimal and pass through.
let small = vec![TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() }];
assert_eq!(minimal_edits(text, small.clone()), small);
}
#[test]
fn php_alignment_is_off_unless_the_php_code_style_turns_it_on() {
let php = LanguageId::new("php");
+6 -29
View File
@@ -537,21 +537,18 @@ pub fn configure_gradle_runtime(cfg: &mut LanguageServerConfig, root: &Path, bui
merge(cfg.settings.get_or_insert_with(|| json!({})), json!({"java": {"import": {"gradle": gradle}}}));
}
/// Settings › Build Tools › Maven › Automatically download sources and Always update
/// snapshots → jdtls `java.maven.downloadSources` / `java.maven.updateSnapshots`.
/// Settings › Build Tools › Maven › Automatically download sources → jdtls
/// `java.maven.downloadSources`.
pub fn configure_maven_sources(cfg: &mut LanguageServerConfig, s: &Settings) {
if cfg.name != "jdtls" {
return;
}
let m = &s.languages.java.maven;
merge(
cfg.settings.get_or_insert_with(|| json!({})),
json!({"java": {"maven": {"downloadSources": m.download_sources, "updateSnapshots": m.update_snapshots}}}),
);
let download = s.languages.java.maven.download_sources;
merge(cfg.settings.get_or_insert_with(|| json!({})), json!({"java": {"maven": {"downloadSources": download}}}));
}
/// Maven options from settings, placed before the goals: `-s <settings.xml>`,
/// `-t <toolchains.xml>`, `-Dmaven.repo.local=<dir>`, `-T <count>`, `-P <profiles>` and `-U`.
/// `-t <toolchains.xml>`, `-Dmaven.repo.local=<dir>`, `-T <count>` and `-P <profiles>`.
pub fn maven_options(root: &Path, s: &Settings) -> Vec<String> {
let m = &s.languages.java.maven;
let mut out = Vec::new();
@@ -570,9 +567,6 @@ pub fn maven_options(root: &Path, s: &Settings) -> Vec<String> {
if let Some(profiles) = non_empty(&m.active_profiles) {
out.extend(["-P".to_owned(), profiles.to_owned()]);
}
if m.update_snapshots {
out.push("-U".to_owned());
}
out
}
@@ -1113,13 +1107,6 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
}
cfg.command = custom.to_string_lossy().into_owned();
}
// `java -jar` servers run on the project JDK when there is one, like JAR Application runs.
if cfg.command == "java"
&& let Some(java) =
project_jdk(root, s).map(|jdk| crate::java::java_executable(&jdk.home)).filter(|j| j.is_file())
{
cfg.command = java.to_string_lossy().into_owned();
}
let name = cfg.name.clone();
let name = name.as_str();
@@ -1548,12 +1535,6 @@ pub fn server_launch_overrides(cfg: &mut LanguageServerConfig, s: &Settings) {
if let Some(args) = &ls.args {
cfg.args = args.clone();
}
// A server shipped as a runnable jar (groovy-language-server-all.jar) runs on `java -jar`;
// `configure_server` then picks the project JDK's `java`.
if Path::new(&cfg.command).extension().is_some_and(|e| e.eq_ignore_ascii_case("jar")) {
let jar = std::mem::replace(&mut cfg.command, "java".to_owned());
cfg.args.splice(0..0, ["-jar".to_owned(), jar]);
}
}
/// Environment, features, `initializationOptions` and `workspace/configuration`
@@ -1653,9 +1634,6 @@ fn maven_option_flag(arg: &str) -> Option<&'static str> {
return Some(short);
}
}
if arg == "-U" || arg == "--update-snapshots" {
return Some("-U");
}
arg.starts_with("-Dmaven.repo.local=").then_some("-Dmaven.repo.local")
}
@@ -2475,9 +2453,8 @@ mod maven_linkage_tests {
Some(json!({"java": {"maven": {"downloadSources": false, "updateSnapshots": false}}}))
);
settings.languages.java.maven.download_sources = true;
settings.languages.java.maven.update_snapshots = true;
configure_maven_sources(&mut cfg, &settings);
assert_eq!(cfg.settings.unwrap()["java"]["maven"], json!({"downloadSources": true, "updateSnapshots": true}));
assert_eq!(cfg.settings.unwrap()["java"]["maven"]["downloadSources"], json!(true));
let mut other = custom_server("kotlin", &LanguageServerSettings::default());
configure_maven_sources(&mut other, &settings);
-48
View File
@@ -887,26 +887,6 @@ fn maven_options_carry_active_profiles_into_the_command_line() {
assert_eq!(configured[0].args, ["-P", "prod", "package"]);
}
#[test]
fn always_update_snapshots_adds_dash_u_once() {
let tmp = tempfile::tempdir().unwrap();
let mut s = Settings::default();
s.languages.java.maven.update_snapshots = true;
assert_eq!(maven_options(tmp.path(), &s), ["-U"]);
let mut configs = vec![run("maven", "./mvnw", &["package"])];
for _ in 0..2 {
apply_to_run_configs(&mut configs, tmp.path(), &s);
assert_eq!(configs[0].args, ["-U", "package"]);
}
let mut own = vec![run("maven", "./mvnw", &["--update-snapshots", "package"])];
apply_to_run_configs(&mut own, tmp.path(), &s);
assert_eq!(own[0].args, ["--update-snapshots", "package"]);
s.languages.java.maven.update_snapshots = false;
apply_to_run_configs(&mut configs, tmp.path(), &s);
assert_eq!(configs[0].args, ["package"]);
}
#[test]
fn maven_profile_and_toolchain_overrides_accept_every_option_form() {
let tmp = tempfile::tempdir().unwrap();
@@ -1292,34 +1272,6 @@ fn language_server_settings_disable_add_and_override() {
assert_eq!(parsed.code_action_kinds, Some(vec!["refactor".to_string()]));
}
#[test]
fn a_server_path_to_a_jar_runs_with_java_jar() {
use crate::apply::server_launch_overrides;
use ide_core::settings::LanguageServerSettings;
let mut s = Settings::default();
let jar = "/opt/groovy/build/libs/groovy-language-server-all.JAR";
s.language_servers.insert(
"groovy-language-server".into(),
LanguageServerSettings { command: jar.into(), args: Some(vec!["--verbose".into()]), ..Default::default() },
);
let mut groovy = server("groovy-language-server");
server_launch_overrides(&mut groovy, &s);
assert_eq!(groovy.command, "java");
assert_eq!(groovy.args, ["-jar", jar, "--verbose"]);
// A project JDK is the one that runs it.
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("jdk");
let java = crate::java::java_executable(&home);
std::fs::create_dir_all(java.parent().unwrap()).unwrap();
std::fs::write(&java, "").unwrap();
std::fs::write(home.join("release"), "JAVA_VERSION=\"21.0.2\"\n").unwrap();
s.languages.java.jdk = home.to_string_lossy().into_owned();
configure_server(&mut groovy, tmp.path(), tmp.path(), &s);
assert!(groovy.command.ends_with(&*Path::new("jdk").join(java.strip_prefix(&home).unwrap()).to_string_lossy()));
assert!(Path::new(&groovy.command).is_file(), "{}", groovy.command);
}
#[test]
fn ruff_configuration_directory_resolves_files_and_validates_pyproject() {
let tmp = tempfile::tempdir().unwrap();
-3
View File
@@ -847,9 +847,6 @@ mod tests {
"disabledPluginChecks": [],
"doubleClickOpensDiff": null,
"agentInstructions": "",
"agent": "",
"agentModel": "",
"agentEffort": "",
})
);
}
+7 -9
View File
@@ -37,15 +37,13 @@ After editing the file, run **Reload .ideavimrc** (from the status bar widget or
Supported lines:
| Line | Notes |
| --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `map`, `noremap` and their `n`, `v`, `x`, `i`, `o` variants (`nnoremap`, `vmap`…) | `<silent>`, `<unique>`, `<nowait>`, `<buffer>`, `<expr>` and `<script>` flags are accepted and ignored. Key names such as `<esc>` and `<CR>` are case-insensitive. |
| `let mapleader = "…"` | Also `g:mapleader`. `"\<Space>"` and `" "` both mean Space. The default leader is `\`. |
| `set …` | `textwidth` (`tw`), `pcre`, `insertModeEscKeysTimeout`, `langmap` (`lmap`) and `clipboard` (`cb`). `+=`, `-=` and `^=` work as in Vim. Other options are reported as ignored. |
| `source <file>` | Reads another file by the same rules. `~` is your home directory. |
| `" comment` | Ignored. |
`set clipboard+=unnamedplus` (or `unnamed`) also copies yanks, deletes and changes without a register to the system clipboard. The `"+` register always reads and writes the system clipboard.
| Line | Notes |
| --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `map`, `noremap` and their `n`, `v`, `x`, `i`, `o` variants (`nnoremap`, `vmap`…) | `<silent>`, `<unique>`, `<nowait>`, `<buffer>`, `<expr>` and `<script>` flags are accepted and ignored. Key names such as `<esc>` and `<CR>` are case-insensitive. |
| `let mapleader = "…"` | Also `g:mapleader`. `"\<Space>"` and `" "` both mean Space. The default leader is `\`. |
| `set …` | Only the options codemirror-vim implements: `textwidth` (`tw`), `pcre`, `insertModeEscKeysTimeout` and `langmap` (`lmap`). Other options are reported as ignored. |
| `source <file>` | Reads another file by the same rules. `~` is your home directory. |
| `" comment` | Ignored. |
Anything else (functions, `if`, `autocmd`, plugin commands) is reported as ignored and never executed.
+7 -9
View File
@@ -37,15 +37,13 @@ Vim 模式开启时(如果上次是开启状态,启动时也会),OpenIDE
支持的写法:
| 写法 | 说明 |
| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `map`、`noremap` 以及它们的 `n`、`v`、`x`、`i`、`o` 变体(`nnoremap`、`vmap`…) | `<silent>`、`<unique>`、`<nowait>`、`<buffer>`、`<expr>`、`<script>` 标志可以写,但会被忽略。`<esc>`、`<CR>` 等键名不区分大小写。 |
| `let mapleader = "…"` | 也可以写 `g:mapleader`。`"\<Space>"` 和 `" "` 都表示空格。默认 leader 是 `\`。 |
| `set …` | `textwidth`(`tw`)、`pcre`、`insertModeEscKeysTimeout`、`langmap`(`lmap`)和 `clipboard`(`cb`)。`+=`、`-=`、`^=` 与 Vim 相同。其他选项会被标记为已忽略。 |
| `source <file>` | 按同样的规则读取另一个文件,`~` 表示主目录。 |
| `" 注释` | 忽略。 |
`set clipboard+=unnamedplus`(或 `unnamed`)让不指定寄存器的复制、删除和修改也写入系统剪贴板。`"+` 寄存器始终读写系统剪贴板。
| 写法 | 说明 |
| ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `map`、`noremap` 以及它们的 `n`、`v`、`x`、`i`、`o` 变体(`nnoremap`、`vmap`…) | `<silent>`、`<unique>`、`<nowait>`、`<buffer>`、`<expr>`、`<script>` 标志可以写,但会被忽略。`<esc>`、`<CR>` 等键名不区分大小写。 |
| `let mapleader = "…"` | 也可以写 `g:mapleader`。`"\<Space>"` 和 `" "` 都表示空格。默认 leader 是 `\`。 |
| `set …` | 只支持 codemirror-vim 实现的选项:`textwidth`(`tw`)、`pcre`、`insertModeEscKeysTimeout` 和 `langmap`(`lmap`)。其他选项会被标记为已忽略。 |
| `source <file>` | 按同样的规则读取另一个文件,`~` 表示主目录。 |
| `" 注释` | 忽略。 |
其他内容(函数、`if`、`autocmd`、插件命令等)都会被标记为已忽略,不会执行。
+10 -13
View File
@@ -219,12 +219,11 @@ function history(page: Page) {
function modelButton(page: Page) {
return page.getByRole("button", { name: "Model", exact: true }).filter({ visible: true });
}
/** The effort is shown on the model button, after the model's name. */
function effortLabel(page: Page) {
return modelButton(page).locator("[class*='modelDetail']");
function effortButton(page: Page) {
return page.getByRole("button", { name: "Reasoning", exact: true }).filter({ visible: true });
}
async function expectEffort(page: Page, name: string) {
await expect(effortLabel(page)).toHaveText(name);
await expect(effortButton(page)).toHaveText(name);
}
async function selected(box: Locator) {
return box.evaluate((element) => {
@@ -365,8 +364,8 @@ test("Settings and effort popup exclude the agent shortcut", async ({ workbench:
await expect(search).toBeFocused();
await expect(search).toHaveValue("keymap");
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await modelButton(page).click();
const popup = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await effortButton(page).click();
const popup = page.getByRole("listbox", { name: "Reasoning", exact: true });
await expect(popup).toBeVisible();
await page.keyboard.press("Alt+t");
expect(await ipcCalls(page, "agent_set_config")).toEqual([]);
@@ -585,16 +584,14 @@ test("New Task discovers uncached model effort before the first prompt", async (
.poll(async () => (await ipcCalls(page, "agent_refresh_models")).filter((call) => call.model === "swift"))
.toEqual([{ provider: provider.id, force: false, model: "swift" }]);
await expect(page.getByRole("status").filter({ hasText: "Loading model settings…" })).toBeVisible();
await expect(effortLabel(page)).toHaveCount(0);
await expect(effortButton(page)).toHaveCount(0);
await page.screenshot({ path: testInfo.outputPath("model-settings-loading.png") });
await page.evaluate(() => document.dispatchEvent(new Event("test:model-settings-ready")));
await expectEffort(page, "Quick");
await modelButton(page).click();
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("radio", { name: "Quick", exact: true })).toBeVisible();
await expect(efforts.getByRole("radio", { name: "Thorough", exact: true })).toBeVisible();
await expect(efforts.getByRole("radio", { name: "Gentle", exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
await effortButton(page).click();
await expect(page.getByRole("option", { name: "Quick", exact: true })).toBeVisible();
await expect(page.getByRole("option", { name: "Thorough", exact: true })).toBeVisible();
await expect(page.getByRole("option", { name: "Gentle", exact: true })).toHaveCount(0);
await expect(box(page)).toHaveText("Keep this first task unsent");
await expectNoSubmission(page);
expect(await ipcCalls(page, "agent_set_config")).toEqual([]);
-16
View File
@@ -3745,12 +3745,6 @@ export type CommitSettings = {
doubleClickOpensDiff?: boolean | null,
/** Team conventions for Generate Commit Message with Agent, added to its prompt. */
agentInstructions?: string,
/** The coding agent Generate Commit Message with Agent uses; empty follows the latest task's agent. */
agent?: string,
/** That agent's model for commit messages; empty keeps the model the agent would use. */
agentModel?: string,
/** That model's thinking level for commit messages; empty keeps the agent's. */
agentEffort?: string,
};
export type Commit_Deserialize = {
@@ -8384,11 +8378,6 @@ export type MavenSettings = {
* from a library class's Download Sources banner.
*/
downloadSources?: boolean,
/**
* Always update snapshots (`-U`): Maven checks remote repositories for newer SNAPSHOT
* dependencies on every sync, build and run, and jdtls on import (`java.maven.updateSnapshots`).
*/
updateSnapshots?: boolean,
};
/** Summary of one server discovered inside an external MCP configuration file. */
@@ -11624,11 +11613,6 @@ export type TerminalSettings = {
/** Shell command line; empty = the login shell. */
shellPath?: string,
tabName?: string,
/**
* Title a program sets (OSC 0/2) as the tab's name: `running` (while a command runs),
* `always`, or `off`.
*/
appTitleAsTabName?: string,
audibleBell?: boolean,
closeOnExit?: boolean,
mouseReporting?: boolean,
+3 -7
View File
@@ -239,7 +239,7 @@
}
.quickLabel {
flex: none;
width: 72px;
width: 52px;
color: var(--fg-muted);
font-size: var(--fs-small);
}
@@ -401,14 +401,10 @@
text-overflow: ellipsis;
white-space: nowrap;
}
/* Details give way to the names, except the model's effort and context: the model's
name truncates first, since they are only shown here. */
.chipDetail:not(.modelDetail) {
/* The effort is in the model popup: the button keeps the model's name readable. */
.chipDetail {
display: none;
}
.modelDetail {
flex: none;
}
.inlineSetting {
display: none;
}
+9 -63
View File
@@ -267,7 +267,7 @@ it("edits secondary settings from the compact popup and restores focus when dism
expect(trigger).toHaveFocus();
});
describe("model settings", () => {
describe("model and effort button", () => {
const copilotConfig = (effortLevels: string[] | null = ["low", "medium", "high", "xhigh"]): AgentConfigOption[] => [
{
id: "model",
@@ -314,66 +314,18 @@ describe("model settings", () => {
},
];
it("keeps effort as a standalone setting when no model is available", () => {
render(
<ConfigPickers
config={[
{
id: "reasoning_effort",
name: "Reasoning Effort",
category: "thought_level",
description: null,
current: "medium",
via: "option",
values: [value("low"), value("medium")],
},
]}
onChange={vi.fn()}
/>,
);
expect(screen.getByRole("button", { name: "Reasoning Effort" })).toHaveTextContent("medium");
expect(screen.queryByRole("button", { name: "Agent settings" })).not.toBeInTheDocument();
});
it("keeps effort with model settings and the mode with Allow All", () => {
it("shows the effort as its own picker beside the model, and the mode with Allow All", () => {
const onChange = vi.fn();
render(<ConfigPickers config={copilotConfig()} onChange={onChange} />);
const model = screen.getByRole("button", { name: "Model" });
expect(model).toHaveTextContent("Claude Sonnet 5.5");
expect(model).toHaveTextContent("medium");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("Claude Sonnet 5.5");
expect(screen.getByRole("button", { name: "Mode" })).toHaveTextContent("AgentAllow All");
fireEvent.click(model);
const dialog = screen.getByRole("dialog", { name: "Model" });
const effort = within(dialog).getByRole("radiogroup", { name: "Effort Level" });
expect(within(effort).getByRole("radio", { name: "medium" })).toHaveAttribute("aria-checked", "true");
fireEvent.click(within(effort).getByRole("radio", { name: "XHigh" }));
const effort = screen.getByRole("button", { name: "Reasoning Effort" });
expect(effort).toHaveTextContent("medium");
fireEvent.click(effort);
fireEvent.click(screen.getByRole("option", { name: "XHigh" }));
expect(onChange).toHaveBeenCalledExactlyOnceWith("reasoning_effort", "xhigh");
});
it("offers more effort levels than fit the segmented control as a dropdown", () => {
const onChange = vi.fn();
const config = copilotConfig().map((o) =>
o.category === "thought_level"
? {
...o,
values: ["Low", "Medium", "High", "Extra high", "Max", "Ultra"].map((name) =>
value(name.toLowerCase().replace(" ", "-"), name),
),
current: "max",
}
: o,
);
render(<ConfigPickers config={config} onChange={onChange} />);
const model = screen.getByRole("button", { name: "Model" });
expect(model).toHaveTextContent("Max");
fireEvent.click(model);
const dialog = screen.getByRole("dialog", { name: "Model" });
expect(within(dialog).queryByRole("radiogroup", { name: "Effort Level" })).not.toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("button", { name: /Reasoning Effort/ }));
fireEvent.click(screen.getByRole("option", { name: /Extra high/ }));
expect(onChange).toHaveBeenCalledWith("reasoning_effort", "extra-high");
});
it("tucks Fast into the model popup", () => {
const config = [
...copilotConfig().filter((o) => o.category !== "thought_level"),
@@ -417,19 +369,13 @@ describe("model settings", () => {
values: [value("default", "200K"), value("long_context", "1M")],
});
render(<ConfigPickers config={cfg} onChange={onChange} />);
const model = screen.getByRole("button", { name: "Model" });
expect(model).toHaveTextContent("Claude Sonnet 5.5");
expect(model).toHaveTextContent("medium");
expect(model).toHaveTextContent("1M");
expect(model).toHaveAttribute("title", expect.stringContaining("Effort Level: medium · Context Size: 1M"));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("Claude Sonnet 5.51M");
fireEvent.click(model);
fireEvent.click(screen.getByRole("button", { name: "Model" }));
const dialog = screen.getByRole("dialog", { name: "Model" });
expect(within(dialog).queryByText("Balanced")).not.toBeInTheDocument();
expect(within(dialog).getByText("Medium cost")).toBeVisible();
const effortGroup = within(dialog).getByRole("radiogroup", { name: "Effort Level" });
expect(within(effortGroup).getByRole("radio", { name: "medium" })).toHaveAttribute("aria-checked", "true");
const contextGroup = within(dialog).getByRole("radiogroup", { name: "Context Size" });
expect(within(contextGroup).getByRole("radio", { name: "1M" })).toHaveAttribute("aria-checked", "true");
fireEvent.click(within(contextGroup).getByRole("radio", { name: "200K" }));
+10 -48
View File
@@ -1,7 +1,7 @@
/**
* Model, effort, mode and approvals controls for a composer's bottom row. The model button
* opens a searchable model list (pinned models first) and keeps effort and context settings
* together above it.
* opens a searchable model list (pinned models first, context size above it); the effort is
* its own picker beside it, one click away.
*/
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
@@ -119,16 +119,16 @@ export function ConfigPickers({
const effort = config.find((o) => o.category === "thought_level" && o.values.length > 0);
const modelConfigs = modelConfigOptions(config);
const hasCostMeta = model?.values.some((v) => !!v.costCategory || !!v.usageMultiplier || !!v.pricing) ?? false;
const combinedModel = !!model && (!!modelRefresh || modelConfigs.length > 0 || hasCostMeta || !!effort);
const tuckedEffort = combinedModel ? (effort ?? null) : null;
const combinedModel = model && (modelRefresh || modelConfigs.length > 0 || hasCostMeta);
const tuckedModelConfig = new Set(modelConfigs.map((o) => o.id));
const mode = options.find((o) => o.category === "mode");
const allowAll = mode && options.find((o) => switchValues(o));
// Effort sits right after the model, as its own one-click picker.
const inline = options.filter(
(o) => o !== effort && o !== allowAll && !(combinedModel && tuckedModelConfig.has(o.id)),
);
if (effort && !tuckedEffort) inline.splice(model ? inline.indexOf(model) + 1 : 0, 0, effort);
// The compact menu holds everything but the model, effort, and model-specific parameters.
if (effort) inline.splice(model ? inline.indexOf(model) + 1 : 0, 0, effort);
// The compact menu holds everything but the model and effort buttons (and the model's own parameters).
const secondary = options.filter(
(o) => o.category !== "model" && o !== effort && !(combinedModel && tuckedModelConfig.has(o.id)),
);
@@ -146,8 +146,6 @@ export function ConfigPickers({
model={o}
modelValue={valueOf(o)}
modelConfigs={modelConfigs}
effort={tuckedEffort}
effortValue={tuckedEffort ? valueOf(tuckedEffort) : null}
valueOf={valueOf}
onChange={onChange}
modelRefresh={modelRefresh}
@@ -256,16 +254,11 @@ function ConfigPicker({
);
}
/** Effort levels that fit the popup's segmented control; more (Codex has six) get a dropdown. */
const SEGMENTED_EFFORT_MAX = 4;
/** The model button: a searchable model list, with effort, context size and model settings above it. */
/** The model button: a searchable model list, with context size and the model's own settings above it. */
function ModelPicker({
model,
modelValue,
modelConfigs,
effort,
effortValue,
valueOf,
onChange,
modelRefresh,
@@ -273,8 +266,6 @@ function ModelPicker({
model: AgentConfigOption;
modelValue: string | null;
modelConfigs: AgentConfigOption[];
effort: AgentConfigOption | null;
effortValue: string | null;
valueOf: (o: AgentConfigOption) => string | null;
onChange: (option: string, value: string) => void;
modelRefresh?: ModelRefresh;
@@ -291,13 +282,9 @@ function ModelPicker({
const contextOption = modelConfigs.find((o) => isContextOption(o.id) && o.values.length > 0);
const contextValue = contextOption ? valueOf(contextOption) : null;
const contextLabel = contextOption
? ((selected(contextOption, contextValue) ?? contextOption.values[0])?.name ?? null)
: null;
const effortLabel = effort ? ((selected(effort, effortValue) ?? effort.values[0])?.name ?? null) : null;
const contextLabel = contextOption ? (selected(contextOption, contextValue)?.name ?? null) : null;
const otherModelConfigs = modelConfigs.filter((o) => o !== contextOption);
const summary = [
effortLabel ? `${tx("Effort Level")}: ${effortLabel}` : null,
contextLabel ? `${tx("Context Size")}: ${contextLabel}` : null,
...otherModelConfigs.map((o) => {
const current = selected(o, valueOf(o));
@@ -323,11 +310,7 @@ function ModelPicker({
}}
>
<span className={styles.chipValue}>{modelName}</span>
{(effortLabel || contextLabel) && (
<span className={clsx(styles.chipDetail, styles.modelDetail)}>
{[effortLabel, contextLabel].filter(Boolean).join(" · ")}
</span>
)}
{contextLabel && <span className={styles.chipDetail}>{contextLabel}</span>}
<Icon name="chevron-down" size={14} className={styles.chipChevron} />
</button>
<Popup
@@ -342,29 +325,8 @@ function ModelPicker({
<T>Choose another model before starting.</T>
</p>
)}
{(effort || contextOption || otherModelConfigs.length > 0) && (
{(contextOption || otherModelConfigs.length > 0) && (
<div className={styles.quickSettings}>
{effort && (
<div className={styles.quickRow}>
<span className={styles.quickLabel}>
<T>Effort Level</T>
</span>
{effort.values.length <= SEGMENTED_EFFORT_MAX ? (
<SegmentedControl
ariaLabel={tx("Effort Level")}
options={effort.values.map((v) => ({
value: v.value,
label: v.name,
description: v.description ?? undefined,
}))}
value={effortValue ?? effort.values[0]!.value}
onChange={(v) => onChange(effort.id, v)}
/>
) : (
<ConfigPicker option={effort} value={effortValue} onChange={onChange} framed />
)}
</div>
)}
{contextOption && (
<div className={styles.quickRow}>
<span className={styles.quickLabel}>
+16 -24
View File
@@ -1,5 +1,5 @@
import { beforeEach, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { AgentConfigOption, AgentProvider, NewAgentTask } from "@/bindings";
import { useProject } from "@/platform/project";
import { HomeEditor } from "./HomeEditor";
@@ -77,32 +77,26 @@ beforeEach(() => {
updateComposer(HOME, { text: "Check the project" });
});
const modelButton = () => screen.getByRole("button", { name: "Model" });
const effortButton = () => screen.getByRole("button", { name: "Reasoning" });
async function chooseModel(model: string) {
if (!screen.queryByRole("dialog", { name: "Model" })) fireEvent.click(modelButton());
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("option", { name: model }));
fireEvent.pointerDown(document.body);
}
async function chooseEffort(effort: string) {
if (!screen.queryByRole("dialog", { name: "Model" })) fireEvent.click(modelButton());
const group = screen.getByRole("radiogroup", { name: "Effort Level" });
fireEvent.click(within(group).getByRole("radio", { name: effort }));
fireEvent.keyDown(document, { key: "Escape" });
}
it("switches model-specific levels and restores each draft effort before starting", async () => {
render(<HomeEditor />);
expect(modelButton()).toHaveTextContent("big");
expect(modelButton()).toHaveTextContent("high");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big");
expect(effortButton()).toHaveTextContent("high");
await chooseModel("small");
expect(modelButton()).toHaveTextContent("minimal");
await chooseEffort("medium");
expect(effortButton()).toHaveTextContent("minimal");
fireEvent.click(effortButton());
fireEvent.click(screen.getByRole("option", { name: "medium" }));
await chooseModel("big");
expect(modelButton()).toHaveTextContent("high");
expect(effortButton()).toHaveTextContent("high");
await chooseModel("small");
expect(modelButton()).toHaveTextContent("medium");
expect(effortButton()).toHaveTextContent("medium");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([
@@ -130,13 +124,11 @@ it("uses GitHub Copilot's own defaults and preserves per-model context tier and
};
useAgents.setState({ providers: [copilot], draft: savedDraft({ provider: "copilot", config: {} }) });
render(<HomeEditor />);
expect(modelButton()).toHaveTextContent("gemini-4-carbon");
expect(modelButton()).toHaveTextContent("medium");
expect(modelButton()).toHaveTextContent("default");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("gemini-4-carbondefault");
expect(effortButton()).toHaveTextContent("medium");
await chooseModel("gpt-5.6-sol");
expect(modelButton()).toHaveTextContent("gpt-5.6-sol");
expect(modelButton()).toHaveTextContent("medium");
expect(modelButton()).toHaveTextContent("default");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("gpt-5.6-soldefault");
expect(effortButton()).toHaveTextContent("medium");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([
@@ -149,7 +141,7 @@ it("uses GitHub Copilot's own defaults and preserves per-model context tier and
it.each(["plain", "unknown"])("hides effort for %s models and sends no stale effort", async (model) => {
render(<HomeEditor />);
await chooseModel(model);
expect(modelButton()).toHaveAttribute("aria-haspopup", "dialog");
expect(screen.getByRole("button", { name: "Model" })).toHaveAttribute("aria-haspopup", "dialog");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([{ id: "model", value: model }]);
@@ -170,7 +162,7 @@ it("ignores old provider-wide effort choices and refreshes unsupported per-model
draft: savedDraft({ provider: "fake", config: { effort: "low" }, thoughtLevels: { big: { effort: "removed" } } }),
});
render(<HomeEditor />);
expect(modelButton()).toHaveTextContent("high");
expect(effortButton()).toHaveTextContent("high");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toContainEqual({ id: "effort", value: "high" });
-67
View File
@@ -274,73 +274,6 @@ describe("pickAgent", () => {
});
});
describe("pickAgent with an agent chosen for commit messages", () => {
const effort: AgentConfigOption = {
id: "effort",
name: "Effort",
description: null,
category: "thought_level",
current: "high",
values: ["low", "high"].map((value) => ({ value, name: value, description: null })),
via: "option",
};
const claude = { ...provider("claude", true, [modelOption("smart")]), thoughtLevels: { fast: [effort] } };
const tasks = [
task("a", "claude", { updatedMs: 1, config: [modelOption("smart")] }),
task("b", "codex", { updatedMs: 5 }),
];
const prefer = (agent: string, model = "", level = "") => ({ agent, agentModel: model, agentEffort: level });
it("uses that agent over the latest task's, on the model of its own latest task", () => {
expect(pickAgent(tasks, [claude, provider("codex")], draft("codex"), prefer("claude"))).toEqual({
provider: "claude",
config: [{ id: "model", value: "smart" }],
});
});
it("runs the chosen model at the chosen effort", () => {
expect(pickAgent(tasks, [claude, provider("codex")], draft("codex"), prefer("claude", "fast", "low"))).toEqual({
provider: "claude",
config: [
{ id: "model", value: "fast" },
{ id: "effort", value: "low" },
],
});
});
it("reads the models from the agent's refreshed catalog", () => {
const catalog = {
config: [{ ...modelOption("smart"), values: [{ value: "mini", name: "mini", description: null }] }],
thoughtLevels: { mini: [effort] },
};
expect(
pickAgent([], [claude], draft("claude"), prefer("claude", "mini", "low"), new Map([["claude", catalog]])),
).toEqual({
provider: "claude",
config: [
{ id: "model", value: "mini" },
{ id: "effort", value: "low" },
],
});
});
it("keeps the agent's model and effort for values it doesn't offer", () => {
expect(pickAgent([], [claude], draft("claude"), prefer("claude", "gone", "low"))).toEqual({
provider: "claude",
config: [{ id: "model", value: "smart" }],
});
});
it("follows the latest task when the chosen agent isn't installed", () => {
expect(
pickAgent(tasks, [provider("claude", false), provider("codex")], draft("codex"), prefer("claude", "fast")),
).toEqual({
provider: "codex",
config: [],
});
});
});
describe("generateCommitMessage", () => {
const changes = { revision: 3, roots: ["/p"], patch: PATCH };
const notified = () => backend.notify.mock.calls.map(([n]) => n as { level: string; title: string; body?: string });
+9 -62
View File
@@ -3,14 +3,7 @@
* changes about to be committed and writes their message. It runs as a short task that
* is deleted once the message is in the commit field.
*/
import type {
AgentConfigChoice,
AgentConfigOption,
AgentEntry,
AgentModelCatalog,
AgentProvider,
AgentTask,
} from "@/bindings";
import type { AgentConfigChoice, AgentConfigOption, AgentEntry, AgentProvider, AgentTask } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
@@ -146,74 +139,28 @@ export function askingChoices(options: readonly AgentConfigOption[]): AgentConfi
const choicesFor = (options: readonly AgentConfigOption[]) => [...modelChoice(options), ...askingChoices(options)];
/** Settings › Version Control › Commit: the agent, model and thinking level to generate with; empty follows the agent. */
export interface CommitAgentPreference {
agent: string;
agentModel: string;
agentEffort: string;
}
type ModelCatalog = Pick<AgentModelCatalog, "config" | "thoughtLevels">;
/**
* The agent that wrote the code: the one of the project's latest task, on the model it
* ran with. Without a task, the one the New Task page has selected. An agent chosen in
* the settings replaces it, on the model and thinking level chosen there when it offers them.
* ran with. Without a task, the one the New Task page has selected.
*/
export function pickAgent(
tasks: Iterable<AgentTask>,
providers: readonly AgentProvider[],
draft: Draft,
preference?: CommitAgentPreference,
catalogs?: ReadonlyMap<string, ModelCatalog>,
): CommitAgent | null {
const installed = providers.filter((p) => p.installed);
const chosen = preference?.agent ? installed.find((p) => p.id === preference.agent) : undefined;
const candidates = chosen ? [chosen] : installed;
const latest = [...tasks]
.filter((t) => t.status !== "archived" && candidates.some((p) => p.id === t.provider))
.filter((t) => t.status !== "archived" && installed.some((p) => p.id === t.provider))
.sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0))[0];
const provider = latest
? installed.find((p) => p.id === latest.provider)!
: (chosen ?? installed.find((p) => p.id === draft.provider) ?? installed[0]);
if (latest) return { provider: latest.provider, config: choicesFor(latest.config) };
const provider = installed.find((p) => p.id === draft.provider) ?? installed[0];
if (!provider) return null;
const options = latest
? latest.config
: provider.id === draft.provider
? draftConfig(provider, draft)
: provider.config;
if (!chosen || !preference || (!preference.agentModel && !preference.agentEffort)) {
return { provider: provider.id, config: choicesFor(options) };
}
return {
provider: provider.id,
config: [...preferredModel(options, provider, preference, catalogs?.get(provider.id)), ...askingChoices(options)],
config: choicesFor(provider.id === draft.provider ? draftConfig(provider, draft) : provider.config),
};
}
/** The model and thinking level of `preference` that the agent offers, else the ones it would run with. */
function preferredModel(
options: readonly AgentConfigOption[],
provider: AgentProvider,
preference: CommitAgentPreference,
catalog: ModelCatalog | undefined,
): AgentConfigChoice[] {
const offered = (catalog?.config ?? provider.config).find((o) => o.category === "model");
const fallback = modelChoice(options);
const model =
offered && preference.agentModel && offered.values.some((v) => v.value === preference.agentModel)
? { id: offered.id, value: preference.agentModel }
: fallback[0];
if (!model) return [];
const levels = (catalog?.thoughtLevels ?? provider.thoughtLevels)?.[model.value] ?? [];
const level = levels.find((o) => o.category === "thought_level");
const effort =
level && preference.agentEffort && level.values.some((v) => v.value === preference.agentEffort)
? [{ id: level.id, value: preference.agentEffort }]
: [];
return [model, ...effort];
}
/** Resolves when the task's turn ends; rejects when it can't produce an answer. */
function turnEnd(task: string): Promise<void> {
return new Promise((resolve, reject) => {
@@ -296,9 +243,8 @@ async function generate(): Promise<void> {
notify({ level: "info", title: "No changes to describe", body: "Include changes in the commit first." });
return;
}
const { commit } = workflowSettings().vcs;
const { tasks, providers, draft, modelCatalogs } = useAgents.getState();
const agent = pickAgent(tasks.values(), providers, draft, commit, modelCatalogs);
const { tasks, providers, draft } = useAgents.getState();
const agent = pickAgent(tasks.values(), providers, draft);
if (!agent) {
notify({
level: "warning",
@@ -309,6 +255,7 @@ async function generate(): Promise<void> {
return;
}
const { commit } = workflowSettings().vcs;
const subjects = await recentSubjects(changes.roots[0]);
const prompt = commitMessagePrompt(
changes.patch,
+11 -10
View File
@@ -219,7 +219,7 @@ it("refreshes an existing chat's searchable model choices and switches through i
expect(modelButton).toHaveTextContent("old");
expect(screen.getByRole("option", { name: "session-only" })).toBeVisible();
expect(modelButton).toHaveTextContent("low");
expect(screen.getByRole("button", { name: "Reasoning" })).toHaveTextContent("low");
expect(screen.getByRole("button", { name: "Mode" })).toHaveTextContent("plan");
expect(screen.getByText("Earlier message")).toBeVisible();
expect(screen.queryByText("catalog-only")).not.toBeInTheDocument();
@@ -324,7 +324,7 @@ it("retains cached model and effort choices after a command failure and retries
draft: savedDraft({ provider: "first", config: { model: "big" }, thoughtLevels: { big: { effort: "low" } } }),
});
render(<HomeEditor />);
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("low");
expect(screen.getByRole("button", { name: "Reasoning" })).toHaveTextContent("low");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(await screen.findByRole("alert")).toHaveTextContent("connection lost");
fireEvent.click(screen.getByRole("option", { name: "small" }));
@@ -351,7 +351,7 @@ it("preserves a valid remembered model and effort when discovery changes the def
render(<HomeEditor />);
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("low");
expect(screen.getByRole("button", { name: "Reasoning" })).toHaveTextContent("low");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(screen.getByRole("option", { name: "new" })).toBeVisible();
fireEvent.keyDown(document, { key: "Escape" });
@@ -471,7 +471,7 @@ it("discovers an uncached model's own settings before its first task and restore
fireEvent.click(screen.getByRole("option", { name: "small" }));
await waitFor(() => expect(backend.refresh).toHaveBeenLastCalledWith("first", false, "small"));
expect(screen.getByText("Loading model settings…")).toHaveAttribute("role", "status");
expect(screen.queryByRole("dialog", { name: "Model" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Reasoning" })).not.toBeInTheDocument();
expect(backend.create).not.toHaveBeenCalled();
await act(async () =>
pending.resolve(
@@ -489,16 +489,17 @@ it("discovers an uncached model's own settings before its first task and restore
),
);
expect(screen.queryByText("Loading model settings…")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("medium");
expect(screen.getByRole("button", { name: "Reasoning" })).toHaveTextContent("medium");
fireEvent.click(screen.getByRole("button", { name: "Reasoning" }));
fireEvent.click(screen.getByRole("option", { name: "max" }));
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("radio", { name: "max" }));
expect(screen.getByRole("radio", { name: "long_context" })).toBeVisible();
fireEvent.click(screen.getByRole("radio", { name: "long_context" }));
fireEvent.click(screen.getByRole("option", { name: "big" }));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("high");
expect(screen.getByRole("button", { name: "Reasoning" })).toHaveTextContent("high");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("option", { name: "small" }));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("max");
expect(screen.getByRole("button", { name: "Reasoning" })).toHaveTextContent("max");
expect(backend.refresh).toHaveBeenCalledTimes(2);
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
@@ -548,7 +549,7 @@ it("waits for an unrelated lookup and discovers only the latest selected model",
ok(catalog("first", { thoughtLevels: { latest: [option("effort", "thought_level", ["medium", "max"])] } })),
),
);
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("medium");
expect(screen.getByRole("button", { name: "Reasoning" })).toHaveTextContent("medium");
expect(backend.refresh).toHaveBeenCalledTimes(2);
expect(backend.create).not.toHaveBeenCalled();
});
@@ -606,7 +607,7 @@ it("does not leak a delayed model's levels or failure into a newer selection", a
),
);
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("low");
expect(screen.getByRole("button", { name: "Reasoning" })).toHaveTextContent("low");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Refresh models" })).toBeEnabled();
+1 -2
View File
@@ -55,8 +55,7 @@ const VOID_HTML = new Set([
export function prettyMarkup(body: string, html = false, indent = " "): string {
// Split into tags / comments / text; raw elements (script, style, pre) stay one token.
const tokens: string[] = [];
// A quoted attribute value may hold `>`; an unclosed quote falls back to the first `>`.
const re = /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<(?:[^>"']|"[^"]*"|'[^']*')+>|<[^>]+>|[^<]+|</g;
const re = /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<[^>]+>|[^<]+|</g;
for (let m = re.exec(body); m; m = re.exec(body)) {
const tok = m[0];
const name = /^<\s*([\w:.-]+)/.exec(tok)?.[1]?.toLowerCase();
@@ -69,17 +69,6 @@ describe("response bodies", () => {
);
});
it("keeps a `>` inside an attribute value within its tag", () => {
expect(prettyMarkup("<rules><rule when=\"a > b\"/><rule when='c > d'>x</rule></rules>")).toBe(
["<rules>", ' <rule when="a > b"/>', " <rule when='c > d'>x</rule>", "</rules>"].join("\n"),
);
expect(prettyMarkup('<div><button onclick="items.filter(i => i.done)">Go</button><p>after</p></div>', true)).toBe(
["<div>", ' <button onclick="items.filter(i => i.done)">Go</button>', " <p>after</p>", "</div>"].join("\n"),
);
// An unclosed quote still ends the tag at the first `>`.
expect(prettyMarkup('<a><b title="x>1</b></a>')).toBe(["<a>", ' <b title="x>1</b>', "</a>"].join("\n"));
});
it("formats sizes and durations", () => {
expect(formatSize(512)).toBe("512 B");
expect(formatSize(2048)).toBe("2.0 KB");
+1 -2
View File
@@ -44,7 +44,6 @@ export const OPTION_LABELS: Array<[ToggleOption, string]> = [
["showExcluded", "Show Excluded Files"],
["showMembers", "Show Members"],
["showRootPaths", "Show Root Paths"],
["horizontalScroll", "Horizontal Scrolling"],
["compact", "Compact Middle Packages"],
["foldersFirst", "Sort Folders First"],
["autoscrollFromSource", "Always Select Opened File"],
@@ -55,7 +54,7 @@ export const OPTION_LABELS: Array<[ToggleOption, string]> = [
];
/** The first entries of OPTION_LABELS are Appearance options, the rest Behavior. */
const APPEARANCE_OPTIONS = 7;
const APPEARANCE_OPTIONS = 6;
/** Header controls of the Project tool window (IDEA: Locate, Expand/Collapse All). */
export function ProjectHeaderActions() {
+1 -1
View File
@@ -907,7 +907,7 @@ export function ProjectView() {
</div>
)}
<Tree<ProjectNode>
horizontalScroll={options.horizontalScroll}
horizontalScroll
aria-label="Project"
focusContext="projectViewFocus"
handleRef={setTreeHandle}
-3
View File
@@ -63,8 +63,6 @@ export interface ViewOptions extends TreeOptions {
showMembers: boolean;
/** Show the location of each project root beside its name. */
showRootPaths: boolean;
/** Rows wider than the pane scroll sideways; off clips long names (VS Code's horizontal scrolling). */
horizontalScroll: boolean;
}
export const DEFAULT_VIEW_OPTIONS: ViewOptions = {
@@ -77,7 +75,6 @@ export const DEFAULT_VIEW_OPTIONS: ViewOptions = {
previewTab: false,
showMembers: false,
showRootPaths: true,
horizontalScroll: true,
};
function storedOptions(): ViewOptions {
@@ -1,201 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { commands } from "@/platform/ipc";
import { ExportTestResultsDialog, defaultExportPath, loadExportOptions } from "./ExportTestResultsDialog";
import { TestResults } from "./testing";
const actions = vi.hoisted(() => ({ executeAction: vi.fn(async () => {}) }));
vi.mock("@/platform/actions", async (orig) => ({ ...(await orig<object>()), executeAction: actions.executeAction }));
const notify = vi.hoisted(() => vi.fn());
vi.mock("@/workbench/contributions", async (orig) => ({
...(await orig<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify }),
}));
const messages = vi.hoisted(() => ({ confirm: vi.fn(async () => true) }));
vi.mock("@/workbench/messages", async (orig) => ({ ...(await orig<object>()), confirm: messages.confirm }));
const dialog = vi.hoisted(() => ({ save: vi.fn(async (): Promise<string | null> => null) }));
vi.mock("@/platform/dialog", () => dialog);
const ok = { status: "ok", data: null } as const;
let onDisk: Record<string, "file" | "dir"> = {};
let written: { path: string; text: string }[] = [];
beforeEach(() => {
localStorage.clear();
onDisk = {};
written = [];
vi.spyOn(commands, "fsEntryKind").mockImplementation(async (path) =>
onDisk[path]
? { status: "ok", data: onDisk[path] }
: { status: "error", error: { kind: "NotFound", message: path } as never },
);
vi.spyOn(commands, "fsDelete").mockImplementation(async (path) => {
delete onDisk[path];
return ok;
});
vi.spyOn(commands, "fsOpenWithSystem").mockResolvedValue(ok);
vi.spyOn(commands, "fsCreateFileBytes").mockImplementation(async (path, data) => {
written.push({ path, text: new TextDecoder().decode(new Uint8Array(data)) });
return ok;
});
});
afterEach(() => vi.restoreAllMocks());
function results() {
const r = new TestResults();
r.apply([
{ type: "result", path: ["calc", "TestAdd"], status: "passed", durationMs: 3 },
{ type: "result", path: ["calc", "TestSub"], status: "failed", durationMs: 12 },
]);
r.finish(1);
return r;
}
function open(onClose = vi.fn()) {
render(<ExportTestResultsDialog results={results()} name="go test ./calc" cwd="/work/app/" onClose={onClose} />);
return onClose;
}
const file = () => screen.getByLabelText("Output file");
const press = (name: string) => fireEvent.click(screen.getByRole("button", { name }));
describe("ExportTestResultsDialog", () => {
it("writes an HTML report to the project folder under IDEA's name and opens it in the browser", async () => {
const onClose = open();
expect(file()).toHaveValue("/work/app/Test Results - go test _calc.html");
expect(screen.getByRole("radio", { name: "HTML" })).toBeChecked();
press("OK");
await waitFor(() => expect(onClose).toHaveBeenCalled());
expect(written).toHaveLength(1);
expect(written[0]!.path).toBe("/work/app/Test Results - go test _calc.html");
expect(written[0]!.text).toContain("<title>Test Results - go test ./calc</title>");
expect(commands.fsDelete).not.toHaveBeenCalled();
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ level: "info", body: written[0]!.path }));
expect(commands.fsOpenWithSystem).toHaveBeenCalledWith(written[0]!.path);
expect(actions.executeAction).not.toHaveBeenCalled();
});
it("opens a report outside the project through the built-in server", async () => {
vi.mocked(commands.fsOpenWithSystem).mockResolvedValueOnce({
status: "error",
error: { kind: "PermissionDenied", message: "outside the project" } as never,
});
const onClose = open();
fireEvent.change(file(), { target: { value: "/tmp/out.html" } });
press("OK");
await waitFor(() =>
expect(actions.executeAction).toHaveBeenCalledWith("web.openInBrowser", { path: "/tmp/out.html" }),
);
expect(onClose).toHaveBeenCalled();
});
it("switches the extension with the format, keeps XML out of the browser, and remembers the choice", async () => {
const onClose = open();
fireEvent.click(screen.getByRole("radio", { name: "XML" }));
expect(file()).toHaveValue("/work/app/Test Results - go test _calc.xml");
// Only an HTML report opens in the browser.
expect(screen.getByRole("checkbox", { name: "Open exported file in browser" })).toBeDisabled();
press("OK");
await waitFor(() => expect(onClose).toHaveBeenCalled());
expect(written[0]!.text).toMatch(/^<\?xml version="1.0" encoding="UTF-8"\?>\n<testrun /);
expect(commands.fsOpenWithSystem).not.toHaveBeenCalled();
expect(loadExportOptions()).toEqual({ format: "xml", openInBrowser: true });
});
it("doesn't open the browser when unticked", async () => {
const onClose = open();
fireEvent.click(screen.getByRole("checkbox", { name: "Open exported file in browser" }));
press("OK");
await waitFor(() => expect(onClose).toHaveBeenCalled());
expect(written).toHaveLength(1);
expect(commands.fsOpenWithSystem).not.toHaveBeenCalled();
expect(loadExportOptions().openInBrowser).toBe(false);
});
it("resolves a relative path against the working directory", async () => {
const onClose = open();
fireEvent.change(file(), { target: { value: " reports/out.html " } });
press("OK");
await waitFor(() => expect(onClose).toHaveBeenCalled());
expect(written[0]!.path).toBe("/work/app/reports/out.html");
});
it("asks before replacing a file, and keeps it when the answer is no", async () => {
onDisk["/work/app/out.html"] = "file";
messages.confirm.mockResolvedValueOnce(false);
const onClose = open();
fireEvent.change(file(), { target: { value: "/work/app/out.html" } });
press("OK");
await waitFor(() => expect(messages.confirm).toHaveBeenCalledTimes(1));
expect(messages.confirm).toHaveBeenCalledWith(
expect.objectContaining({ message: "File 'out.html' already exists. Do you want to overwrite it?" }),
);
await waitFor(() => expect(screen.getByRole("button", { name: "OK" })).toBeEnabled());
expect(written).toHaveLength(0);
expect(commands.fsDelete).not.toHaveBeenCalled();
expect(onClose).not.toHaveBeenCalled();
messages.confirm.mockResolvedValueOnce(true);
press("OK");
await waitFor(() => expect(onClose).toHaveBeenCalled());
expect(commands.fsDelete).toHaveBeenCalledWith("/work/app/out.html");
expect(written.map((w) => w.path)).toEqual(["/work/app/out.html"]);
});
it("doesn't ask again for a file the save dialog already confirmed", async () => {
onDisk["/tmp/picked.html"] = "file";
dialog.save.mockResolvedValueOnce("/tmp/picked.html");
const onClose = open();
press("Browse…");
await waitFor(() => expect(file()).toHaveValue("/tmp/picked.html"));
expect(dialog.save).toHaveBeenCalledWith(
expect.objectContaining({ filters: [{ name: "HTML", extensions: ["html"] }] }),
);
press("OK");
await waitFor(() => expect(onClose).toHaveBeenCalled());
expect(messages.confirm).not.toHaveBeenCalled();
expect(written.map((w) => w.path)).toEqual(["/tmp/picked.html"]);
});
it("reports a directory or a failed write and stays open", async () => {
onDisk["/work/app/reports"] = "dir";
const onClose = open();
fireEvent.change(file(), { target: { value: "/work/app/reports" } });
press("OK");
await waitFor(() =>
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ level: "error", body: "/work/app/reports is a directory" }),
),
);
expect(written).toHaveLength(0);
vi.mocked(commands.fsCreateFileBytes).mockResolvedValueOnce({
status: "error",
error: { kind: "PermissionDenied", message: "permission denied" } as never,
});
fireEvent.change(file(), { target: { value: "/ro/out.html" } });
press("OK");
await waitFor(() => expect(notify).toHaveBeenCalledTimes(2));
expect(onClose).not.toHaveBeenCalled();
expect(actions.executeAction).not.toHaveBeenCalled();
});
it("can't export to an empty path", () => {
open();
fireEvent.change(file(), { target: { value: " " } });
expect(screen.getByRole("button", { name: "OK" })).toBeDisabled();
});
});
describe("defaultExportPath", () => {
it("replaces characters file systems refuse in the configuration's name", () => {
expect(defaultExportPath("C:\\proj\\", 'a/b\\c:d*e?f"g<h>i|j', "xml")).toBe(
"C:\\proj/Test Results - a_b_c_d_e_f_g_h_i_j.xml",
);
expect(defaultExportPath("/p", "go test ./...", "html")).toBe("/p/Test Results - go test.html");
expect(defaultExportPath("/p", "Tests in 'com.acme.Cart'", "html")).toBe(
"/p/Test Results - Tests in 'com_acme_Cart'.html",
);
expect(defaultExportPath("/p", "...", "html")).toBe("/p/Test Results - Tests.html");
});
});
@@ -1,202 +0,0 @@
/**
* IDEA's Export Test Results dialog: HTML or XML, the output file, and whether to
* open an HTML report in the browser once it is written.
*/
import { useState } from "react";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { Checkbox, Dialog, IconButton, Input, Radio, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
import { exportTestResults, isAbsolutePath, type TestExportFormat } from "./testing/export";
import type { TestResults } from "./testing";
import styles from "./Run.module.css";
/** The format and "open in browser" choice, kept across exports (IDEA remembers them). */
const OPTIONS_KEY = "openidea.run.testExport";
interface ExportOptions {
format: TestExportFormat;
openInBrowser: boolean;
}
export function loadExportOptions(): ExportOptions {
try {
const v = JSON.parse(globalThis.localStorage?.getItem(OPTIONS_KEY) ?? "{}") as Partial<ExportOptions>;
return { format: v.format === "xml" ? "xml" : "html", openInBrowser: v.openInBrowser !== false };
} catch {
return { format: "html", openInBrowser: true };
}
}
function saveExportOptions(o: ExportOptions) {
try {
globalThis.localStorage?.setItem(OPTIONS_KEY, JSON.stringify(o));
} catch {
/* storage unavailable */
}
}
/**
* IDEA's default name, `Test Results - <configuration>.html`. Like IDEA's `PathUtil.suggestFileName`, runs of
* dots and characters file systems refuse become one `_` (`go test ./...` gives `go test`).
*/
export function defaultExportPath(dir: string, name: string, format: TestExportFormat): string {
const safe = name.replace(/[/\\:*?"<>|.]+/g, "_").replace(/^[\s_]+|[\s_]+$/g, "");
return `${dir.replace(/[\\/]+$/, "")}/Test Results - ${safe || "Tests"}.${format}`;
}
async function exists(path: string): Promise<"file" | "dir" | null> {
try {
const kind = await call(commands.fsEntryKind(path));
return kind === "dir" ? "dir" : "file";
} catch {
return null;
}
}
/** Writes the report; false when the user kept an existing file or the write failed. */
export async function writeTestReport(path: string, text: string, confirmed: boolean): Promise<boolean> {
const name = path.split(/[\\/]/).pop() ?? path;
try {
const kind = await exists(path);
if (kind === "dir") throw new Error(tx`${path} is a directory`);
if (kind === "file") {
if (
!confirmed &&
!(await confirm({
title: "Export Test Results",
message: tx`File '${name}' already exists. Do you want to overwrite it?`,
ok: "Overwrite",
}))
)
return false;
await call(commands.fsDelete(path));
}
await call(commands.fsCreateFileBytes(path, Array.from(new TextEncoder().encode(text))));
return true;
} catch (e) {
notifications().notify({
group: "run",
level: "error",
title: "Cannot export test results",
body: e instanceof Error ? e.message : String(e),
key: "run-test-export",
});
return false;
}
}
/**
* Opens the report with the system's browser as a file, without saving open editors; a file outside the project
* (which that refuses) goes through the built-in server instead.
*/
async function openReport(path: string): Promise<void> {
try {
await call(commands.fsOpenWithSystem(path));
} catch {
await executeAction("web.openInBrowser", { path });
}
}
export function ExportTestResultsDialog({
results,
name,
cwd,
onClose,
}: {
results: TestResults;
name: string;
cwd: string;
onClose: () => void;
}) {
const [options, setOptions] = useState(loadExportOptions);
const [path, setPath] = useState(() => defaultExportPath(cwd, name, options.format));
// The save dialog already asked before replacing this file.
const [picked, setPicked] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const html = options.format === "html";
const update = (next: Partial<ExportOptions>) => {
const merged = { ...options, ...next };
setOptions(merged);
saveExportOptions(merged);
// The file follows the format's extension, as in the Export Data dialog.
if (next.format) setPath((p) => p.replace(/\.(html|xml)$/i, `.${next.format}`));
};
const browse = async () => {
try {
const { save } = await import("@/platform/dialog");
const chosen = await save({
defaultPath: path,
filters: [{ name: html ? "HTML" : "XML", extensions: [options.format] }],
});
if (chosen) {
setPath(chosen);
setPicked(chosen);
}
} catch {
// No dialog (tests): keep typing the path.
}
};
const run = async () => {
const raw = path.trim();
if (!raw) return;
const target = isAbsolutePath(raw) ? raw : `${cwd.replace(/[\\/]+$/, "")}/${raw}`;
setBusy(true);
const text = exportTestResults(options.format, results, { name, cwd, date: new Date() });
const ok = await writeTestReport(target, text, picked === raw);
setBusy(false);
if (!ok) return;
onClose();
notifications().notify({
group: "run",
level: "info",
title: "Test results exported",
body: target,
key: "run-test-export",
});
if (html && options.openInBrowser) void openReport(target);
};
return (
<Dialog
open
title="Export Test Results"
onClose={onClose}
width={520}
buttons={[
{ label: "OK", role: "default", disabled: busy || !path.trim(), onClick: () => void run() },
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.dialogBody}>
<div className={styles.exportFormats} role="radiogroup" aria-label="Export format">
<span>
<T>Export format:</T>
</span>
<Radio name="test-export-format" label="HTML" checked={html} onChange={() => update({ format: "html" })} />
<Radio name="test-export-format" label="XML" checked={!html} onChange={() => update({ format: "xml" })} />
</div>
<label className={styles.exportField}>
<span>
<T>Output file:</T>
</span>
<div className={styles.inputWithButton}>
<Input mono aria-label="Output file" value={path} onChange={(e) => setPath(e.target.value)} />
<IconButton icon="folder" title="Browse…" onClick={() => void browse()} />
</div>
</label>
<Checkbox
checked={html && options.openInBrowser}
disabled={!html}
onChange={(v) => update({ openInBrowser: v })}
label="Open exported file in browser"
/>
</div>
</Dialog>
);
}
-11
View File
@@ -953,17 +953,6 @@
gap: var(--space-2);
padding: 12px 16px;
}
.exportFormats {
display: flex;
align-items: center;
gap: var(--space-4);
}
.exportField {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
align-items: center;
gap: var(--space-2);
}
/* Folded console lines ("<N internal lines>"). */
.fold {
+2 -3
View File
@@ -45,8 +45,8 @@ import {
pinSession,
} from "./store";
import { rerunFailedConfigs } from "./testing/rerun";
import { formatDuration, nodeOutput } from "./testing";
import { TestTreeView } from "./TestTreeView";
import { nodeOutput } from "./testing";
import { TestTreeView, formatDuration } from "./TestTreeView";
import { StackTracePanel, useStackTraces, type StackTraceTab } from "./stackTrace";
import { closeRunTab, runTabMenu } from "./runTabs";
import { showApplicationUpdate, useApplicationUpdates } from "./applicationUpdate";
@@ -280,7 +280,6 @@ export function SessionPanel({
version={version}
cwd={cwd}
running={running}
name={session.config.name}
selected={selectedTest}
onSelect={setSelectedTest}
canRunTests={(ids) => canRunSelectedTests(session.id, ids)}
-46
View File
@@ -286,49 +286,3 @@ describe("Expand All / Collapse All", () => {
expect(screen.getByRole("button", { name: "Collapse All" })).toBeDisabled();
});
});
describe("Export Test Results", () => {
function finished() {
const r = new TestResults();
r.apply([{ type: "result", path: ["calc", "TestAdd"], status: "passed" }]);
r.finish(0);
return r;
}
const view = (results: TestResults, running: boolean) => (
<TestTreeView
results={results}
version={1}
cwd="/p"
name="calc tests"
selected={null}
onSelect={() => {}}
running={running}
/>
);
it("the button and the action open the dialog for the finished run", () => {
const { unmount } = render(view(finished(), false));
fireEvent.click(screen.getByRole("button", { name: "Export Test Results…" }));
expect(screen.getByRole("dialog", { name: "Export Test Results" })).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
act(() => testTree.exportResults!());
expect(screen.getByRole("dialog", { name: "Export Test Results" })).toBeInTheDocument();
expect(screen.getByLabelText("Output file")).toHaveValue("/p/Test Results - calc tests.html");
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(screen.queryByRole("dialog", { name: "Export Test Results" })).toBeNull();
unmount();
expect(testTree.exportResults).toBeNull();
});
it("is unavailable while the tests run and without results", () => {
const { rerender } = render(view(finished(), true));
expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeDisabled();
expect(testTree.exportResults).toBeNull();
rerender(view(new TestResults(), false));
expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeDisabled();
expect(testTree.exportResults).toBeNull();
rerender(view(finished(), false));
expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeEnabled();
expect(testTree.exportResults).not.toBeNull();
});
});
+24 -22
View File
@@ -14,10 +14,9 @@ import {
} from "@/ui";
import { useOccurrenceNavigator } from "@/workbench/contributions";
import { openTarget } from "./navigate";
import { formatDuration, nodeDuration, nodeStatus, type TestNode, type TestResults, type TestStatus } from "./testing";
import { nodeStatus, type TestNode, type TestResults, type TestStatus } from "./testing";
import { parseComparison } from "./testing/comparison";
import { TEST_TREE_FOCUS, testTree } from "./testTree";
import { ExportTestResultsDialog } from "./ExportTestResultsDialog";
import styles from "./Run.module.css";
import { tx } from "@/platform/i18n";
@@ -60,6 +59,28 @@ export function showTestDiff(node: TestNode): boolean {
return true;
}
export function formatDuration(ms: number | undefined): string {
if (ms === undefined) return "";
if (ms < 1000) return `${Math.round(ms)} ms`;
if (ms < 60_000) return `${(ms / 1000).toFixed(ms < 10_000 ? 2 : 1).replace(/\.?0+$/, "")} s`;
const m = Math.floor(ms / 60_000);
return `${m} m ${Math.round((ms % 60_000) / 1000)} s`;
}
function totalDuration(node: TestNode): number | undefined {
if (node.durationMs !== undefined) return node.durationMs;
let sum = 0;
let any = false;
for (const c of node.children) {
const d = totalDuration(c);
if (d !== undefined) {
sum += d;
any = true;
}
}
return any ? sum : undefined;
}
export function StatusIcon({ status }: { status: TestStatus | null }) {
switch (status) {
case "passed":
@@ -113,8 +134,6 @@ export interface TestTreeViewProps {
selected: string | null;
onSelect: (id: string | null) => void;
running: boolean;
/** The run configuration's name (Export Test Results names the file after it). */
name?: string;
/** Run / Debug the selected tests (context menu); absent when the configuration can't be narrowed. */
onRunTests?: (ids: string[], debug: boolean) => void;
canRunTests?: (ids: string[]) => boolean | Promise<boolean>;
@@ -127,7 +146,6 @@ export function TestTreeView({
selected,
onSelect,
running,
name = "Tests",
onRunTests,
canRunTests,
}: TestTreeViewProps) {
@@ -140,7 +158,6 @@ export function TestTreeView({
return next;
});
const [expanded, setExpanded] = useState<Set<string> | null>(null);
const [exporting, setExporting] = useState(false);
const [selection, setSelection] = useState<Set<string>>(new Set());
const tree = useRef<TreeHandle>(null);
const selectedKeys = useMemo(
@@ -223,17 +240,13 @@ export function TestTreeView({
return set;
}, [expanded, roots]);
// Export Test Results waits for the run to finish.
const canExport = !running && !results.isEmpty;
// Collapse All leaves the top-level suites in view, as IDEA's test tree does.
useEffect(() => {
testTree.expandAll = () => setExpanded(suiteIds(results.roots));
testTree.collapseAll = () => setExpanded(new Set());
testTree.exportResults = canExport ? () => setExporting(true) : null;
return () => {
testTree.expandAll = null;
testTree.collapseAll = null;
testTree.exportResults = null;
};
});
const hasSuites = roots.some((n) => n.children.length > 0);
@@ -304,18 +317,7 @@ export function TestTreeView({
title="Next Failed Test"
disabled={!hasNextFailed}
/>
<IconButton
icon="export"
size="small"
iconSize={16}
title="Export Test Results…"
disabled={!canExport}
onClick={() => setExporting(true)}
/>
</div>
{exporting && (
<ExportTestResultsDialog results={results} name={name} cwd={cwd} onClose={() => setExporting(false)} />
)}
<Tree<TestNode>
aria-label="Test results"
className={styles.testTree}
@@ -340,7 +342,7 @@ export function TestTreeView({
onContextMenu={contextMenu}
renderNode={(n) => {
const s = nodeStatus(n);
const d = nodeDuration(n);
const d = totalDuration(n);
return (
<span className={styles.testRow}>
<StatusIcon status={s} />
-11
View File
@@ -748,17 +748,6 @@ export function activate(): () => void {
keyWhen: TEST_TREE_FOCUS,
run: () => testTree.collapseAll?.(),
},
{
id: "run.exportTestResults",
title: "Export Test Results…",
description: "Save the test results as an HTML report or IDEA's XML",
category: "Run",
icon: "export",
when: "projectOpen && activeToolWindow == 'run'",
keywords: ["test", "results", "report", "html", "xml", "save"],
enabled: () => testTree.exportResults !== null,
run: () => testTree.exportResults?.(),
},
{
id: "run.reloadConfigs",
title: "Reload Run Configurations",
+2 -8
View File
@@ -1,14 +1,8 @@
/** Context key: the test results tree has focus. */
export const TEST_TREE_FOCUS = "testTreeFocus";
/** Set while a test results tree is shown: Expand All / Collapse All / Export Test Results act on it. */
export const testTree: {
expandAll: (() => void) | null;
collapseAll: (() => void) | null;
/** Null while the run is in progress or has no results. */
exportResults: (() => void) | null;
} = {
/** Set while a test results tree is shown: Expand All / Collapse All act on it. */
export const testTree: { expandAll: (() => void) | null; collapseAll: (() => void) | null } = {
expandAll: null,
collapseAll: null,
exportResults: null,
};
-152
View File
@@ -1,152 +0,0 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { exportTestResults, testResultsHtml, testResultsXml } from "./export";
import { TestResults } from "./results";
const info = { name: "go test ./calc", cwd: "/work/app", date: new Date(2026, 10, 19, 5, 40) };
function results() {
const r = new TestResults();
r.apply([
{ type: "result", path: ["calc", "TestAdd"], status: "passed", durationMs: 3 },
{ type: "result", path: ["calc", "TestSub"], status: "failed", durationMs: 12 },
{ type: "output", path: ["calc", "TestSub"], line: "expected: <1> but was: <2>" },
{ type: "location", path: ["calc", "TestSub"], location: { path: "calc/sub_test.go", line: 9, resolve: "path" } },
{ type: "result", path: ["calc", "TestDiv"], status: "skipped" },
{ type: "location", path: ["calc", "TestDiv"], location: { path: "div_test.go", line: 4, resolve: "name" } },
]);
r.finish(1);
return r;
}
describe("testResultsXml", () => {
it("writes IDEA's testrun format: counts, suites, tests, statuses, durations, output and the diff", () => {
expect(testResultsXml(results(), info)).toBe(
[
'<?xml version="1.0" encoding="UTF-8"?>',
`<testrun duration="15" footerText="Generated by OpenIDEA on ${info.date.toLocaleString()}" name="go test ./calc">`,
' <count name="total" value="3"/>',
' <count name="passed" value="1"/>',
' <count name="failed" value="1"/>',
' <count name="ignored" value="1"/>',
' <suite name="calc" status="failed" duration="15">',
' <test name="TestAdd" status="passed" duration="3"/>',
' <test locationUrl="file:///work/app/calc/sub_test.go:9" name="TestSub" status="failed" duration="12">',
' <diff actual="2" expected="1"/>',
' <output type="stdout">expected: &lt;1&gt; but was: &lt;2&gt;</output>',
" </test>",
// A file name to look up in the project is no location to link to.
' <test name="TestDiv" status="ignored"/>',
" </suite>",
"</testrun>",
"",
].join("\n"),
);
});
it("prefers the runner's total duration and keeps absolute and Windows locations as they are", () => {
const r = new TestResults();
r.apply([
{ type: "result", path: ["A"], status: "passed" },
{ type: "location", path: ["A"], location: { path: "C:\\src\\a_test.go", line: 2, resolve: "path" } },
{ type: "result", path: ["B"], status: "passed" },
{ type: "location", path: ["B"], location: { path: "/abs/b_test.go", resolve: "path" } },
{ type: "summary", durationMs: 1500 },
]);
r.finish(0);
const xml = testResultsXml(r, info);
expect(xml).toContain('<testrun duration="1500"');
expect(xml).toContain('locationUrl="file://C:/src/a_test.go:2"');
expect(xml).toContain('locationUrl="file:///abs/b_test.go"');
});
it("escapes markup, quotes and line breaks, and drops characters XML can't hold", () => {
const r = new TestResults();
r.apply([
{ type: "result", path: ['Test "quotes" & <tags>'], status: "failed" },
{ type: "output", path: ['Test "quotes" & <tags>'], line: "bell\u0007 and \u001b[31mred</output>" },
{ type: "output", path: ['Test "quotes" & <tags>'], line: 'expected: <"a\tb"> but was: <x & y>' },
]);
r.finish(1);
const xml = testResultsXml(r, { ...info, name: "it's <all>" });
expect(xml).toContain('name="it\'s &lt;all&gt;"');
expect(xml).toContain('<test name="Test &quot;quotes&quot; &amp; &lt;tags&gt;" status="failed">');
expect(xml).toContain('<diff actual="x &amp; y" expected="&quot;a&#9;b&quot;"/>');
expect(xml).toContain("bell and [31mred&lt;/output&gt;\nexpected:");
for (const c of ["\u0000", "\u0007", "\u001b"]) expect(xml).not.toContain(c);
});
it("rounds durations to whole milliseconds", () => {
const r = new TestResults();
r.apply([
{ type: "result", path: ["S", "a"], status: "passed", durationMs: 0.1 },
{ type: "result", path: ["S", "b"], status: "passed", durationMs: 1.2 },
]);
r.finish(0);
const xml = testResultsXml(r, info);
expect(xml).toContain('<suite name="S" status="passed" duration="1">');
expect(xml).toContain('<test name="a" status="passed" duration="0"/>');
expect(xml).toContain('<test name="b" status="passed" duration="1"/>');
});
it("writes an empty run, and marks tests the run never finished as terminated", () => {
expect(testResultsXml(new TestResults(), info)).toContain('<count name="total" value="0"/>\n</testrun>');
const r = new TestResults();
r.apply([{ type: "start", path: ["Slow"] }]);
expect(testResultsXml(r, info)).toContain('<test name="Slow" status="terminated"/>');
});
});
describe("testResultsHtml", () => {
it("is a standalone page with the summary, the tree, failures' output and source locations", () => {
const html = testResultsHtml(results(), info);
expect(html.startsWith("<!DOCTYPE html>")).toBe(true);
expect(html).toContain("<title>Test Results - go test ./calc</title>");
expect(html).toContain(
'<p class="summary"><b>3</b> tests · <b>1</b> passed · <b>1</b> failed · <b>1</b> ignored · 15 ms</p>',
);
expect(html).toContain(
'<details open class="failed"><summary><span class="status">Failed</span><span class="name">calc</span>',
);
expect(html).toContain(
'<span class="name">TestSub</span><span class="location">sub_test.go:9</span><span class="duration">12 ms</span>',
);
expect(html).toContain("<pre>expected: &lt;1&gt; but was: &lt;2&gt;</pre>");
expect(html).toContain(
'<div class="test ignored"><span class="status">Ignored</span><span class="name">TestDiv</span><span class="location">div_test.go:4</span></div>',
);
// Nothing loads from outside the file.
expect(html).not.toMatch(/<(script|link)\b/);
});
it("escapes test names and output", () => {
const r = new TestResults();
r.apply([
{ type: "result", path: ["<script>alert(1)</script>"], status: "failed" },
{ type: "output", path: ["<script>alert(1)</script>"], line: "<img src=x onerror=alert(1)>" },
]);
r.finish(1);
const html = testResultsHtml(r, { ...info, name: "<b>run</b>" });
expect(html).not.toContain("<script>alert");
expect(html).not.toContain("<img");
expect(html).toContain("<title>Test Results - &lt;b&gt;run&lt;/b&gt;</title>");
expect(html).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
});
it("leaves out ignored and duration from the summary when there are none", () => {
const r = new TestResults();
r.apply([{ type: "result", path: ["A"], status: "passed" }]);
r.finish(0);
expect(testResultsHtml(r, info)).toContain(
'<p class="summary"><b>1</b> tests · <b>1</b> passed · <b>0</b> failed</p>',
);
});
});
describe("exportTestResults", () => {
it("picks the writer by format", () => {
const r = results();
expect(exportTestResults("html", r, info)).toBe(testResultsHtml(r, info));
expect(exportTestResults("xml", r, info)).toBe(testResultsXml(r, info));
});
});
-231
View File
@@ -1,231 +0,0 @@
/**
* IDEA's Export Test Results: the results tree as a self-contained HTML report,
* or as XML in IDEA's `<testrun>` format (counts, suites, tests, output, diff).
*/
import { parseComparison } from "./comparison";
import { nodeDuration, nodeStatus, type TestNode, type TestResults } from "./results";
import { formatDuration } from "./types";
export type TestExportFormat = "html" | "xml";
export interface TestExportInfo {
/** The run configuration's name. */
name: string;
/** Working directory: relative test locations are resolved against it. */
cwd: string;
date: Date;
}
/** Status words as IDEA writes them (`skipped` tests are `ignored`). */
function statusOf(node: TestNode): "passed" | "failed" | "ignored" | "terminated" | "skipped" {
switch (nodeStatus(node)) {
case "passed":
return "passed";
case "failed":
return "failed";
case "skipped":
return "ignored";
case "running":
return "terminated";
default:
return "skipped";
}
}
function totalDuration(results: TestResults): number | undefined {
if (results.summary.durationMs !== undefined) return results.summary.durationMs;
let sum: number | undefined;
for (const r of results.roots) {
const d = nodeDuration(r);
if (d !== undefined) sum = (sum ?? 0) + d;
}
return sum;
}
export const isAbsolutePath = (path: string) => /^([a-zA-Z]:)?[\\/]/.test(path);
/** IDEA's `file://<path>:<line>` location of a test; only for locations that name a real path. */
function locationUrl(node: TestNode, cwd: string): string | undefined {
const loc = node.location;
if (!loc || loc.resolve !== "path") return undefined;
const abs = isAbsolutePath(loc.path) ? loc.path : `${cwd.replace(/[\\/]+$/, "")}/${loc.path}`;
return `file://${abs.replace(/\\/g, "/")}${loc.line !== undefined ? `:${loc.line}` : ""}`;
}
/** Where a test is, as the report shows it: `sub_test.go:9`. */
function locationText(node: TestNode): string | undefined {
const loc = node.location;
if (!loc) return undefined;
const file = loc.path.split(/[\\/]/).pop() ?? loc.path;
return loc.line !== undefined ? `${file}:${loc.line}` : file;
}
/** IDEA's importer reads durations as whole milliseconds. */
const ms = (d: number | undefined) => (d === undefined ? undefined : Math.round(d));
// XML 1.0 can't hold most control characters even escaped; test output may contain them.
// eslint-disable-next-line no-control-regex
const XML_INVALID = /[\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]/g;
function escapeXml(s: string): string {
return s
.replace(XML_INVALID, "")
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/\n/g, "&#10;")
.replace(/\r/g, "&#13;")
.replace(/\t/g, "&#9;");
}
/** Text content: line breaks stay as they are. */
const escapeText = (s: string) =>
s.replace(XML_INVALID, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
function attrs(values: Record<string, string | number | undefined>): string {
return Object.entries(values)
.filter(([, v]) => v !== undefined)
.map(([k, v]) => ` ${k}="${escapeXml(String(v))}"`)
.join("");
}
function counts(results: TestResults) {
const c = results.counts();
return { total: c.total, passed: c.passed, failed: c.failed, ignored: c.skipped };
}
/** IDEA's export XML (`TestResultsXmlFormatter`): the same tags, so IDEA's Import Tests from File can read it. */
export function testResultsXml(results: TestResults, info: TestExportInfo): string {
const out = ['<?xml version="1.0" encoding="UTF-8"?>'];
out.push(
`<testrun${attrs({
duration: ms(totalDuration(results)),
footerText: `Generated by OpenIDEA on ${info.date.toLocaleString()}`,
name: info.name,
})}>`,
);
for (const [name, value] of Object.entries(counts(results)))
if (value > 0 || name === "total") out.push(` <count${attrs({ name, value })}/>`);
const visit = (node: TestNode, depth: number) => {
const pad = " ".repeat(depth);
const tag = node.children.length > 0 ? "suite" : "test";
const head = `${pad}<${tag}${attrs({
locationUrl: locationUrl(node, info.cwd),
name: node.name,
status: statusOf(node),
duration: ms(nodeDuration(node)),
})}`;
const comparison = tag === "test" && nodeStatus(node) === "failed" ? parseComparison(node.output) : null;
if (node.children.length === 0 && node.output.length === 0 && !comparison) {
out.push(`${head}/>`);
return;
}
out.push(`${head}>`);
if (comparison) out.push(`${pad} <diff${attrs({ actual: comparison.actual, expected: comparison.expected })}/>`);
if (node.output.length > 0)
out.push(`${pad} <output type="stdout">${escapeText(node.output.join("\n"))}</output>`);
for (const c of node.children) visit(c, depth + 1);
out.push(`${pad}</${tag}>`);
};
for (const r of results.roots) visit(r, 1);
out.push("</testrun>", "");
return out.join("\n");
}
const STYLE = `
:root { color-scheme: light dark; --fg: #1f2328; --muted: #6a737d; --bg: #ffffff; --line: #d8dee4;
--passed: #1a7f37; --failed: #cf222e; --ignored: #9a6700; --code: #f6f8fa; }
@media (prefers-color-scheme: dark) { :root { --fg: #dfe1e5; --muted: #8c9199; --bg: #1e1f22; --line: #393b40;
--passed: #5fb865; --failed: #f75464; --ignored: #c9a23f; --code: #2b2d30; } }
body { margin: 24px; background: var(--bg); color: var(--fg); font: 13px/1.5 -apple-system, "Segoe UI", sans-serif; }
h1 { font-size: 18px; margin: 0 0 4px; }
.summary { margin: 0 0 16px; color: var(--muted); }
.summary b { color: var(--fg); }
ul { list-style: none; margin: 0; padding-left: 20px; }
body > ul { padding-left: 0; }
summary, .test { display: flex; gap: 8px; align-items: baseline; padding: 1px 0; }
summary { cursor: pointer; list-style: none; }
summary::-webkit-details-marker { display: none; }
summary::before { content: "\\25B8"; width: 10px; color: var(--muted); }
details[open] > summary::before { content: "\\25BE"; }
.test::before { content: ""; width: 10px; }
.status { font-weight: 600; min-width: 64px; }
.passed > .status, .passed > summary > .status { color: var(--passed); }
.failed > .status, .failed > summary > .status { color: var(--failed); }
.ignored > .status, .ignored > summary > .status, .skipped > .status, .terminated > .status { color: var(--ignored); }
.location, .duration { color: var(--muted); }
.duration { margin-left: auto; padding-left: 16px; }
pre { margin: 4px 0 8px 18px; padding: 8px; background: var(--code); border: 1px solid var(--line); border-radius: 4px;
overflow: auto; font: 12px/1.45 ui-monospace, Menlo, Consolas, monospace; white-space: pre-wrap; }
footer { margin-top: 24px; color: var(--muted); font-size: 12px; }
`;
const STATUS_TEXT = {
passed: "Passed",
failed: "Failed",
ignored: "Ignored",
terminated: "Terminated",
skipped: "Skipped",
};
/** A report that opens in any browser: summary, then the tree with each test's status, duration and output. */
export function testResultsHtml(results: TestResults, info: TestExportInfo): string {
const c = counts(results);
const total = totalDuration(results);
const title = `Test Results - ${info.name}`;
const parts = [`<b>${c.total}</b> tests`, `<b>${c.passed}</b> passed`, `<b>${c.failed}</b> failed`];
if (c.ignored > 0) parts.push(`<b>${c.ignored}</b> ignored`);
if (total !== undefined) parts.push(escapeText(formatDuration(total)));
const out = [
"<!DOCTYPE html>",
'<html lang="en">',
"<head>",
'<meta charset="utf-8">',
'<meta name="viewport" content="width=device-width, initial-scale=1">',
`<title>${escapeText(title)}</title>`,
`<style>${STYLE}</style>`,
"</head>",
"<body>",
`<h1>${escapeText(title)}</h1>`,
`<p class="summary">${parts.join(" · ")}</p>`,
];
const row = (node: TestNode, status: keyof typeof STATUS_TEXT) => {
const d = nodeDuration(node);
const where = locationText(node);
return [
`<span class="status">${STATUS_TEXT[status]}</span>`,
`<span class="name">${escapeText(node.name)}</span>`,
where ? `<span class="location">${escapeText(where)}</span>` : "",
d !== undefined ? `<span class="duration">${escapeText(formatDuration(d))}</span>` : "",
].join("");
};
const visit = (nodes: readonly TestNode[]) => {
out.push("<ul>");
for (const n of nodes) {
const status = statusOf(n);
const output = n.output.length > 0 ? `<pre>${escapeText(n.output.join("\n"))}</pre>` : "";
if (n.children.length === 0) {
out.push(`<li><div class="test ${status}">${row(n, status)}</div>${output}</li>`);
continue;
}
// Suites start open; a click on one folds it.
out.push(`<li><details open class="${status}"><summary>${row(n, status)}</summary>${output}`);
visit(n.children);
out.push("</details></li>");
}
out.push("</ul>");
};
visit(results.roots);
out.push(
`<footer>Generated by OpenIDEA on ${escapeText(info.date.toLocaleString())}</footer>`,
"</body>",
"</html>",
"",
);
return out.join("\n");
}
export function exportTestResults(format: TestExportFormat, results: TestResults, info: TestExportInfo): string {
return format === "html" ? testResultsHtml(results, info) : testResultsXml(results, info);
}
+2 -2
View File
@@ -12,8 +12,8 @@ import { zigParser } from "./zig";
import type { TestEvent, TestOutputParser } from "./types";
export type { TestEvent, TestOutputParser, TestStatus } from "./types";
export { formatDuration, parseDuration } from "./types";
export { TestResults, nodeDuration, nodeOutput, nodeStatus, type TestNode } from "./results";
export { parseDuration } from "./types";
export { TestResults, nodeOutput, nodeStatus, type TestNode } from "./results";
export {
cargoParser,
goParser,
-15
View File
@@ -19,21 +19,6 @@ export function nodeOutput(node: TestNode): string[] {
return [...node.output, ...node.children.flatMap(nodeOutput)];
}
/** A test's duration, or the sum of its children's for a group. */
export function nodeDuration(node: TestNode): number | undefined {
if (node.durationMs !== undefined) return node.durationMs;
let sum = 0;
let any = false;
for (const c of node.children) {
const d = nodeDuration(c);
if (d !== undefined) {
sum += d;
any = true;
}
}
return any ? sum : undefined;
}
export interface TestCounts {
passed: number;
failed: number;
-9
View File
@@ -43,15 +43,6 @@ export function parseDuration(text: string | undefined): number | undefined {
return matched ? Math.round(total * 1000) / 1000 : undefined;
}
/** Formats a duration the way the test tree shows it: `850 ms`, `1.25 s`, `2 m 5 s`. */
export function formatDuration(ms: number | undefined): string {
if (ms === undefined) return "";
if (ms < 1000) return `${Math.round(ms)} ms`;
if (ms < 60_000) return `${(ms / 1000).toFixed(ms < 10_000 ? 2 : 1).replace(/\.?0+$/, "")} s`;
const m = Math.floor(ms / 60_000);
return `${m} m ${Math.round((ms % 60_000) / 1000)} s`;
}
/**
* Stdout of a runner that prints machine-readable records (`go test -json`, PHPUnit `--teamcity`):
* feeds complete, unsplit lines to the test parser and returns each line's console text.
@@ -65,7 +65,6 @@ describe("languages settings", () => {
activeProfiles: "",
delegateBuild: false,
downloadSources: false,
updateSnapshots: false,
});
expect(validateSettings({}).languages).toEqual(DEFAULT_LANGUAGES);
expect(validateLanguages({ java: { maven: { threads: 4 } } }).java.maven.threads).toBe("");
@@ -78,7 +77,6 @@ describe("languages settings", () => {
expect(validateLanguages({ java: { maven: { delegateBuild: true } } }).java.maven.delegateBuild).toBe(true);
expect(validateLanguages({ java: { maven: { delegateBuild: "yes" } } }).java.maven.delegateBuild).toBe(false);
expect(validateLanguages({ java: { maven: { downloadSources: true } } }).java.maven.downloadSources).toBe(true);
expect(validateLanguages({ java: { maven: { updateSnapshots: true } } }).java.maven.updateSnapshots).toBe(true);
const settings = validateSettings({ languages: { java: { maven: { runnerJre: " ./jdks/21 " } } } });
expect(validateSettings(settings).languages.java.maven.runnerJre).toBe("./jdks/21");
});
@@ -564,7 +564,6 @@ export function MavenPage() {
const [delegateBuild, setDelegateBuild] = useSetting<boolean>("languages.java.maven.delegateBuild");
const [daemon, setDaemon] = useSetting<boolean>("languages.java.maven.daemon");
const [downloadSources, setDownloadSources] = useSetting<boolean>("languages.java.maven.downloadSources");
const [updateSnapshots, setUpdateSnapshots] = useSetting<boolean>("languages.java.maven.updateSnapshots");
const [threads, setThreads] = useSetting<string>("languages.java.maven.threads");
const [activeProfiles, setActiveProfiles] = useSetting<string>("languages.java.maven.activeProfiles");
const id = useId();
@@ -583,12 +582,6 @@ export function MavenPage() {
onChange={setDownloadSources}
hint="The Java language server downloads the sources of all dependencies when it imports the project. When off, a library class opens decompiled and its Download Sources banner fetches the sources of that library only."
/>
<Toggle
label="Always update snapshots"
checked={updateSnapshots}
onChange={setUpdateSnapshots}
hint="Checks remote repositories for newer SNAPSHOT dependencies on every sync, build and run (-U)."
/>
<SdkRow
k="languages.java.maven.runnerJre"
label="JRE"
@@ -215,9 +215,6 @@ export const EXECUTION_PAGES: PageSpec[] = [
"threads",
"-T",
"parallel",
"Always update snapshots",
"SNAPSHOT",
"-U",
],
component: MavenPage,
},
-11
View File
@@ -33,11 +33,6 @@ const SEND_KEY_OPTIONS = [
{ value: "enter", label: "Enter" },
{ value: "modEnter", label: "⌘Enter" },
];
const APP_TITLE_OPTIONS = [
{ value: "running", label: "When command is running" },
{ value: "always", label: "Always" },
{ value: "off", label: "Never" },
];
const WHILE_RUNNING_OPTIONS = [
{ value: "queue", label: "Queues the message for after the turn" },
{ value: "steer", label: "Sends it into the turn" },
@@ -606,12 +601,6 @@ export const TOOLS_PAGES: PageSpec[] = [
options: [
{ kind: "custom", label: "Shell path", component: ShellPathRow },
{ kind: "text", key: "terminal.tabName", label: "Default Tab name", placeholder: "Local" },
{
kind: "select",
key: "terminal.appTitleAsTabName",
label: "Use application title as tab name",
options: APP_TITLE_OPTIONS,
},
{
kind: "custom",
label: "Audible bell",
-118
View File
@@ -14,7 +14,6 @@ import { Button, Icon, IconButton, Input, Select, type SelectOption, T } from "@
import { choosePath } from "@/platform/choosePath";
import { Row, SettingSelect } from "../components/Form";
import { useSetting } from "../components/context";
import type { AgentModelCatalog, AgentProvider } from "@/bindings";
import type { PageSpec } from "./spec";
import { BoundToggle, Grid, Indented, RadioRow, TableEditor, ToggleNumber } from "./workflowControls";
import styles from "./Workflow.module.css";
@@ -379,117 +378,6 @@ function MessageLimits() {
);
}
const AUTOMATIC = "";
/** The installed coding agents, as the agents feature reports them; empty where agents can't run. */
function useInstalledAgents(): AgentProvider[] {
const [agents, setAgents] = useState<AgentProvider[]>([]);
useEffect(() => {
if (!isTauri()) return;
let live = true;
call(commands.agentProviders())
.then((all) => live && setAgents(all.filter((p) => p.installed)))
.catch(() => {});
return () => {
live = false;
};
}, []);
return agents;
}
type ModelCatalog = Pick<AgentModelCatalog, "config" | "thoughtLevels">;
/** The models `agent` offers, from its catalog; asks the agent for it once when it hasn't reported one. */
function useModelCatalog(agent: AgentProvider | undefined): ModelCatalog | undefined {
const [catalog, setCatalog] = useState<{ provider: string } & ModelCatalog>();
const id = agent?.id;
useEffect(() => {
if (!id) return;
let live = true;
let timer: ReturnType<typeof setTimeout> | undefined;
let polls = 0;
const load = () =>
call(commands.agentRefreshModels(id, false, null))
.then((c) => {
if (!live) return;
setCatalog(c);
if (c.refreshing && ++polls < CATALOG_POLLS) timer = setTimeout(load, CATALOG_POLL_MS);
})
.catch(() => {});
void load();
return () => {
live = false;
clearTimeout(timer);
};
}, [id]);
if (!agent) return undefined;
const fresh = catalog?.provider === agent.id && catalog.config.some((o) => o.category === "model");
return fresh ? catalog : { config: agent.config, thoughtLevels: agent.thoughtLevels ?? {} };
}
const CATALOG_POLL_MS = 1_500;
const CATALOG_POLLS = 40;
/** `values` as options after `automatic`, keeping a saved value the agent no longer lists. */
function choiceOptions(
automatic: string,
values: readonly { value: string; name: string }[],
saved: string,
): SelectOption<string>[] {
const options = [{ value: AUTOMATIC, label: automatic }, ...values.map((v) => ({ value: v.value, label: v.name }))];
return saved && !values.some((v) => v.value === saved) ? [...options, { value: saved, label: saved }] : options;
}
function CommitAgentRows() {
const agents = useInstalledAgents();
const [agent, setAgent] = useSetting<string>("vcs.commit.agent");
const [model, setModel] = useSetting<string>("vcs.commit.agentModel");
const [effort, setEffort] = useSetting<string>("vcs.commit.agentEffort");
const catalog = useModelCatalog(agents.find((p) => p.id === agent));
const models = catalog?.config.find((o) => o.category === "model");
const shown = model || models?.current;
const levels = (shown ? catalog?.thoughtLevels[shown] : undefined)?.find((o) => o.category === "thought_level");
const agentOptions = choiceOptions(
tx("Automatic (the agent of the latest task)"),
agents.map((p) => ({ value: p.id, name: p.name })),
agent,
);
const pick = (next: string) => {
if (next === agent) return;
setAgent(next);
setModel(AUTOMATIC);
setEffort(AUTOMATIC);
};
return (
<>
<Row label="Agent" hint="Commit messages are short: a fast model with low effort is usually enough.">
<Select value={agent} options={agentOptions} onChange={pick} aria-label={tx("Agent")} />
</Row>
<Row label="Model" disabled={!agent}>
<Select
value={model}
options={choiceOptions(tx("The agent's current model"), models?.values ?? [], model)}
onChange={(next) => {
setModel(next);
setEffort(AUTOMATIC);
}}
disabled={!agent}
aria-label={tx("Model")}
/>
</Row>
<Row label="Effort" disabled={!agent}>
<Select
value={effort}
options={choiceOptions(tx("The agent's default"), levels?.values ?? [], effort)}
onChange={setEffort}
disabled={!agent}
aria-label={tx("Effort")}
/>
</Row>
</>
);
}
function AgentInstructionsRow() {
const [value, set] = useSetting<string>("vcs.commit.agentInstructions");
const id = useId();
@@ -643,12 +531,6 @@ export const VCS_PAGES: PageSpec[] = [
{
title: "Commit Message Generation",
options: [
{
kind: "custom",
label: "Agent",
keywords: ["agent", "ai", "model", "effort", "thinking", "reasoning", "generate commit message"],
component: CommitAgentRows,
},
{
kind: "custom",
label: "Instructions for Generate Commit Message with Agent",
+2 -7
View File
@@ -176,15 +176,10 @@ export function trimMiddle(text: string, max: number): string {
const APP_TITLE_MAX = 30;
/**
* The title the program in the tab set (OSC 0/2), per Settings › Terminal: by default only
* while a command runs (at the prompt it is the shell's own), as IDEA does.
*/
/** The title the program in the tab set, while a command runs (at the prompt it is the shell's own). */
function appTitle(tab: TerminalTab, sessions?: Record<string, SessionSnapshot>): string | null {
const s = sessions?.[tab.session];
const when = workflowSettings().terminal.appTitleAsTabName;
if (!s?.appTitle || when === "off") return null;
return when === "always" || s.commandRunning ? s.appTitle : null;
return s?.commandRunning ? s.appTitle : null;
}
/**
-15
View File
@@ -17,8 +17,6 @@ import {
} from "./store";
import type { SessionSnapshot } from "./session";
import { usePlatform } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
import type { Settings } from "@/bindings";
import { buildTheme, mix, parseColor, terminalFont, toHex } from "./theme";
describe("theme", () => {
@@ -478,19 +476,6 @@ describe("terminal tab titles", () => {
expect(tabFullTitle(tab, snap(long))).toBe(long);
});
it("uses the program's title always or never, per Settings › Terminal", () => {
const set = (appTitleAsTabName: string) =>
useProject.setState({ settings: { terminal: { appTitleAsTabName } } as unknown as Settings });
try {
set("always");
expect(tabTitle(tab, snap("claude", false))).toBe("claude");
set("off");
expect(tabTitle(tab, snap("vim notes.md"))).toBe("Local");
} finally {
useProject.setState({ settings: null });
}
});
it("keeps a name the user gave the tab", () => {
const renamed = { ...tab, customName: "Server" };
expect(tabTitle(renamed, snap("top"))).toBe("Server");
+1 -4
View File
@@ -19,7 +19,6 @@ export function ComparisonTree<F>({
getColor,
onOpen,
inlineDiff = true,
openDiff = (diff) => void openVcsDiff(diff),
}: {
tree: FileTreeNode<F>[];
current: F | null;
@@ -33,8 +32,6 @@ export function ComparisonTree<F>({
onOpen?: () => void;
/** Show the selected file's diff beside the tree; off where there is no room (a sidebar). */
inlineDiff?: boolean;
/** With `openOnActivate`: where a double-clicked file's diff opens (default: an editor tab). */
openDiff?: (diff: DiffData) => void;
}) {
const [selected, setSelected] = useState<ReadonlySet<string>>(new Set());
const [expanded, setExpanded] = useState<ReadonlySet<string> | null>(null);
@@ -61,7 +58,7 @@ export function ComparisonTree<F>({
onSelect(entry);
const diff = diffFor(entry);
if (openOnActivate && diff) {
openDiff(diff);
void openVcsDiff(diff);
onOpen?.();
}
}}
+2 -6
View File
@@ -1,12 +1,10 @@
/**
* Push dialog: the files changed by the outgoing commits (the selected commit's, or all of
* them), with the selected file's diff beside the tree. Double-click or Enter opens the diff in
* its own window, as IDEA does, since the dialog is modal and small. A single commit also shows
* its message, author and time.
* them), with the selected file's diff beside the tree. The diff stays inside the dialog,
* which is modal. A single commit also shows its message, author and time.
*/
import { useEffect, useMemo, useState } from "react";
import type { ChangedFile, Commit, RevisionChange } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { Button, IconButton, Spinner, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui";
@@ -96,8 +94,6 @@ export function PushChanges({
}}
diffFor={(c) => c.diff}
inlineDiff={!onSelectFile}
openOnActivate
openDiff={(diff) => void executeAction("vcs.showDiffInNewWindow", diff)}
getColor={(c) => KIND_COLOR[c.kind === "untracked" ? "added" : c.kind]}
ariaLabel="Changed files"
renderDetails={(n) =>
@@ -2,16 +2,7 @@ import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import type { Commit } from "@/bindings";
const { files, combined, executeAction } = vi.hoisted(() => ({
files: vi.fn(),
combined: vi.fn(),
executeAction: vi.fn(async () => true),
}));
vi.mock("@/platform/actions", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/actions")>()),
executeAction,
}));
const { files, combined } = vi.hoisted(() => ({ files: vi.fn(), combined: vi.fn() }));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
@@ -85,18 +76,6 @@ describe("Push dialog changes", () => {
expect(localStorage.getItem("openidea.vcs.push.groupByDirectory")).toBe("false");
});
it("opens a double-clicked file's diff in its own window and keeps the selection's diff in the dialog", async () => {
files.mockResolvedValue({ status: "ok", data: [{ path: "a.txt", oldPath: null, kind: "modified" }] });
const select = vi.fn();
render(<PushChanges repo="/r" commits={[older]} onSelectFile={select} />);
fireEvent.doubleClick(await screen.findByText("a.txt"));
expect(select).toHaveBeenLastCalledWith(expect.objectContaining({ path: "a.txt" }));
expect(executeAction).toHaveBeenCalledWith(
"vcs.showDiffInNewWindow",
expect.objectContaining({ path: expect.stringContaining("a.txt") }),
);
});
it("shows no commit details for several commits", async () => {
combined.mockResolvedValue({ status: "ok", data: [] });
render(<PushChanges repo="/r" commits={[newer, older]} />);
+10 -6
View File
@@ -36,16 +36,20 @@ describe("ideavimrc parsing", () => {
);
});
it("parses set with Vim's =, +=, -= and ^= forms", () => {
it("parses the clipboard list option, including the += append form", () => {
expect(parseVimrc("set clipboard=unnamedplus").commands).toEqual([
{ kind: "set", name: "clipboard", value: "unnamedplus" },
]);
expect(parseVimrc("set clipboard+=unnamed cb^=unnamedplus tw-=10").commands).toEqual([
{ kind: "set", name: "clipboard", value: "unnamed", op: "+=" },
{ kind: "set", name: "cb", value: "unnamedplus", op: "^=" },
{ kind: "set", name: "tw", value: "10", op: "-=" },
expect(parseVimrc("set clipboard+=unnamed").commands).toEqual([
{ kind: "set", name: "clipboard", value: "unnamed", append: true },
]);
// Only list options append; other forms stay unsupported syntax.
expect(parseVimrc("set textwidth+=4").ignored.map((i) => i.reason)).toEqual([
"unsupported option syntax: textwidth+=4",
]);
expect(parseVimrc("set clipboard-=unnamed").ignored.map((i) => i.reason)).toEqual([
"unsupported option syntax: clipboard-=unnamed",
]);
expect(parseVimrc("set ideajoin+=x").ignored.map((i) => i.reason)).toEqual(["option not supported: ideajoin"]);
});
it("parses map variants with modes, noremap and the leader in effect at that line", () => {
+3 -33
View File
@@ -156,28 +156,11 @@ describe("Vim engine", () => {
view.destroy();
});
it("applies +=, -= and ^= to list and number options from the rc file", () => {
it("appends list option values from the rc file", () => {
try {
const problems = applyRcCommands(
parseVimrc("set clipboard+=unnamed\nset cb+=unnamedplus\nset clipboard+=unnamed").commands,
);
const problems = applyRcCommands(parseVimrc("set clipboard+=unnamed\nset clipboard+=unnamedplus").commands);
expect(problems).toEqual([]);
expect(Vim.getOption("clipboard")).toBe("ideaput,autoselect,unnamed,unnamedplus");
applyRcCommands(parseVimrc("set clipboard-=autoselect\nset clipboard^=unnamedplus").commands);
expect(Vim.getOption("clipboard")).toBe("ideaput,unnamed,unnamedplus");
applyRcCommands(parseVimrc("set clipboard^=autoselect").commands);
expect(Vim.getOption("clipboard")).toBe("autoselect,ideaput,unnamed,unnamedplus");
const timeout = Vim.getOption("insertModeEscKeysTimeout");
applyRcCommands(
parseVimrc(
"set insertModeEscKeysTimeout=100\nset insertModeEscKeysTimeout+=50\nset insertModeEscKeysTimeout^=2\nset insertModeEscKeysTimeout-=60",
).commands,
);
expect(Vim.getOption("insertModeEscKeysTimeout")).toBe(240);
expect(applyRcCommands(parseVimrc("set insertModeEscKeysTimeout+=x").commands)).toEqual([
"insertModeEscKeysTimeout: number required: x",
]);
Vim.setOption("insertModeEscKeysTimeout", timeout);
} finally {
Vim.setOption("clipboard", "ideaput,autoselect");
}
@@ -407,7 +390,7 @@ describe("Vim engine", () => {
/** A key's keydown, then the text it types. jsdom reports an Apple vendor, so CodeMirror
* treats it as Safari and drops the keydown within 100ms of `compositionend`. */
const press = (view: EditorView, key: string, text: string) => {
view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));
view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true }));
typeText(view, text);
};
let clock = 0;
@@ -453,19 +436,6 @@ describe("Vim engine", () => {
view.destroy();
});
it("drops the text an input method echoes after a key Vim took outside Insert mode (#4402)", async () => {
const view = makeView();
press(view, "j", "j");
expect(view.state.doc.toString()).toBe("one two\nthree");
expect(view.state.selection.main.head).toBe(8);
press(view, "i", "i");
expect(view.state.doc.toString()).toBe("one two\nthree");
// Keys typed in the new Insert mode stay text, even the same letter.
press(view, "i", "i");
expect(view.state.doc.toString()).toBe("one two\nithree");
view.destroy();
});
it("leaves text input to the usual handlers once a keydown got through or the window passed", async () => {
const view = makeView();
composeKorean(view);
+1 -1
View File
@@ -16,7 +16,7 @@ const CLIPBOARD_DEFAULT = "ideaput,autoselect";
const MIRROR_OPTIONS = new Set(["unnamed", "unnamedplus"]);
// The rc file's `set clipboard=…` lines need the option to exist before they are applied.
Vim.defineOption("clipboard", CLIPBOARD_DEFAULT, "string", ["cb"]);
Vim.defineOption("clipboard", CLIPBOARD_DEFAULT, "string");
/** Whether the user asked for unnamed register writes to reach the system clipboard. */
function unnamedMirrors(): boolean {
+8 -41
View File
@@ -14,7 +14,7 @@ import { showStatusInfo } from "@/workbench/contributions";
import { installClipboardHooks } from "./clipboard";
import { modeAction, modeMovedToIde, movedToIde, VIM_EDITOR_ATTR, VIM_MODE_ATTR, vimModeOf } from "./conflicts";
import { useVimMode, type VimModeState } from "./mode";
import { resolveActionId, type RcCommand, type SetOp } from "./rc";
import { resolveActionId, type RcCommand } from "./rc";
import { useVimSettings } from "./settings";
import { mapFunctionTextObjects } from "./textObjects";
@@ -147,34 +147,13 @@ const imeHandlers = EditorView.domEventHandlers({
},
});
/** The last keydown and whether it arrived outside Insert mode (see `vimKeyEcho`). */
const lastKeydown = new WeakMap<EditorView, { event: KeyboardEvent; at: number; normal: boolean }>();
const KEY_ECHO_WINDOW_MS = 100;
/** A keydown CodeMirror didn't drop reaches Vim the usual way (observers run before Vim's handler). */
/** A keydown CodeMirror didn't drop reaches Vim the usual way (observers run even after Vim's). */
const imeKeydown = EditorView.domEventObservers({
keydown(e, view) {
keydown(_e, view) {
imeEnded.delete(view);
const vimState = getCM(view)?.state.vim;
lastKeydown.set(view, { event: e, at: Date.now(), normal: !!vimState && !vimState.insertMode });
},
});
/**
* Text input echoing a key Vim already took outside Insert mode. Some macOS input methods
* (Doubao in its English mode) still insert a key's character after its keydown was handled
* and prevented, so `j` both moved and typed `j`, and `i` entered Insert mode and typed `i`.
* Any later keydown replaces the record, so a key typed in the new Insert mode stays text.
*/
function vimKeyEcho(view: EditorView, text: string): boolean {
const last = lastKeydown.get(view);
if (!last || view.composing) return false;
lastKeydown.delete(view);
return (
last.normal && last.event.defaultPrevented && last.event.key === text && Date.now() - last.at <= KEY_ECHO_WINDOW_MS
);
}
/**
* The key typed right after a Normal-mode composition. On WebKit (macOS, and WebKitGTK on
* Linux), CodeMirror drops the first keydown within 100ms of `compositionend`, meant for the
@@ -208,7 +187,7 @@ function imeNextKey(view: EditorView, text: string): boolean {
/** Let CodeMirror apply the composing text; it is removed when the IME ends. */
const imeInput = EditorView.inputHandler.of((view, _from, _to, text) => {
if (imeNextKey(view, text) || vimKeyEcho(view, text)) return true;
if (imeNextKey(view, text)) return true;
const composition = imeCompositions.get(view);
if (!composition) return false;
const cm = getCM(view);
@@ -518,26 +497,14 @@ function firstKey(lhs: string): string {
return /^<[^<>]+>|^./.exec(lhs)?.[0] ?? lhs;
}
/**
* The value `set name{op}value` gives an option, as in Vim: numbers add, subtract or multiply;
* comma lists append an item once (`+=`), remove it (`-=`) or put it first (`^=`).
*/
function adjustedOption(name: string, op: SetOp, value: string): string | number {
/** `set clipboard+=unnamed`: the comma list option with `add` appended once. */
function appendedOption(name: string, add: string): string {
const current = Vim.getOption(name);
// A number option (rc values arrive as text, so `set x=100` stores "100").
if (typeof current === "number" || (typeof current === "string" && /^-?\d+$/.test(current))) {
if (!/^-?\d+$/.test(value)) throw new Error(`number required: ${value}`);
const [a, b] = [Number(current), Number(value)];
return op === "+=" ? a + b : op === "-=" ? a - b : a * b;
}
const items = (typeof current === "string" ? current : "")
.split(",")
.map((v) => v.trim())
.filter(Boolean);
const rest = items.filter((v) => v !== value);
if (op === "-=") return rest.join(",");
if (op === "^=") return (items.includes(value) ? items : [value, ...items]).join(",");
return (items.includes(value) ? items : [...items, value]).join(",");
return items.includes(add) ? items.join(",") : [...items, add].join(",");
}
/** Applies rc commands (replacing earlier rc mappings). Returns problems to report. */
@@ -551,7 +518,7 @@ export function applyRcCommands(commands: readonly RcCommand[]): string[] {
for (const c of commands) {
try {
if (c.kind === "set") {
const err = Vim.setOption(c.name, c.op ? adjustedOption(c.name, c.op, String(c.value)) : c.value);
const err = Vim.setOption(c.name, c.append ? appendedOption(c.name, String(c.value)) : c.value);
if (err) problems.push(`set ${c.name}: ${err.message}`);
} else if (c.kind === "map") {
if (c.noremap) Vim.noremap(c.lhs, c.rhs, c.mode as string);
+7 -6
View File
@@ -12,14 +12,12 @@ import { IDEA_ACTIONS } from "@/platform/ideaActions";
export type MapMode = "normal" | "insert" | "visual" | "operatorPending" | undefined;
export type RcCommand =
/** `op` is Vim's `+=` (append to a list, add to a number), `-=` (remove, subtract) or `^=` (prepend, multiply). */
| { kind: "set"; name: string; value: string | boolean; op?: SetOp }
/** `append` marks `set name+=value`, the way a comma list option gains an item. */
| { kind: "set"; name: string; value: string | boolean; append?: boolean }
| { kind: "map"; mode: MapMode; noremap: boolean; lhs: string; rhs: string }
/** A key mapped to one Ex command, e.g. `<Action>(ReformatCode)` → `action ReformatCode`. */
| { kind: "mapEx"; mode: MapMode; lhs: string; ex: string };
export type SetOp = "+=" | "-=" | "^=";
export interface RcIgnored {
/** The sourced file it came from, as written after `source`; absent for the rc file itself. */
file?: string;
@@ -115,8 +113,9 @@ const SUPPORTED_OPTIONS = new Set([
"langmap",
"lmap",
"clipboard",
"cb",
]);
/** Comma list options, the ones Vim's `+=` appends an item to (`set clipboard+=unnamed`). */
const LIST_OPTIONS = new Set(["clipboard"]);
const MAP_FLAGS = /^<(silent|unique|nowait|buffer|expr|script)>$/i;
function leaderKeys(value: string): string {
@@ -197,9 +196,11 @@ export function parseVimrc(text: string, sources?: ReadonlyMap<string, string |
if (!restWords.length) return ignore("set without options");
for (const opt of restWords) {
const eq = /^([a-zA-Z]+)([-+^]?)=(.*)$/.exec(opt);
// Vim only appends to comma list options; `-=` / `^=` are not implemented.
const append = eq?.[2] === "+" && LIST_OPTIONS.has(eq[1]!);
let cmd: RcCommand | null = null;
if (eq) {
cmd = { kind: "set", name: eq[1]!, value: eq[3]!, ...(eq[2] ? { op: `${eq[2]}=` as SetOp } : {}) };
if (!eq[2] || append) cmd = { kind: "set", name: eq[1]!, value: eq[3]!, ...(append ? { append: true } : {}) };
} else if (/^[a-zA-Z]+$/.test(opt)) {
const negated = !SUPPORTED_OPTIONS.has(opt) && opt.startsWith("no") && SUPPORTED_OPTIONS.has(opt.slice(2));
cmd = { kind: "set", name: negated ? opt.slice(2) : opt, value: !negated };
@@ -68,16 +68,6 @@
font-size: var(--fs-small);
font-weight: 600;
}
.groupHeader {
display: flex;
align-items: center;
gap: var(--space-1-5);
padding: 6px 16px 2px;
color: var(--fg);
font-weight: 600;
white-space: nowrap;
--icon-color: var(--fg-muted);
}
.badge {
align-self: flex-start;
margin-top: 1px;
+2 -33
View File
@@ -1,13 +1,12 @@
import { describe, expect, it, vi } from "vitest";
import { createRef } from "react";
import { render, screen, within } from "@testing-library/react";
import type { OpenProject, RecentProject, RecentProjectGroup } from "@/platform/ipc";
import type { OpenProject, RecentProject } from "@/platform/ipc";
import { remoteLocation } from "@/platform/remote";
const wsl = { kind: "wsl", distro: "Ubuntu-24.04" } as const;
let open: OpenProject[] = [];
let recent: RecentProject[] = [];
let groups: RecentProjectGroup[] = [];
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
@@ -17,7 +16,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
commands: {
...real.commands,
recentProjects: async () => recent,
recentProjectGroups: async () => groups,
recentProjectGroups: async () => [],
windowOpenProjects: async () => ({ status: "ok", data: open }),
},
};
@@ -57,34 +56,4 @@ describe("ProjectPopup", () => {
expect(text.indexOf("Recent Projects")).toBeLessThan(text.indexOf("other"));
expect(within(list).getAllByText("FastAPIProject")).toHaveLength(1);
});
it("lists recent projects under the Welcome screen's groups, collapsed or not, then the ungrouped ones", async () => {
open = [{ name: "current", root: "/w/current", current: true, remote: null }];
const project = (name: string, at: number): RecentProject => ({
path: `/w/${name}`,
name,
openedAtMs: at,
branch: null,
});
recent = [project("current", 9), project("example-web", 5), project("loose", 4), project("example-api", 3)];
groups = [
{ name: "Frontend", paths: ["/w/example-web"], expanded: true },
{ name: "Backend", paths: ["/w/example-api", "/w/current"], expanded: false },
];
const anchor = createRef<HTMLButtonElement>();
render(
<>
<button ref={anchor} />
<ProjectPopup anchor={anchor} onClose={() => {}} />
</>,
);
await screen.findByText("Frontend");
const text = screen.getByRole("listbox").textContent ?? "";
const order = ["Recent Projects", "Frontend", "example-web", "Backend", "example-api", "loose"];
expect(order.map((t) => text.indexOf(t))).toEqual([...order.map((t) => text.indexOf(t))].sort((a, b) => a - b));
expect(order.every((t) => text.includes(t))).toBe(true);
// The open project stays under Open Projects only.
expect(within(screen.getByRole("listbox")).getAllByText("current")).toHaveLength(1);
expect(screen.getAllByRole("option").map((o) => o.textContent)).not.toContain("Frontend");
});
});
+6 -34
View File
@@ -5,14 +5,14 @@ import { call, commands, isTauri, type OpenProject, type RecentProject } from "@
import { HighlightedText, Icon, Popup, showContextMenu, type IconName, T } from "@/ui";
import type { ProjectPopupProps } from "@/workbench/contributions";
import { askRemoveRecent, ProjectBadge, recentMenu, unavailableTitle } from "./RecentList";
import { filterRecent, loadRecent, openRecent, recentRows, useRecent, type RecentMatch } from "./recent";
import { filterRecent, loadRecent, openRecent, useRecent, type RecentMatch } from "./recent";
import styles from "./ProjectPopup.module.css";
import { tx } from "@/platform/i18n";
import { parseRemoteLocation, remoteLocation } from "@/platform/remote";
type Entry =
| { kind: "action"; id: string; label: string; icon: IconName }
| { kind: "project"; open: boolean; m: RecentMatch; group?: string | null };
| { kind: "project"; open: boolean; m: RecentMatch };
const ACTIONS: { id: string; label: string; icon: IconName }[] = [
{ id: "file.newProject", label: "New Project…", icon: "plus" },
@@ -36,14 +36,10 @@ function useOpenProjects(): OpenProject[] {
return open;
}
/**
* The title bar project widget's popup, after IDEA's ProjectWidget: actions, open projects, recent
* projects (under the Welcome screen's project groups, then the ungrouped ones); type to filter.
*/
/** The title bar project widget's popup, after IDEA's ProjectWidget: actions, open projects, recent projects; type to filter. */
export function ProjectPopup({ anchor, onClose }: ProjectPopupProps) {
const actions = useActions((s) => s.actions);
const recent = useRecent((s) => s.projects);
const groups = useRecent((s) => s.groups);
const home = useRecent((s) => s.home);
const openProjects = useOpenProjects();
const [query, setQuery] = useState("");
@@ -64,17 +60,14 @@ export function ProjectPopup({ anchor, onClose }: ProjectPopupProps) {
open: true,
m,
}));
// Every group lists its projects here, collapsed on the Welcome screen or not; a search is flat.
const expanded = groups.map((g) => ({ ...g, expanded: true }));
const rest = recentRows(
const rest = filterRecent(
recent.filter((r) => !openPaths.has(r.path)),
expanded,
query,
home,
).flatMap((r) => (r.kind === "project" ? [{ kind: "project" as const, open: false, m: r.m, group: r.group }] : []));
).map((m) => ({ kind: "project" as const, open: false, m }));
const acts = query ? [] : ACTIONS.filter((a) => actions.has(a.id)).map((a) => ({ kind: "action" as const, ...a }));
return [...acts, ...open, ...rest];
}, [actions, recent, groups, home, openProjects, query]);
}, [actions, recent, home, openProjects, query]);
const current = Math.min(active, entries.length - 1);
useEffect(() => {
@@ -157,7 +150,6 @@ export function ProjectPopup({ anchor, onClose }: ProjectPopupProps) {
<T>Recent Projects</T>
</Header>
)}
{e.kind === "project" && !e.open && <GroupBoundary entry={e} previous={entries[i - 1]} />}
<div
role="option"
aria-selected={i === current}
@@ -202,26 +194,6 @@ function Header({ first, children }: { first: boolean; children: ReactNode }) {
);
}
/** A project group's name above its first project; a separator where the ungrouped projects start. */
function GroupBoundary({
entry,
previous,
}: {
entry: Extract<Entry, { kind: "project" }>;
previous: Entry | undefined;
}) {
const before = previous?.kind === "project" && !previous.open ? (previous.group ?? null) : null;
const group = entry.group ?? null;
if (group === before) return null;
if (group === null) return <div className={styles.separator} role="separator" />;
return (
<div className={styles.groupHeader}>
<Icon name="folder" size={14} />
<span className={styles.label}>{group}</span>
</div>
);
}
function ProjectRow({ m, active }: { m: RecentMatch; active: boolean }) {
return (
<>
-1
View File
@@ -56,7 +56,6 @@ export const CLIENT_SETTINGS_KEYS = [
"editor.general.richTextCopy",
"editor.codeStyle.visualGuides",
"terminal.tabName",
"terminal.appTitleAsTabName",
"terminal.audibleBell",
"terminal.closeOnExit",
"terminal.mouseReporting",
-4
View File
@@ -234,8 +234,6 @@ export interface LanguagesValid {
delegateBuild: boolean;
/** Download dependencies' `-sources.jar` when jdtls imports the project. */
downloadSources: boolean;
/** Always update snapshots: `-U` on Maven runs, `java.maven.updateSnapshots` for jdtls. */
updateSnapshots: boolean;
};
};
/** Preview font size in px; `null` follows the editor font size. */
@@ -326,7 +324,6 @@ export const DEFAULT_LANGUAGES: LanguagesValid = {
activeProfiles: "",
delegateBuild: false,
downloadSources: false,
updateSnapshots: false,
},
},
markdown: { previewFontSize: null },
@@ -507,7 +504,6 @@ export function validateLanguages(raw: unknown): LanguagesValid {
activeProfiles: text(maven.activeProfiles, d.java.maven.activeProfiles),
delegateBuild: bool(maven.delegateBuild, d.java.maven.delegateBuild),
downloadSources: bool(maven.downloadSources, d.java.maven.downloadSources),
updateSnapshots: bool(maven.updateSnapshots, d.java.maven.updateSnapshots),
},
},
markdown: { previewFontSize: previewSize(markdown.previewFontSize) },
+1 -21
View File
@@ -2632,25 +2632,5 @@
"Updated {n} branch": "Updated {n} branch",
"Updated {n} branches": "Updated {n} branches",
"No branches were updated": "No branches were updated",
"Selected branches are up-to-date": "Selected branches are up-to-date",
"Use application title as tab name": "Use application title as tab name",
"When command is running": "When command is running",
"Horizontal Scrolling": "Horizontal Scrolling",
"Export Test Results…": "Export Test Results…",
"Save the test results as an HTML report or IDEA's XML": "Save the test results as an HTML report or IDEA's XML",
"Export Test Results": "Export Test Results",
"Export format:": "Export format:",
"HTML": "HTML",
"XML": "XML",
"Open exported file in browser": "Open exported file in browser",
"File '{name}' already exists. Do you want to overwrite it?": "File '{name}' already exists. Do you want to overwrite it?",
"{path} is a directory": "{path} is a directory",
"Cannot export test results": "Cannot export test results",
"Test results exported": "Test results exported",
"Always update snapshots": "Always update snapshots",
"Checks remote repositories for newer SNAPSHOT dependencies on every sync, build and run (-U).": "Checks remote repositories for newer SNAPSHOT dependencies on every sync, build and run (-U).",
"Automatic (the agent of the latest task)": "Automatic (the agent of the latest task)",
"The agent's current model": "The agent's current model",
"The agent's default": "The agent's default",
"Commit messages are short: a fast model with low effort is usually enough.": "Commit messages are short: a fast model with low effort is usually enough."
"Selected branches are up-to-date": "Selected branches are up-to-date"
}
+1 -21
View File
@@ -9011,25 +9011,5 @@
"Updated {n} branch": "已更新 {n} 个分支",
"Updated {n} branches": "已更新 {n} 个分支",
"No branches were updated": "没有分支被更新",
"Selected branches are up-to-date": "所选分支都是最新的",
"Use application title as tab name": "使用应用标题作为标签页名称",
"When command is running": "命令运行时",
"Horizontal Scrolling": "横向滚动",
"Export Test Results…": "导出测试结果…",
"Save the test results as an HTML report or IDEA's XML": "将测试结果保存为 HTML 报告或 IDEA 的 XML",
"Export Test Results": "导出测试结果",
"Export format:": "导出格式:",
"HTML": "HTML",
"XML": "XML",
"Open exported file in browser": "在浏览器中打开导出的文件",
"File '{name}' already exists. Do you want to overwrite it?": "文件 '{name}' 已存在。是否覆盖?",
"{path} is a directory": "{path} 是目录",
"Cannot export test results": "无法导出测试结果",
"Test results exported": "测试结果已导出",
"Always update snapshots": "始终更新快照",
"Checks remote repositories for newer SNAPSHOT dependencies on every sync, build and run (-U).": "每次同步、构建和运行时都检查远程仓库中是否有更新的 SNAPSHOT 依赖(-U)。",
"Automatic (the agent of the latest task)": "自动(最近任务的智能体)",
"The agent's current model": "智能体当前的模型",
"The agent's default": "智能体的默认值",
"Commit messages are short: a fast model with low effort is usually enough.": "提交信息很短,通常用快速模型配低推理强度就够了。"
"Selected branches are up-to-date": "所选分支都是最新的"
}
-17
View File
@@ -62,12 +62,6 @@ export interface CommitSettingsValid {
doubleClickOpensDiff: boolean | null;
/** Team conventions for Generate Commit Message with Agent, added to its prompt. */
agentInstructions: string;
/** The agent Generate Commit Message with Agent uses; empty follows the latest task's agent. */
agent: string;
/** That agent's model for commit messages; empty keeps the model the agent would use. */
agentModel: string;
/** That model's thinking level for commit messages; empty keeps the agent's. */
agentEffort: string;
}
export interface VcsSettingsValid {
@@ -146,8 +140,6 @@ export interface ExternalDiffValid {
}
export type TerminalMaxFps = "unlimited" | "60" | "30" | "15" | "10";
/** When a title the program sets (OSC 0/2) names the terminal tab, as IDEA's option. */
export type TerminalAppTitle = "running" | "always" | "off";
export const TERMINAL_MAX_FPS_OPTIONS: readonly { value: TerminalMaxFps; label: string }[] = [
{ value: "unlimited", label: "Unlimited" },
@@ -162,7 +154,6 @@ export interface TerminalSettingsValid {
env: Record<string, string>;
shellPath: string;
tabName: string;
appTitleAsTabName: TerminalAppTitle;
audibleBell: boolean;
closeOnExit: boolean;
mouseReporting: boolean;
@@ -306,9 +297,6 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
disabledPluginChecks: [],
doubleClickOpensDiff: null,
agentInstructions: "",
agent: "",
agentModel: "",
agentEffort: "",
},
confirmation: {
onCreate: "ask",
@@ -373,7 +361,6 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
env: {},
shellPath: "",
tabName: "Local",
appTitleAsTabName: "running",
audibleBell: true,
closeOnExit: true,
mouseReporting: true,
@@ -474,9 +461,6 @@ export function validateVcs(raw: unknown): VcsSettingsValid {
disabledPluginChecks: strings(c.disabledPluginChecks, d.commit.disabledPluginChecks),
doubleClickOpensDiff: tri(c.doubleClickOpensDiff),
agentInstructions: text(c.agentInstructions, d.commit.agentInstructions),
agent: text(c.agent, d.commit.agent),
agentModel: text(c.agentModel, d.commit.agentModel),
agentEffort: text(c.agentEffort, d.commit.agentEffort),
},
confirmation: {
onCreate: oneOf(conf.onCreate, confirm, d.confirmation.onCreate),
@@ -586,7 +570,6 @@ export function validateTerminal(raw: unknown): TerminalSettingsValid {
env,
shellPath: text(v.shellPath, d.shellPath).trim(),
tabName: nonEmpty(v.tabName, d.tabName),
appTitleAsTabName: oneOf(v.appTitleAsTabName, ["running", "always", "off"] as const, d.appTitleAsTabName),
audibleBell: bool(v.audibleBell, d.audibleBell),
closeOnExit: bool(v.closeOnExit, d.closeOnExit),
mouseReporting: bool(v.mouseReporting, d.mouseReporting),