Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai f1ca1fc7a2 feat(vcs): choose the agent, model and effort for Generate Commit Message
Settings › Version Control › Commit › Commit Message Generation gets Agent,
Model and Effort dropdowns (vcs.commit.agent / agentModel / agentEffort,
global or per project). Automatic keeps the current behaviour: the agent of
the latest task on its model. A chosen agent runs on the chosen model and
thinking level when it offers them, and the chat's model is no longer
involved. The lists come from the agent's model catalog.

Closes #4467
2026-11-19 19:15:22 +08:00
l0ng-ai 0f355c286d fix(format): keep the caret when a language server replaces the whole file (#4497)
Vue's language server answers Reformat Code with one edit replacing the whole document, which moved the caret and the view to the top of the file. Multi-line LSP formatting edits are now reduced to one edit per changed region via Document::diff, which covers every server that formats this way.
2026-11-19 19:05:18 +08:00
l0ng-ai a0a51a63cb feat(vcs): open a push dialog file's diff in its own window (#4490)
Double-click or Enter on a file in the push dialog opens its diff in a separate diff window (Show Diff in New Window), as IDEA's push dialog does; closing it returns to the dialog. Before, the diff was only shown in a split inside the small modal dialog. Selecting a file still shows the diff in the dialog.
2026-11-19 18:28:32 +08:00
l0ng-ai b44393a989 feat(welcome): show project groups in the title bar's recent projects (#4485)
The title bar project popup's Recent Projects section now lists each Welcome-screen project group's name above its projects (collapsed groups included), then the ungrouped projects after a separator; a search stays a flat list. Before, recent projects were always flat, so similarly named projects were easy to mix up.
2026-11-19 18:23:12 +08:00
l0ng-ai eda632866a feat(maven): Always update snapshots setting (#4484)
Settings › Build Tools › Maven gets Always update snapshots (off by default, Global or This project). On, Maven runs, builds, goals and sync get -U and jdtls imports with java.maven.updateSnapshots, so newer SNAPSHOT dependencies are picked up from remote repositories. A configuration's own -U/--update-snapshots is kept; turning the setting off removes the -U it added.
2026-11-19 18:20:15 +08:00
HEOJUNFO 3eaaa71ae1 fix(http-client): keep a > inside an attribute value within its tag (#4470)
The HTTP Client's formatted XML/HTML response cut a tag at the first `>` even inside a quoted attribute value, splitting the value across lines, over-indenting what followed and, in HTML, dropping the space after the `>`. The tag pattern now skips "…" and '…' values; a tag with an unclosed quote still ends at the first `>`.

Co-authored-by: HEOJUNFO <[email protected]>
2026-11-19 17:58:48 +08:00
Mansur Akhmadiтаmansur-akhmadi 77503e5fee feat(run): Export Test Results to HTML or XML from the test results toolbar (#4413)
The test results toolbar and Find Action get Export Test Results…: a dialog with HTML or XML format, the output file (default "<working directory>/Test Results - <configuration>.html") and an option to open the HTML report in the browser. HTML is a self-contained report (summary, suites, per-test status, duration, output and location, no scripts); XML uses the <testrun> format with count, suite, test, output and expected/actual diff. An existing file is replaced only after confirmation. Both entry points are disabled while tests run and when there are no results.

Closes #4412

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-19 17:57:29 +08:00
l0ng-ai 8edab7b8e6 fix(vim): drop text an input method echoes after a key Vim handled (#4479)
Some macOS input methods (Doubao in its English mode) still insert a key's character after Vim handled and prevented its keydown, so Normal-mode j/k moved and typed, and i/a entered Insert mode and typed. Text input equal to the last keydown is dropped when Vim took that key outside Insert mode within 100 ms; any later keydown clears the record, so keys typed in the new Insert mode stay text.
2026-11-19 17:56:25 +08:00
l0ng-ai f8474fc2a2 feat(project-view): option to turn off horizontal scrolling (#4478)
The Project view's options menu gets Horizontal Scrolling under Appearance (on by default, as before). Turned off, long rows are clipped with an ellipsis instead of the whole tree scrolling sideways and cutting names on the left.
2026-11-19 17:56:15 +08:00
l0ng-ai 0558c1127c feat(terminal): option to use the application title as the tab name always (#4477)
Settings › Tools › Terminal gets "Use application title as tab name" (When command is running, the default; Always; Never). The title a program sets via OSC 0/2 named the tab only while a command ran, so a CLI agent's own title did not show when shell integration could not tell a command was running.
2026-11-19 17:55:24 +08:00
47 змінених файлів з 1553 додано та 69 видалено

No files matched your search

+3
Переглянути файл
@@ -1535,6 +1535,9 @@ 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
Переглянути файл
@@ -170,6 +170,12 @@ 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 {
@@ -192,6 +198,9 @@ 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(),
}
}
}
@@ -448,6 +457,9 @@ 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,
@@ -483,6 +495,7 @@ 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,
+47 -1
Переглянути файл
@@ -119,6 +119,29 @@ 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,
@@ -292,7 +315,11 @@ async fn provider_edits(
if options.on_save && !settings.editor.format_on_save {
return Ok(None);
}
return project.lsp.format(doc, range, options).await.map(Some);
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()));
};
let tool_settings = settings.languages.formatter(selected);
if options.on_save && !tool_settings.run_on_save {
@@ -523,6 +550,25 @@ 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");
+16 -6
Переглянути файл
@@ -537,18 +537,21 @@ 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 → jdtls
/// `java.maven.downloadSources`.
/// Settings › Build Tools › Maven › Automatically download sources and Always update
/// snapshots → jdtls `java.maven.downloadSources` / `java.maven.updateSnapshots`.
pub fn configure_maven_sources(cfg: &mut LanguageServerConfig, s: &Settings) {
if cfg.name != "jdtls" {
return;
}
let download = s.languages.java.maven.download_sources;
merge(cfg.settings.get_or_insert_with(|| json!({})), json!({"java": {"maven": {"downloadSources": download}}}));
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}}}),
);
}
/// Maven options from settings, placed before the goals: `-s <settings.xml>`,
/// `-t <toolchains.xml>`, `-Dmaven.repo.local=<dir>`, `-T <count>` and `-P <profiles>`.
/// `-t <toolchains.xml>`, `-Dmaven.repo.local=<dir>`, `-T <count>`, `-P <profiles>` and `-U`.
pub fn maven_options(root: &Path, s: &Settings) -> Vec<String> {
let m = &s.languages.java.maven;
let mut out = Vec::new();
@@ -567,6 +570,9 @@ 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
}
@@ -1647,6 +1653,9 @@ 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")
}
@@ -2466,8 +2475,9 @@ 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"]["downloadSources"], json!(true));
assert_eq!(cfg.settings.unwrap()["java"]["maven"], json!({"downloadSources": true, "updateSnapshots": true}));
let mut other = custom_server("kotlin", &LanguageServerSettings::default());
configure_maven_sources(&mut other, &settings);
+20
Переглянути файл
@@ -887,6 +887,26 @@ 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();
+3
Переглянути файл
@@ -847,6 +847,9 @@ mod tests {
"disabledPluginChecks": [],
"doubleClickOpensDiff": null,
"agentInstructions": "",
"agent": "",
"agentModel": "",
"agentEffort": "",
})
);
}
+16
Переглянути файл
@@ -3745,6 +3745,12 @@ 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 = {
@@ -8378,6 +8384,11 @@ 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. */
@@ -11613,6 +11624,11 @@ 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,
+67
Переглянути файл
@@ -274,6 +274,73 @@ 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 });
+62 -9
Переглянути файл
@@ -3,7 +3,14 @@
* 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, AgentProvider, AgentTask } from "@/bindings";
import type {
AgentConfigChoice,
AgentConfigOption,
AgentEntry,
AgentModelCatalog,
AgentProvider,
AgentTask,
} from "@/bindings";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
@@ -139,28 +146,74 @@ 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.
* 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.
*/
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" && installed.some((p) => p.id === t.provider))
.filter((t) => t.status !== "archived" && candidates.some((p) => p.id === t.provider))
.sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0))[0];
if (latest) return { provider: latest.provider, config: choicesFor(latest.config) };
const provider = installed.find((p) => p.id === draft.provider) ?? installed[0];
const provider = latest
? installed.find((p) => p.id === latest.provider)!
: (chosen ?? 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: choicesFor(provider.id === draft.provider ? draftConfig(provider, draft) : provider.config),
config: [...preferredModel(options, provider, preference, catalogs?.get(provider.id)), ...askingChoices(options)],
};
}
/** 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) => {
@@ -243,8 +296,9 @@ async function generate(): Promise<void> {
notify({ level: "info", title: "No changes to describe", body: "Include changes in the commit first." });
return;
}
const { tasks, providers, draft } = useAgents.getState();
const agent = pickAgent(tasks.values(), providers, draft);
const { commit } = workflowSettings().vcs;
const { tasks, providers, draft, modelCatalogs } = useAgents.getState();
const agent = pickAgent(tasks.values(), providers, draft, commit, modelCatalogs);
if (!agent) {
notify({
level: "warning",
@@ -255,7 +309,6 @@ async function generate(): Promise<void> {
return;
}
const { commit } = workflowSettings().vcs;
const subjects = await recentSubjects(changes.roots[0]);
const prompt = commitMessagePrompt(
changes.patch,
+2 -1
Переглянути файл
@@ -55,7 +55,8 @@ 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[] = [];
const re = /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<[^>]+>|[^<]+|</g;
// A quoted attribute value may hold `>`; an unclosed quote falls back to the first `>`.
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();
+11
Переглянути файл
@@ -69,6 +69,17 @@ 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");
+2 -1
Переглянути файл
@@ -44,6 +44,7 @@ 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"],
@@ -54,7 +55,7 @@ export const OPTION_LABELS: Array<[ToggleOption, string]> = [
];
/** The first entries of OPTION_LABELS are Appearance options, the rest Behavior. */
const APPEARANCE_OPTIONS = 6;
const APPEARANCE_OPTIONS = 7;
/** Header controls of the Project tool window (IDEA: Locate, Expand/Collapse All). */
export function ProjectHeaderActions() {
+1 -1
Переглянути файл
@@ -907,7 +907,7 @@ export function ProjectView() {
</div>
)}
<Tree<ProjectNode>
horizontalScroll
horizontalScroll={options.horizontalScroll}
aria-label="Project"
focusContext="projectViewFocus"
handleRef={setTreeHandle}
+3
Переглянути файл
@@ -63,6 +63,8 @@ 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 = {
@@ -75,6 +77,7 @@ export const DEFAULT_VIEW_OPTIONS: ViewOptions = {
previewTab: false,
showMembers: false,
showRootPaths: true,
horizontalScroll: true,
};
function storedOptions(): ViewOptions {
+201
Переглянути файл
@@ -0,0 +1,201 @@
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");
});
});
+202
Переглянути файл
@@ -0,0 +1,202 @@
/**
* 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
Переглянути файл
@@ -953,6 +953,17 @@
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 {
+3 -2
Переглянути файл
@@ -45,8 +45,8 @@ import {
pinSession,
} from "./store";
import { rerunFailedConfigs } from "./testing/rerun";
import { nodeOutput } from "./testing";
import { TestTreeView, formatDuration } from "./TestTreeView";
import { formatDuration, nodeOutput } from "./testing";
import { TestTreeView } from "./TestTreeView";
import { StackTracePanel, useStackTraces, type StackTraceTab } from "./stackTrace";
import { closeRunTab, runTabMenu } from "./runTabs";
import { showApplicationUpdate, useApplicationUpdates } from "./applicationUpdate";
@@ -280,6 +280,7 @@ export function SessionPanel({
version={version}
cwd={cwd}
running={running}
name={session.config.name}
selected={selectedTest}
onSelect={setSelectedTest}
canRunTests={(ids) => canRunSelectedTests(session.id, ids)}
+46
Переглянути файл
@@ -286,3 +286,49 @@ 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();
});
});
+22 -24
Переглянути файл
@@ -14,9 +14,10 @@ import {
} from "@/ui";
import { useOccurrenceNavigator } from "@/workbench/contributions";
import { openTarget } from "./navigate";
import { nodeStatus, type TestNode, type TestResults, type TestStatus } from "./testing";
import { formatDuration, nodeDuration, 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";
@@ -59,28 +60,6 @@ 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":
@@ -134,6 +113,8 @@ 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>;
@@ -146,6 +127,7 @@ export function TestTreeView({
selected,
onSelect,
running,
name = "Tests",
onRunTests,
canRunTests,
}: TestTreeViewProps) {
@@ -158,6 +140,7 @@ 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(
@@ -240,13 +223,17 @@ 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);
@@ -317,7 +304,18 @@ 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}
@@ -342,7 +340,7 @@ export function TestTreeView({
onContextMenu={contextMenu}
renderNode={(n) => {
const s = nodeStatus(n);
const d = totalDuration(n);
const d = nodeDuration(n);
return (
<span className={styles.testRow}>
<StatusIcon status={s} />
+11
Переглянути файл
@@ -748,6 +748,17 @@ 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",
+8 -2
Переглянути файл
@@ -1,8 +1,14 @@
/** 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 act on it. */
export const testTree: { expandAll: (() => void) | null; collapseAll: (() => void) | null } = {
/** 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;
} = {
expandAll: null,
collapseAll: null,
exportResults: null,
};
+152
Переглянути файл
@@ -0,0 +1,152 @@
// @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
Переглянути файл
@@ -0,0 +1,231 @@
/**
* 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
Переглянути файл
@@ -12,8 +12,8 @@ import { zigParser } from "./zig";
import type { TestEvent, TestOutputParser } from "./types";
export type { TestEvent, TestOutputParser, TestStatus } from "./types";
export { parseDuration } from "./types";
export { TestResults, nodeOutput, nodeStatus, type TestNode } from "./results";
export { formatDuration, parseDuration } from "./types";
export { TestResults, nodeDuration, nodeOutput, nodeStatus, type TestNode } from "./results";
export {
cargoParser,
goParser,
+15
Переглянути файл
@@ -19,6 +19,21 @@ 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
Переглянути файл
@@ -43,6 +43,15 @@ 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.
+2
Переглянути файл
@@ -65,6 +65,7 @@ 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("");
@@ -77,6 +78,7 @@ 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");
});
+7
Переглянути файл
@@ -564,6 +564,7 @@ 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();
@@ -582,6 +583,12 @@ 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"
+3
Переглянути файл
@@ -215,6 +215,9 @@ export const EXECUTION_PAGES: PageSpec[] = [
"threads",
"-T",
"parallel",
"Always update snapshots",
"SNAPSHOT",
"-U",
],
component: MavenPage,
},
+11
Переглянути файл
@@ -33,6 +33,11 @@ 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" },
@@ -601,6 +606,12 @@ 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
Переглянути файл
@@ -14,6 +14,7 @@ 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";
@@ -378,6 +379,117 @@ 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();
@@ -531,6 +643,12 @@ 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",
+7 -2
Переглянути файл
@@ -176,10 +176,15 @@ export function trimMiddle(text: string, max: number): string {
const APP_TITLE_MAX = 30;
/** The title the program in the tab set, while a command runs (at the prompt it is the shell's own). */
/**
* 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.
*/
function appTitle(tab: TerminalTab, sessions?: Record<string, SessionSnapshot>): string | null {
const s = sessions?.[tab.session];
return s?.commandRunning ? s.appTitle : null;
const when = workflowSettings().terminal.appTitleAsTabName;
if (!s?.appTitle || when === "off") return null;
return when === "always" || s.commandRunning ? s.appTitle : null;
}
/**
+15
Переглянути файл
@@ -17,6 +17,8 @@ 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", () => {
@@ -476,6 +478,19 @@ 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");
+4 -1
Переглянути файл
@@ -19,6 +19,7 @@ export function ComparisonTree<F>({
getColor,
onOpen,
inlineDiff = true,
openDiff = (diff) => void openVcsDiff(diff),
}: {
tree: FileTreeNode<F>[];
current: F | null;
@@ -32,6 +33,8 @@ 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);
@@ -58,7 +61,7 @@ export function ComparisonTree<F>({
onSelect(entry);
const diff = diffFor(entry);
if (openOnActivate && diff) {
void openVcsDiff(diff);
openDiff(diff);
onOpen?.();
}
}}
+6 -2
Переглянути файл
@@ -1,10 +1,12 @@
/**
* 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. The diff stays inside the dialog,
* which is modal. A single commit also shows its message, author and time.
* 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.
*/
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";
@@ -94,6 +96,8 @@ 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) =>
+22 -1
Переглянути файл
@@ -2,7 +2,16 @@ import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import type { Commit } from "@/bindings";
const { files, combined } = vi.hoisted(() => ({ files: vi.fn(), combined: vi.fn() }));
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,
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
@@ -76,6 +85,18 @@ 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]} />);
+14 -1
Переглянути файл
@@ -407,7 +407,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 }));
view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));
typeText(view, text);
};
let clock = 0;
@@ -453,6 +453,19 @@ 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);
+24 -3
Переглянути файл
@@ -147,13 +147,34 @@ const imeHandlers = EditorView.domEventHandlers({
},
});
/** A keydown CodeMirror didn't drop reaches Vim the usual way (observers run even after Vim's). */
/** 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). */
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
@@ -187,7 +208,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)) return true;
if (imeNextKey(view, text) || vimKeyEcho(view, text)) return true;
const composition = imeCompositions.get(view);
if (!composition) return false;
const cm = getCM(view);
+10
Переглянути файл
@@ -68,6 +68,16 @@
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;
+33 -2
Переглянути файл
@@ -1,12 +1,13 @@
import { describe, expect, it, vi } from "vitest";
import { createRef } from "react";
import { render, screen, within } from "@testing-library/react";
import type { OpenProject, RecentProject } from "@/platform/ipc";
import type { OpenProject, RecentProject, RecentProjectGroup } 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")>();
@@ -16,7 +17,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
commands: {
...real.commands,
recentProjects: async () => recent,
recentProjectGroups: async () => [],
recentProjectGroups: async () => groups,
windowOpenProjects: async () => ({ status: "ok", data: open }),
},
};
@@ -56,4 +57,34 @@ 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");
});
});
+34 -6
Переглянути файл
@@ -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, useRecent, type RecentMatch } from "./recent";
import { filterRecent, loadRecent, openRecent, recentRows, 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 };
| { kind: "project"; open: boolean; m: RecentMatch; group?: string | null };
const ACTIONS: { id: string; label: string; icon: IconName }[] = [
{ id: "file.newProject", label: "New Project…", icon: "plus" },
@@ -36,10 +36,14 @@ function useOpenProjects(): OpenProject[] {
return open;
}
/** The title bar project widget's popup, after IDEA's ProjectWidget: actions, open projects, recent projects; type to filter. */
/**
* 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.
*/
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("");
@@ -60,14 +64,17 @@ export function ProjectPopup({ anchor, onClose }: ProjectPopupProps) {
open: true,
m,
}));
const rest = filterRecent(
// 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(
recent.filter((r) => !openPaths.has(r.path)),
expanded,
query,
home,
).map((m) => ({ kind: "project" as const, open: false, m }));
).flatMap((r) => (r.kind === "project" ? [{ kind: "project" as const, open: false, m: r.m, group: r.group }] : []));
const acts = query ? [] : ACTIONS.filter((a) => actions.has(a.id)).map((a) => ({ kind: "action" as const, ...a }));
return [...acts, ...open, ...rest];
}, [actions, recent, home, openProjects, query]);
}, [actions, recent, groups, home, openProjects, query]);
const current = Math.min(active, entries.length - 1);
useEffect(() => {
@@ -150,6 +157,7 @@ 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}
@@ -194,6 +202,26 @@ 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
Переглянути файл
@@ -56,6 +56,7 @@ export const CLIENT_SETTINGS_KEYS = [
"editor.general.richTextCopy",
"editor.codeStyle.visualGuides",
"terminal.tabName",
"terminal.appTitleAsTabName",
"terminal.audibleBell",
"terminal.closeOnExit",
"terminal.mouseReporting",
+4
Переглянути файл
@@ -234,6 +234,8 @@ 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. */
@@ -324,6 +326,7 @@ export const DEFAULT_LANGUAGES: LanguagesValid = {
activeProfiles: "",
delegateBuild: false,
downloadSources: false,
updateSnapshots: false,
},
},
markdown: { previewFontSize: null },
@@ -504,6 +507,7 @@ 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) },
+21 -1
Переглянути файл
@@ -2632,5 +2632,25 @@
"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"
"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."
}
+21 -1
Переглянути файл
@@ -9011,5 +9011,25 @@
"Updated {n} branch": "已更新 {n} 个分支",
"Updated {n} branches": "已更新 {n} 个分支",
"No branches were updated": "没有分支被更新",
"Selected branches are up-to-date": "所选分支都是最新的"
"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.": "提交信息很短,通常用快速模型配低推理强度就够了。"
}
+17
Переглянути файл
@@ -62,6 +62,12 @@ 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 {
@@ -140,6 +146,8 @@ 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" },
@@ -154,6 +162,7 @@ export interface TerminalSettingsValid {
env: Record<string, string>;
shellPath: string;
tabName: string;
appTitleAsTabName: TerminalAppTitle;
audibleBell: boolean;
closeOnExit: boolean;
mouseReporting: boolean;
@@ -297,6 +306,9 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
disabledPluginChecks: [],
doubleClickOpensDiff: null,
agentInstructions: "",
agent: "",
agentModel: "",
agentEffort: "",
},
confirmation: {
onCreate: "ask",
@@ -361,6 +373,7 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
env: {},
shellPath: "",
tabName: "Local",
appTitleAsTabName: "running",
audibleBell: true,
closeOnExit: true,
mouseReporting: true,
@@ -461,6 +474,9 @@ 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),
@@ -570,6 +586,7 @@ 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),