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

...
Автор 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
23 змінених файлів з 507 додано та 30 видалено

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 {
+9
Переглянути файл
@@ -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(),
}
}
}
+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": "",
})
);
}
+11
Переглянути файл
@@ -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. */
+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
Переглянути файл
@@ -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,
},
+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",
+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]} />);
+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 (
<>
+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) },
+7 -1
Переглянути файл
@@ -2646,5 +2646,11 @@
"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"
"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."
}
+7 -1
Переглянути файл
@@ -9025,5 +9025,11 @@
"File '{name}' already exists. Do you want to overwrite it?": "文件 '{name}' 已存在。是否覆盖?",
"{path} is a directory": "{path} 是目录",
"Cannot export test results": "无法导出测试结果",
"Test results exported": "测试结果已导出"
"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.": "提交信息很短,通常用快速模型配低推理强度就够了。"
}
+12
Переглянути файл
@@ -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 {
@@ -300,6 +306,9 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
disabledPluginChecks: [],
doubleClickOpensDiff: null,
agentInstructions: "",
agent: "",
agentModel: "",
agentEffort: "",
},
confirmation: {
onCreate: "ask",
@@ -465,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),