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

...
Автор SHA1 Повідомлення Дата
l0ng-ai e6ad1bee8f fix(startup): don't time out while the Trust Project prompt waits for an answer
A window opened for an untrusted project asks Trust Project over the splash.
The 60-second startup watchdog in boot.js kept counting while the prompt was up,
so answering after a minute replaced the prompt with "OpenIDEA could not start".
askOverSplash now tells boot.js when a question starts and ends, and the
watchdog pauses for that time, as it already does while the window is hidden.
2026-11-18 21:25:22 +08:00
l0ng-ai 3ed4fa6836 fix(vcs): keep worktree operation errors through refresh (#4271) 2026-11-18 21:20:10 +08:00
l0ng-ai 4990a90bbf Keep build selections when reloading the .NET workspace (#4267) 2026-11-18 21:14:17 +08:00
l0ng-ai 762b509b66 fix(coverage): keep asynchronous results with their project (#4260) 2026-11-18 21:05:39 +08:00
l0ng-ai 2964b2ffc5 Ignore Logcat callbacks from superseded streams (#4259) 2026-11-18 21:05:16 +08:00
l0ng-ai 704952a6ae fix(build): ignore completions from superseded requests (#4258) 2026-11-18 21:05:07 +08:00
l0ng-ai 65007093e7 Confirm before replacing a saved macro recording (#4256) 2026-11-18 21:03:14 +08:00
l0ng-ai 696ab0c3ba fix(http-client): pin the starting environment for request batches (#4255) 2026-11-18 21:01:37 +08:00
l0ng-ai e282546697 Isolate GitHub review drafts by pull request context (#4252) 2026-11-18 20:55:46 +08:00
l0ng-ai 93fb7b6a85 fix(search): keep an empty Directory scope inactive (#4250) 2026-11-18 20:53:07 +08:00
Mr0Bread e691aa9fb3 fix(ui): remeasure popup height before choosing a side (#4296)
The shared Popup decided where it fit using the max-height cap from its previous placement, so a popup clipped below its anchor still looked as if it fit there: the agent Composer's @ list stayed clipped after erasing the filter or when file results arrived after it opened. A middleware now clears the old cap before flip, and the size step only caps a popup that is taller than the space available.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-18 20:35:10 +08:00
acaoтаamphetamlne 44a12abbd7 perf(vfs): compact adjacent duplicate modification events (#3276)
Adjacent, exactly identical single-path Modify(Any/Data/Metadata) notifications (same path spelling, event and process id) are merged before they accumulate in the debounce queue; create/remove/rename, multi-path and flagged events are kept, and the first/last arrival times are kept so the 100 ms debounce and 1 s maximum delay don't move. A debug-level "file watcher batch" line reports received/queued counts and queue, processing and callback times.

Co-authored-by: amphetamlne <[email protected]>
2026-11-18 20:33:50 +08:00
GuoYuтаguoyucode 497b25bf4a fix(mcp): say projectPath defaults to the connection's project (#4262)
Every MCP tool described projectPath as optional only when one project is open, so agents with several projects open passed it on every call. The description now matches resolve_project: the call's projectPath, then the connection's project (?project= / X-OpenIDEA-Project), then the only open project.

Co-authored-by: guoyucode <[email protected]>
2026-11-18 20:31:47 +08:00
l0ng-ai 4ecfb98c94 fix(local-history): keep a file's content from before its first edit (#4302)
A file with no Local History entries had nothing to revert to at a label put before its first save. The first edit of an open document now records the file's content on disk as an "Original" snapshot when the file has no history yet, dated by its modification time (but not before the oldest entry kept, so retention and working days are unaffected). A label put before the edit finds it; a file written after the label is dated after it.
2026-11-18 20:29:55 +08:00
l0ng-ai f1d6b0dc1b fix(nav): drop a useless conversion clippy rejects (#4301) 2026-11-18 20:27:21 +08:00
Bert Verhelstтаbertyhell f2cfe38931 feat(agents): view and roll back the last turn's changes (#4042)
The agent session's Changes pane gets a Whole Task / Last Turn switch. Each turn records a baseline the way a task records its start (HEAD, the stamped list of changed files and copies of them in the task store, reusing copies of files unchanged since the previous turn); Last Turn lists only what the last turn changed, diffs against the file as that turn started, and Rollback restores only that turn's changes. Accept still brings over the whole task. Host-side behind agent_changes / agent_base_text / agent_rollback_changes (lastTurn view), so remote development works the same way.

Closes #3689

Co-authored-by: bertyhell <[email protected]>
2026-11-18 20:22:19 +08:00
l0ng-ai d18ac58b56 feat(lsp): configure a language server from the status bar popup (#4298)
Each server in the Language Servers popup gets a Configure button that opens Settings › Language Servers on that server's language with the server selected, where the interchangeable servers are chosen and additional ones turned off. tools.languageServers takes the server name and opens the page as languages.servers#<name>; the page selects that tool and scrolls its language into view.
2026-11-18 20:08:31 +08:00
Vladislav Kuzmin 0021a764c3 fix(database): connect to ClickHouse accounts with strict read-only settings (#4292)
A ClickHouse account with server-enforced readonly = 1 rejected the HTTP driver's own per-query settings (Code 164) on the connection probe. When the probe fails on one of those settings, the driver checks getSetting('readonly') in the same session and, only when it is 1, sends further requests without its own settings (the server then provides write protection; the client still caps the grid rows). A writable session that reports the error keeps failing as before.

Closes #4275

Co-authored-by: principalwater <[email protected]>
2026-11-18 20:01:45 +08:00
Mollo-i a30103d410 feat(nav): @property@ in YAML and properties resources jumps to its pom properties entry (#4243)
Go to Declaration on a Maven resource-filtering placeholder (`@profileActive@` in `application.yml` or `application.properties`) jumps to the `<properties>` entry that defines it: the nearest `pom.xml` above the resource, up through the project root, is searched along its parent chain with the lookup the pom's own `${property}` navigation uses (now exposed as `ide_build::maven::property_declaration`). Plugin definition providers still run, with the pom result first.

Closes #4241

Co-authored-by: Greenker <[email protected]>
2026-11-18 20:00:25 +08:00
Mollo-i 89798baa3c fix(lsp): a Maven resource-filtering placeholder no longer fails YAML parsing (#4242)
yaml-language-server reports "Plain value cannot start with reserved character @" for unquoted Maven placeholders such as `spring.profiles.active: @profileActive@`, which Maven replaces before the file is read as YAML. The diagnostic is dropped when its scalar is exactly an `@token@` placeholder; other parser errors (an unpaired `@`, a different message, a stale range) still show.

Co-authored-by: Greenker <[email protected]>
2026-11-18 20:00:10 +08:00
l0ng-ai c09c9b8aaf docs: describe the Linux DMA-BUF workaround for unresponsive windows (#4295)
The troubleshooting entry still said NVIDIA on Wayland gets WEBKIT_DISABLE_DMABUF_RENDERER=1; since #2179 the app turns the driver's explicit sync off instead. The entry now covers windows that stop reacting to input, notes the slower CPU drawing, and shows how to keep the variable for menu launches.
2026-11-18 19:50:24 +08:00
l0ng-ai 995a9563f7 feat(profiler): navigate and zoom the flame graph with the keyboard (#4294)
The flame graph had no keyboard focus target. It is now focusable with a current frame (outlined, announced via aria-activedescendant): Up/Down go to callee/caller, Left/Right to neighbours, Enter zooms, Escape resets, F4 opens the source. Fixes #4209.
2026-11-18 19:45:37 +08:00
l0ng-ai 893d9af6e6 fix(inspections): Rerun Inspection repeats the file its results are for (#4291)
A Current file inspection stored its unresolved scope, so Rerun resolved it to whichever file was active. The run now records the file it inspected and Rerun inspects that file again. Fixes #4234.
2026-11-18 19:42:27 +08:00
l0ng-ai 73496669e7 fix(web): the built-in preview reloads only for the page and web resources (#4290)
The HTML preview reloaded on any project file change or document save, so editing notes.txt cleared the page's inputs and scroll position. It now reloads when the page itself or a web resource changes. Fixes #4231.
2026-11-18 19:41:01 +08:00
l0ng-ai add914f7fb fix(markdown): a word double-clicked in the preview leaves out the space after it (#4288)
On Windows a double-click selects the word plus the following space, so the preview's selection highlights and Find used "Order ". A word selection's trailing whitespace is now dropped from the text and, when it ends in a text node, from the selection itself. Fixes #4230.
2026-11-18 19:37:24 +08:00
l0ng-ai 0fd0f08865 fix(search): Replace All saves open documents that had no unsaved changes (#4286)
Replace All saved only files it opened itself, so a file the search preview held open got the replacement in memory but not on disk. Documents without unsaved changes are now saved after the replacement; buffers the user is editing are left unsaved. Fixes #4202.
2026-11-18 19:35:26 +08:00
l0ng-ai 054d2ba517 fix(toolwindows): show Hide All Tool Windows as Restore Tool Windows when it restores (#4277)
With every window hidden, Hide All restores them but kept its Hide label. The actions registry gets retitleAction for titles that follow state; the action and its menu label read Restore Tool Windows while a hidden set can be restored. Fixes #4162.
2026-11-18 19:27:54 +08:00
l0ng-ai 738dc12ef7 fix(libraries): clear the previous project's External Libraries on switching (#4276)
The External Libraries node and last complete result were kept across a project switch until the new discovery answered, so the new project showed and filled in the old project's libraries. Refreshing for another project now clears them first. Fixes #4194.
2026-11-18 19:26:48 +08:00
l0ng-ai 6135a5326d fix(local-history): reverting to a label leaves files deleted before it absent (#4274)
A file whose last revision before a label is its Deleted snapshot was absent at the label, but Revert restored it and counted it. Folder reverts now skip such files; a file's own revert says it did not exist then. Part of #4199.
2026-11-18 19:22:37 +08:00
l0ng-ai 403bb28ca4 fix(local-history): keep snapshots as document text (no BOM, LF) (#4272)
Saves record the document's text but the watcher snapshotted the file with its BOM and CRLF, adding an External change revision per save; reverting that revision doubled the BOM. Disk snapshots and snapshot content are now normalized to document text. Fixes #4195.
2026-11-18 19:21:04 +08:00
l0ng-ai 3249d4ee90 fix(lsp): count a Rust error once when rust-analyzer and rustc both report it (#4270)
rust-analyzer publishes its own analysis next to cargo check's, so one type mismatch arrived as rust-analyzer(E0308) and rustc(E0308) and counted twice. Its own entry is dropped when rustc reports the same code and severity over an overlapping range. Fixes #4193.
2026-11-18 19:18:46 +08:00
l0ng-ai 79e41c85ff fix(build): resolve Build Module's Cargo diagnostics from the workspace root (#4269)
rustc names workspace members' files from the workspace root; Build Module runs cargo in the member, so its diagnostics doubled the member folder. Resolution now tries the manifest directory, then its ancestors, taking the first existing file. Fixes #4189.
2026-11-18 19:17:01 +08:00
l0ng-ai f0a7cca1b1 fix(project-view): say which view option hides a file Select Opened File can't reach (#4268)
With Show Excluded Files or Show Hidden Files off, Select Opened File silently selected the nearest shown ancestor. It now notifies which option hides the file, with an action that turns it on and selects the file. Fixes #4181.
2026-11-18 19:15:14 +08:00
l0ng-ai 21f1e2bbb4 fix(editor): don't carry untitled tabs to the Welcome screen (#4264)
Untitled tabs were carried when Close Project returned to Welcome, after the leave guard had asked about them, so a draft discarded with Don't Save reopened as an empty focused tab. Closing to Welcome now drops them; in-place switches still carry them. Fixes #4173.
2026-11-18 19:11:22 +08:00
l0ng-ai ffdb5d74f2 fix(navigation): Navigate to Test uses the top-level class at the caret (#4263)
Navigate to Test derived test names from the file name, so with the caret in a second top-level class it offered the file's test instead. For Java, Kotlin, Scala, Groovy and C# it now takes the outermost type around the caret from the document outline, falling back to the file name. Fixes #4171.
2026-11-18 19:08:21 +08:00
l0ng-ai d4d9e7d191 fix(editor): tab limit keeps VCS-changed tabs with Close non-modified files first (#4261)
The tab limit's closing policy only counted unsaved changes as modified, so a saved file with a Git change closed before clean tabs. It now shares Close Unmodified Tabs' check: unsaved changes or a VCS status. Fixes #4166.
2026-11-18 19:05:43 +08:00
l0ng-ai 6a41509fd2 fix(project-trust): list restricted projects in Project Trust settings (#4257)
A project with a restricted decision stays restricted inside a trusted location, but the settings page didn't list those decisions. The page now lists restricted projects with a Trust button, and the location hint says restricted projects are excluded. Fixes #4156.
2026-11-18 19:03:39 +08:00
l0ng-ai 6efece99a4 fix(project): ask about trust before leaving the current project (#4253)
Opening a folder in this window confirmed leaving the current project (which stops its running processes) before the trust prompt, so Don't Open left the original project without its processes. Trust is now asked first; the fallback open path follows the same order. Fixes #4160.
2026-11-18 19:00:24 +08:00
l0ng-ai 0fab45689f fix(vcs): expire the conflict notice once the merge or rebase is over (#4251)
"All conflicts resolved" kept its Commit… and Abort Merge actions after the
merge was committed, and Abort Merge then reported no merge in progress. The
conflict notices (key vcs.conflicts) now expire when the repository leaves
the merge, rebase, cherry-pick, revert or am they refer to, however it ended.

Fixes #4154
2026-11-18 18:53:43 +08:00
l0ng-ai 71090202b6 fix(debugger): Breakpoints dialog selects on click and keeps typed conditions (#4249)
A single click on a breakpoint jumped to its source and closed the dialog,
and a condition typed and confirmed with Enter (Done) was lost, as only
leaving the field saved it. A click now selects the breakpoint (double-click
or Enter goes to the source), and the shown breakpoint's typed fields are
saved when the dialog closes or another breakpoint is shown, for method and
field breakpoints too; unchanged fields are not written again.

Fixes #4150
2026-11-18 18:52:04 +08:00
l0ng-ai 8ed08510ed fix: Delete in a popup's search field edits the text before it removes the selection (#4248)
Open Recent removed the selected project on Delete wherever the caret was in
the search field, and the run configuration chooser deleted the selected
configuration without asking. Delete now acts on the selection only when it
has no text to delete (the caret at the end of the query, nothing selected;
⌘⌫ only with an empty query), and the chooser asks before deleting a
configuration, from Delete or its menu, as IDEA's popup does.

Fixes #4159
Fixes #4203
2026-11-18 18:48:03 +08:00
l0ng-ai 500df4ffc4 fix(vcs): Show Diff of a staged or unstaged row shows that side of the index (#4247)
The changes tree's Show Diff passed only the file's path to the action, which
opened HEAD against the working copy, so a partially staged file showed its
unstaged edit from the Staged group too. The menu item now opens the row's own
diff, as double-click does: HEAD ↔ Index under Staged, Index ↔ working copy under
Unstaged. Show Diff from the keyboard builds the tree the Commit window shows
(staging groups, no change lists, with the staging area) so the selected row is
found, and uses it with the non-modal interface too.

Fixes #4152
2026-11-18 18:45:05 +08:00
l0ng-ai 81aa9418aa fix(vcs): no Commit File… in the changes tree with the staging area (#4246)
With the staging area the commit takes the whole index, so Commit File… on a
staged file only focused the message and committed every staged file. The
item is left out of the changes tree's menu while the staging area is on, as
the staging tree has no per-file commit.

Fixes #4153
2026-11-18 18:39:57 +08:00
acaoтаamphetamlne 706ce87cb7 test(plugins): exercise fuel renewal with explicit CPU work (#3438)
Keeps main's 40,000 foreground fuel budget and patient CPU workload, and adds a quiet mode that runs the same workload without task reports and must exhaust the scaled budget, so beginning a task alone is shown not to renew it. The Git capability setup now fails the test instead of returning early. Production limits are unchanged.

Co-authored-by: amphetamlne <[email protected]>
2026-11-18 18:38:14 +08:00
胡翀таzzxzz12345 4e5dbc8e0c feat(markdown): render LaTeX math with KaTeX (#4138)
Markdown views (file preview, agent chat, notebook Markdown cells, LSP/GitHub/plugin Markdown) now typeset $...$, $$...$$, \(...\), \[...\] and ```math blocks with KaTeX. The marked extension emits [data-math] placeholders that survive DOMPurify and are typeset after sanitizing (trust: false); inline $ follows Pandoc's rules, so currency like $5 and $10 stays text. The Markdown preview keeps the placeholders in its rendered HTML and typesets them after each render, like Mermaid diagrams, so its per-block sanitize cache is unaffected.

New dependency: katex 0.19.1 (MIT).

Co-authored-by: zzxzz12345 <[email protected]>
2026-11-18 18:36:43 +08:00
Deng Liuтаdengliu 79accd1311 perf(settings): split Settings and auxiliary window boot out of the Workbench module (#4044)
Native auxiliary windows (settings, comparison, diff, deployment) all booted src/main.tsx, which statically imported the Workbench and every workbench feature (CodeMirror, xterm, editor extensions) even when the Settings window rendered none of them. main.tsx is now a small window-kind router with one boot module per window kind, and the settings pages, core plugin points and plugin theme runtime are registered from editor-free modules, so the Settings window loads no Workbench, @codemirror, @xterm or @/editor modules (about 57% less JS and a third less heap per Settings window). A static test keeps the Settings boot isolated.

Part of #3942

Co-authored-by: dengliu <[email protected]>
2026-11-18 18:32:14 +08:00
Deng Liuтаdengliu 85d02e03f9 feat(agents): discover MCP servers from installed Copilot CLI plugins (#4029)
MCP servers bundled in installed GitHub Copilot CLI plugins (installedPlugins in ~/.copilot/config.json) were started by Copilot CLI in sessions but never listed in Session MCP Servers or Agent Configs, so they could not be seen, disabled per session or imported. External discovery and import now also read each enabled plugin's .mcp.json / plugin.json mcpServers inside its cache_path (paths kept within the plugin root), expand ${COPILOT_PLUGIN_ROOT} / ${CLAUDE_PLUGIN_ROOT} / ${PLUGIN_ROOT}, and honour disabledMcpServers and enabledPlugins in ~/.copilot/settings.json.

Co-authored-by: dengliu <[email protected]>
2026-11-18 18:18:21 +08:00
Ernstjan FreriksтаEjaYF e689c95e93 feat(database): create and drop databases and schemas from the tree (#4201)
The Database tree gets New > Database... and New > Schema..., and Drop... on database nodes (PostgreSQL, MySQL/MariaDB schemas, SQL Server), each with a preview of the statement it runs.

Creating closes the IDE's own connections to the database the server copies (the template on PostgreSQL, model on SQL Server), which both refuse to copy while it has sessions. Dropping closes the IDE's pools and sessions of that database first and runs DROP DATABASE on the data source's default database; "Close the sessions of other clients" adds WITH (FORCE) on PostgreSQL 13+ and single-user mode on SQL Server. Drop is refused for the data source's own database and read-only data sources. Both go through withConnection, so a password the data source does not save is asked for first.

Closes #3189

Co-authored-by: EjaYF <[email protected]>
2026-11-18 18:17:18 +08:00
faithererer bb243909bf feat(vcs): suggest branch name prefixes in the New Branch dialog (#4219)
Typing a name in Create New Branch now suggests the folders of existing local branch names (typing `fe` offers `feat/`, `feat/2610/`, `feat/2610/08/`), shallowest first. Arrow keys pick one, Enter or Tab fills it in and keeps typing; Enter without a pick creates the branch as typed. Remote branches are left out of the suggestions.

Closes #4208

Co-authored-by: faithererer <[email protected]>
2026-11-18 18:00:55 +08:00
HL-SLCтаHL-slc 64544a4edd fix(database): don't read data sources after the project is closed (#4226)
Closing the project resets the database state to not loaded while an open SQL file's console bar is still mounted; its effect called loadSources() with no project open and showed "Cannot read data sources: no project is open in this window". loadSources() now returns early without a project; the next project loads its sources as before.

Co-authored-by: HL-slc <[email protected]>
2026-11-18 17:58:16 +08:00
l0ng-ai 4fd1e4356e fix(java): keep jdtls temporary files in its workspace and clear them at start (#4238)
JDT APT copies a project's annotation processor jars into a new jdt-apt-*
folder in the system temp directory for each processor class loader, and
deletes them only when the JVM exits normally. jdtls stopped by the IDE never
does, and on Windows the jars are still open at exit, so every start left
another copy behind (tens of GB in %TEMP% after a while).

jdtls now gets -Djava.io.tmpdir=<workspace>/.tmp for the workspaces the IDE
creates, and that folder is emptied before each start. A temp directory set in
the user's JVM arguments, and a -data workspace of the user's own, are left
alone.

Fixes #4192
2026-11-18 17:56:21 +08:00
221 змінених файлів з 7503 додано та 1637 видалено

No files matched your search

+146 -32
Переглянути файл
@@ -359,6 +359,9 @@ struct TaskFile {
/// `None` for a worktree task, and a task saved before these were recorded.
#[serde(default, skip_serializing_if = "Option::is_none")]
touched: Option<BTreeSet<String>>,
/// The checkout as the last turn started, its copies in the store's `<id>.turn` folder.
#[serde(default, skip_serializing_if = "Option::is_none")]
turn: Option<worktree::TurnStart>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
subagents: Vec<SavedSubagent>,
/// Turns to drop from the session once it is loaded (a fork of an earlier point).
@@ -382,6 +385,8 @@ struct TaskState {
saved: Option<String>,
/// See `TaskFile::touched`.
touched: Option<Arc<BTreeSet<String>>>,
/// See `TaskFile::turn`.
turn: Option<Arc<worktree::TurnStart>>,
pending_rollback: u32,
/// The user named the task; see `TaskFile::title_renamed`.
title_renamed: bool,
@@ -753,6 +758,7 @@ impl AgentManager {
before: BTreeMap::new(),
saved: None,
touched: Some(BTreeSet::new()),
turn: None,
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: true,
@@ -866,6 +872,7 @@ impl AgentManager {
before,
saved,
touched: (req.isolation == Isolation::Local).then(BTreeSet::new),
turn: None,
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: false,
@@ -1189,6 +1196,8 @@ impl AgentManager {
before: (*s.before).clone(),
saved: s.saved.clone(),
touched: s.touched.as_deref().cloned(),
// The source's next turn replaces its copies: the fork's last turn is one of its own.
turn: None,
subagents: s.conversation.saved_subagents(),
pending_rollback: total - keep,
title_renamed: s.title_renamed,
@@ -1528,6 +1537,7 @@ impl AgentManager {
self.tasks.write().remove(id);
*task.deleted.lock() = true;
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
let _ = std::fs::remove_dir_all(task.turn_dir());
let saved = task.state.lock().saved.clone();
if let Some(saved) = saved
&& !self.tasks.read().values().any(|t| t.state.lock().saved.as_ref() == Some(&saved))
@@ -1570,18 +1580,47 @@ impl AgentManager {
.await
}
/// Content of `path` (in the task's directory) when the task started.
pub async fn base_text(&self, id: &str, path: PathBuf) -> IdeResult<Option<String>> {
let at = self.task(id)?.base();
blocking(move || match at.rev()? {
Some(rev) => worktree::file_at(at.cwd(), &path, &rev),
None => Ok(None),
/// The files the task's last turn changed, against the checkout as it started (while a
/// turn runs: that turn's so far). None before the task's first turn.
pub async fn turn_changes(&self, id: &str) -> IdeResult<Vec<AgentChange>> {
let (cwd, turn, dir) = self.task(id)?.last_turn();
let Some(turn) = turn else { return Ok(Vec::new()) };
blocking(move || {
let changed = match &turn.changed {
Some(changed) => changed.clone(),
None => worktree::changed_in_turn(&cwd, &turn)?.1,
};
worktree::turn_changes(&cwd, &turn, &dir, &changed)
})
.await
}
/// Content of `path` (in the task's directory) as `view` compares it: when the task
/// started, in `HEAD`, or when the last turn started.
pub async fn base_text(&self, id: &str, path: PathBuf, view: AgentChangesView) -> IdeResult<Option<String>> {
let task = self.task(id)?;
if view == AgentChangesView::LastTurn {
let (cwd, turn, dir) = task.last_turn();
let Some(turn) = turn else { return Ok(None) };
return blocking(move || worktree::turn_text(&cwd, &path, &turn, &dir)).await;
}
let at = task.base();
blocking(move || {
let rev = match view {
AgentChangesView::Group => worktree::head_commit(at.cwd())?,
_ => at.rev()?,
};
match rev {
Some(rev) => worktree::file_at(at.cwd(), &path, &rev),
None => Ok(None),
}
})
.await
}
/// Rollback: puts the task's changed files among `rel_paths` (all with `None`) back as
/// `view` compares them: as they were when it started, or as they are in `HEAD`.
/// `view` compares them: as they were when it started, as they are in `HEAD`, or as they
/// were when its last turn started.
pub async fn rollback_changes(
&self,
id: &str,
@@ -1592,15 +1631,18 @@ impl AgentManager {
if task.state.lock().busy {
return Err(IdeError::invalid("the agent is working: stop it before rolling back its changes"));
}
if view == AgentChangesView::LastTurn {
return self.rollback_turn(&task, rel_paths).await;
}
let at = task.base();
let (before, saved, touched) = {
let s = task.state.lock();
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)), s.touched.clone())
};
let restamped = blocking(move || {
let (restamped, restored) = blocking(move || {
let (changes, rev) = match view {
AgentChangesView::Group => (at.grouped_changes(&before)?.uncommitted, worktree::head_commit(at.cwd())?),
AgentChangesView::SinceStart => (at.changes(&before)?, at.rev()?),
AgentChangesView::SinceStart | AgentChangesView::LastTurn => (at.changes(&before)?, at.rev()?),
};
let changes = worktree::made_by_task(changes, touched.as_deref());
let sources = match rev.as_deref() {
@@ -1608,6 +1650,7 @@ impl AgentManager {
None => Default::default(),
};
let mut restamped = Vec::new();
let mut restored = Vec::new();
for change in changes.iter().filter(|c| rel_paths.as_ref().is_none_or(|p| p.contains(&c.rel_path))) {
// A rename goes back to its old path too; the new one is taken away first, so a
// case-only rename on a case-insensitive disk ends as the old file.
@@ -1617,6 +1660,58 @@ impl AgentManager {
if before.contains_key(&change.rel_path) {
restamped.push((change.rel_path.clone(), worktree::stamp(&change.path.0)));
}
restored.push(change.rel_path.clone());
}
}
Ok((restamped, restored))
})
.await?;
{
let mut s = task.state.lock();
if !restamped.is_empty() {
let mut before = (*s.before).clone();
before.extend(restamped);
s.before = Arc::new(before);
}
// Rolled back further than the last turn: what it changed there is gone, not the turn's to list.
if let Some(turn) = &s.turn
&& let Some(changed) = &turn.changed
&& restored.iter().any(|rel| changed.contains(rel))
{
let changed = changed.iter().filter(|rel| !restored.contains(rel)).cloned().collect();
s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(changed), ..(**turn).clone() }));
}
}
task.persist();
Ok(())
}
/// Puts the last turn's changed files among `rel_paths` (all with `None`) back as they
/// were when it started.
async fn rollback_turn(&self, task: &Task, rel_paths: Option<Vec<String>>) -> IdeResult<()> {
let (cwd, turn, dir) = task.last_turn();
let Some(turn) = turn else { return Ok(()) };
let (before, saved) = {
let s = task.state.lock();
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)))
};
let restamped = blocking(move || {
let changed = match &turn.changed {
Some(changed) => changed.clone(),
None => worktree::changed_in_turn(&cwd, &turn)?.1,
};
let mut restamped = Vec::new();
for change in worktree::turn_changes(&cwd, &turn, &dir, &changed)?
.iter()
.filter(|c| rel_paths.as_ref().is_none_or(|p| p.contains(&c.rel_path)))
{
worktree::restore_turn(&cwd, &turn, &dir, change)?;
// Back to the user's own edits from before the task: not a change of the task.
if let Some(Some(_)) = before.get(&change.rel_path)
&& let Some(copy) = saved.as_deref().and_then(|d| worktree::saved_copy(d, &change.rel_path))
&& std::fs::read(&change.path.0).is_ok_and(|now| now == copy)
{
restamped.push((change.rel_path.clone(), worktree::stamp(&change.path.0)));
}
}
Ok(restamped)
@@ -1752,6 +1847,7 @@ impl Task {
before: Arc::new(file.before),
saved: file.saved,
touched: file.touched.map(Arc::new),
turn: file.turn.map(Arc::new),
pending_rollback: file.pending_rollback,
title_renamed: file.title_renamed,
busy: false,
@@ -1785,31 +1881,48 @@ impl Task {
(s.before.clone(), s.touched.clone())
}
/// The changed files of the checkout as a turn starts, when the task records what its turns change.
async fn checkout_before_turn(&self) -> Option<Snapshot> {
let cwd = {
let s = self.state.lock();
s.touched.as_ref()?;
s.task.cwd.0.clone()
};
blocking(move || worktree::snapshot(&cwd)).await.ok()
/// Where the copies of the files already changed as the last turn started are kept.
fn turn_dir(&self) -> PathBuf {
self.shared.paths.store_dir.join(format!("{}.turn", self.id))
}
/// Records the files that changed in the checkout since `start`, as the turn ends, as the task's.
async fn record_turn_changes(&self, start: Option<Snapshot>) {
let Some(start) = start else { return };
let cwd = self.state.lock().task.cwd.0.clone();
let Ok(end) = blocking(move || worktree::snapshot(&cwd)).await else { return };
let changed = worktree::changed_between(&start, &end);
if changed.is_empty() {
return;
}
/// The checkout as the last turn started, with the folder of its copies.
fn last_turn(&self) -> (PathBuf, Option<Arc<worktree::TurnStart>>, PathBuf) {
let s = self.state.lock();
(s.task.cwd.0.clone(), s.turn.clone(), self.turn_dir())
}
/// Records the checkout as a turn starts: what the turn's changes are compared with.
async fn checkout_before_turn(&self) {
let (cwd, previous, dir) = self.last_turn();
let turn = match blocking(move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await {
Ok(turn) => Some(Arc::new(turn)),
Err(e) => {
tracing::warn!("recording the checkout as a turn of agent task {} starts: {e}", self.id);
None
}
};
self.state.lock().turn = turn;
self.persist();
}
/// Records the files that changed in the checkout while the turn ran: the turn's, and in
/// the project's own checkout also the task's.
async fn record_turn_changes(&self) {
let (cwd, turn, _) = self.last_turn();
let Some(turn) = turn else { return };
let start = turn.clone();
let Ok((in_worktree, all)) = blocking(move || worktree::changed_in_turn(&cwd, &start)).await else { return };
{
let mut s = self.state.lock();
let Some(touched) = &s.touched else { return };
let mut touched = (**touched).clone();
touched.extend(changed);
s.touched = Some(Arc::new(touched));
if !in_worktree.is_empty()
&& let Some(touched) = &s.touched
{
let mut touched = (**touched).clone();
touched.extend(in_worktree);
s.touched = Some(Arc::new(touched));
}
s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() }));
}
self.persist();
}
@@ -1926,6 +2039,7 @@ impl Task {
before: (*s.before).clone(),
saved: s.saved.clone(),
touched: s.touched.as_deref().cloned(),
turn: s.turn.as_deref().cloned(),
subagents: s.conversation.saved_subagents(),
pending_rollback: s.pending_rollback,
title_renamed: s.title_renamed,
@@ -1977,11 +2091,11 @@ impl Task {
/// the user stops one. The caller set `busy`.
async fn run(self: Arc<Self>, mut prompt: AgentPrompt) {
loop {
let start = self.checkout_before_turn().await;
self.checkout_before_turn().await;
let result = self.turn(&prompt).await;
self.cancel_pending.store(false, Ordering::Release);
tokio::time::sleep(TURN_GRACE).await;
self.record_turn_changes(start).await;
self.record_turn_changes().await;
let changed = self.state.lock().conversation.end_turn(Some(now_ms()));
self.mark_dirty(changed);
let send_now = self.send_now.swap(false, Ordering::AcqRel);
+436 -49
Переглянути файл
@@ -399,163 +399,429 @@ pub fn apply_save_json(
Ok(saved_names)
}
#[derive(Clone, Copy, PartialEq, Eq)]
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
".github/plugin/plugin.json",
".plugin/plugin.json",
".claude-plugin/plugin.json",
".cursor-plugin/plugin.json",
"plugin.json",
];
#[derive(Clone, PartialEq, Eq)]
enum SourceFormat {
Jsonc,
CodexToml,
CopilotPlugin { root: PathBuf },
}
#[derive(Clone)]
struct SourceSpec {
id: &'static str,
label: &'static str,
id: String,
label: String,
path: PathBuf,
format: SourceFormat,
suggested_scope: McpScope,
native_provider: Option<&'static str>,
claude_project_lookup: bool,
disabled_servers: std::sync::Arc<BTreeSet<String>>,
}
#[derive(Default)]
struct CopilotSettings {
disabled_mcp_servers: std::sync::Arc<BTreeSet<String>>,
disabled_plugins: BTreeSet<String>,
}
fn external_source_specs(home_dir: Option<&Path>, workspace_root: Option<&Path>) -> Vec<SourceSpec> {
let mut specs = Vec::new();
let no_disabled: std::sync::Arc<BTreeSet<String>> = std::sync::Arc::new(BTreeSet::new());
if let Some(root) = workspace_root {
specs.push(SourceSpec {
id: "workspace-mcp",
label: "Project (.mcp.json)",
id: "workspace-mcp".into(),
label: "Project (.mcp.json)".into(),
path: root.join(".mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: Some("claude"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "vscode-mcp",
label: "VS Code (.vscode/mcp.json)",
id: "vscode-mcp".into(),
label: "VS Code (.vscode/mcp.json)".into(),
path: root.join(".vscode").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: None,
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "cursor-project",
label: "Cursor Project (.cursor/mcp.json)",
id: "cursor-project".into(),
label: "Cursor Project (.cursor/mcp.json)".into(),
path: root.join(".cursor").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: Some("cursor"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "codex-project",
label: "Codex Project (.codex/config.toml)",
id: "codex-project".into(),
label: "Codex Project (.codex/config.toml)".into(),
path: root.join(".codex").join("config.toml"),
format: SourceFormat::CodexToml,
suggested_scope: McpScope::Workspace,
native_provider: Some("codex"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "gemini-project",
label: "Gemini Project (.gemini/settings.json)",
id: "gemini-project".into(),
label: "Gemini Project (.gemini/settings.json)".into(),
path: root.join(".gemini").join("settings.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: Some("gemini"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
}
if let Some(home) = home_dir {
let copilot_dir = home.join(".copilot");
let copilot_settings = read_copilot_settings(&copilot_dir);
specs.push(SourceSpec {
id: "copilot-cli",
label: "GitHub Copilot CLI",
path: home.join(".copilot").join("mcp-config.json"),
id: "copilot-cli".into(),
label: "GitHub Copilot CLI".into(),
path: copilot_dir.join("mcp-config.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("copilot"),
claude_project_lookup: false,
disabled_servers: copilot_settings.disabled_mcp_servers.clone(),
});
specs.extend(copilot_plugin_source_specs(&copilot_dir, &copilot_settings));
specs.push(SourceSpec {
id: "claude-code",
label: "Claude Code",
id: "claude-code".into(),
label: "Claude Code".into(),
path: home.join(".claude.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("claude"),
claude_project_lookup: true,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "codex",
label: "Codex",
id: "codex".into(),
label: "Codex".into(),
path: home.join(".codex").join("config.toml"),
format: SourceFormat::CodexToml,
suggested_scope: McpScope::User,
native_provider: Some("codex"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "cursor",
label: "Cursor",
id: "cursor".into(),
label: "Cursor".into(),
path: home.join(".cursor").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("cursor"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "gemini",
label: "Gemini CLI",
id: "gemini".into(),
label: "Gemini CLI".into(),
path: home.join(".gemini").join("settings.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("gemini"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "jetbrains-air",
label: "JetBrains Air",
id: "jetbrains-air".into(),
label: "JetBrains Air".into(),
path: home.join(".jetbrains").join("mcp").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: None,
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "copilot-intellij",
label: "GitHub Copilot (JetBrains)",
id: "copilot-intellij".into(),
label: "GitHub Copilot (JetBrains)".into(),
path: home.join(".config").join("github-copilot").join("intellij").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: None,
claude_project_lookup: false,
disabled_servers: no_disabled,
});
}
specs
}
fn read_source_servers(spec: &SourceSpec, workspace_root: Option<&Path>) -> BTreeMap<String, AgentMcpServer> {
let Ok(text) = std::fs::read_to_string(&spec.path) else {
return BTreeMap::new();
fn read_copilot_settings(copilot_dir: &Path) -> CopilotSettings {
let Ok(text) = std::fs::read_to_string(copilot_dir.join("settings.json")) else {
return CopilotSettings::default();
};
if spec.format == SourceFormat::CodexToml {
return parse_codex_toml_servers(&text);
}
let Ok(root) = parse_jsonc_value(&text) else {
return BTreeMap::new();
return CopilotSettings::default();
};
let mut servers = extract_servers_from_root(&root, None);
if spec.claude_project_lookup
&& let Some(ws) = workspace_root
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
{
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
for (proj_key, proj_val) in projects {
let matches = Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
if matches {
for (name, srv) in extract_servers_from_root(proj_val, None) {
servers.insert(name, srv);
let disabled_mcp_servers = root
.get("disabledMcpServers")
.and_then(Value::as_array)
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned))
.collect::<BTreeSet<_>>()
})
.unwrap_or_default();
let disabled_plugins = root
.get("enabledPlugins")
.and_then(Value::as_object)
.map(|obj| {
obj.iter()
.filter(|(_, v)| v.as_bool() == Some(false))
.map(|(k, _)| k.trim().to_owned())
.filter(|k| !k.is_empty())
.collect::<BTreeSet<_>>()
})
.unwrap_or_default();
CopilotSettings { disabled_mcp_servers: std::sync::Arc::new(disabled_mcp_servers), disabled_plugins }
}
fn copilot_plugin_source_specs(copilot_dir: &Path, settings: &CopilotSettings) -> Vec<SourceSpec> {
let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json")) else {
return Vec::new();
};
let Ok(root) = parse_jsonc_value(&text) else {
return Vec::new();
};
let Some(installed) = root.get("installedPlugins").and_then(Value::as_array) else {
return Vec::new();
};
let mut seen_ids = HashSet::new();
let mut specs = Vec::new();
for entry in installed {
let Some(obj) = entry.as_object() else { continue };
if obj.get("enabled").and_then(Value::as_bool) == Some(false) {
continue;
}
let Some(name) = obj.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) else {
continue;
};
let marketplace = obj.get("marketplace").and_then(Value::as_str).map(str::trim).unwrap_or_default();
if settings.disabled_plugins.contains(name)
|| (!marketplace.is_empty()
&& (settings.disabled_plugins.contains(&format!("{name}@{marketplace}"))
|| settings.disabled_plugins.contains(&format!("{marketplace}/{name}"))))
{
continue;
}
let Some(raw_cache) = obj.get("cache_path").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
else {
continue;
};
let plugin_root =
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
if !plugin_root.is_dir() {
continue;
}
let Some((manifest_path, _)) = read_copilot_plugin_servers(&plugin_root) else {
continue;
};
let base_id = if marketplace.is_empty() {
format!("copilot-plugin:{name}")
} else {
format!("copilot-plugin:{marketplace}/{name}")
};
let mut id = base_id.clone();
let mut suffix = 2usize;
while !seen_ids.insert(id.clone()) {
id = format!("{base_id}#{suffix}");
suffix += 1;
}
let label = if marketplace.is_empty() {
format!("GitHub Copilot Plugin ({name})")
} else {
format!("GitHub Copilot Plugin ({name} · {marketplace})")
};
specs.push(SourceSpec {
id,
label,
path: manifest_path,
format: SourceFormat::CopilotPlugin { root: plugin_root },
suggested_scope: McpScope::User,
native_provider: Some("copilot"),
claude_project_lookup: false,
disabled_servers: settings.disabled_mcp_servers.clone(),
});
}
specs
}
fn resolve_within_dir(base_dir: &Path, candidate: &Path) -> Option<PathBuf> {
if candidate.as_os_str().is_empty() {
return None;
}
let base_canon = dunce::canonicalize(base_dir).ok()?;
let clean = candidate.strip_prefix(".").unwrap_or(candidate);
let joined = if clean.is_relative() { base_dir.join(clean) } else { clean.to_path_buf() };
let meta = std::fs::metadata(&joined).ok()?;
if !meta.is_file() {
return None;
}
let target_canon = dunce::canonicalize(&joined).ok()?;
target_canon.starts_with(&base_canon).then_some(joined)
}
fn expand_plugin_root_vars(value: &str, root: &str) -> String {
value.replace("${COPILOT_PLUGIN_ROOT}", root).replace("${CLAUDE_PLUGIN_ROOT}", root).replace("${PLUGIN_ROOT}", root)
}
fn expand_plugin_servers(servers: &mut BTreeMap<String, AgentMcpServer>, plugin_root: &Path) {
let root = plugin_root.to_string_lossy();
for srv in servers.values_mut() {
if let Some(cmd) = srv.command.as_mut() {
*cmd = expand_plugin_root_vars(cmd, &root);
}
for arg in &mut srv.args {
*arg = expand_plugin_root_vars(arg, &root);
}
if let Some(url) = srv.url.as_mut() {
*url = expand_plugin_root_vars(url, &root);
}
for val in srv.env.values_mut() {
*val = expand_plugin_root_vars(val, &root);
}
for val in srv.headers.values_mut() {
*val = expand_plugin_root_vars(val, &root);
}
}
}
fn extract_plugin_manifest_servers(
plugin_root: &Path,
manifest_path: &Path,
mcp_val: &Value,
) -> (PathBuf, BTreeMap<String, AgentMcpServer>) {
match mcp_val {
Value::String(rel) => {
if let Some(path) = resolve_within_dir(plugin_root, Path::new(rel.trim())) {
let map = read_external_file(&path);
return (path, map);
}
(manifest_path.to_path_buf(), BTreeMap::new())
}
Value::Object(_) => {
let wrapper = json!({ "mcpServers": mcp_val });
(manifest_path.to_path_buf(), extract_servers_from_root(&wrapper, None))
}
Value::Array(items) => {
let mut merged = BTreeMap::new();
let mut first_path: Option<PathBuf> = None;
for item in items {
match item {
Value::String(rel) => {
if let Some(path) = resolve_within_dir(plugin_root, Path::new(rel.trim())) {
let map = read_external_file(&path);
if !map.is_empty() && first_path.is_none() {
first_path = Some(path);
}
merged.extend(map);
}
}
Value::Object(_) => {
let map = extract_servers_from_root(item, None);
if !map.is_empty() && first_path.is_none() {
first_path = Some(manifest_path.to_path_buf());
}
merged.extend(map);
}
_ => {}
}
}
(first_path.unwrap_or_else(|| manifest_path.to_path_buf()), merged)
}
_ => (manifest_path.to_path_buf(), BTreeMap::new()),
}
}
fn read_copilot_plugin_servers(plugin_root: &Path) -> Option<(PathBuf, BTreeMap<String, AgentMcpServer>)> {
if let Some(dot_mcp) = resolve_within_dir(plugin_root, Path::new(".mcp.json")) {
let mut servers = read_external_file(&dot_mcp);
if !servers.is_empty() {
expand_plugin_servers(&mut servers, plugin_root);
return Some((dot_mcp, servers));
}
}
for rel in COPILOT_PLUGIN_MANIFESTS {
let Some(manifest_path) = resolve_within_dir(plugin_root, Path::new(rel)) else {
continue;
};
let Ok(text) = std::fs::read_to_string(&manifest_path) else {
continue;
};
let Ok(manifest) = parse_jsonc_value(&text) else {
continue;
};
let Some(mcp_val) = manifest.get("mcpServers") else {
continue;
};
let (source_path, mut servers) = extract_plugin_manifest_servers(plugin_root, &manifest_path, mcp_val);
if !servers.is_empty() {
expand_plugin_servers(&mut servers, plugin_root);
return Some((source_path, servers));
}
}
None
}
fn read_source_servers(spec: &SourceSpec, workspace_root: Option<&Path>) -> BTreeMap<String, AgentMcpServer> {
let mut servers = match &spec.format {
SourceFormat::CopilotPlugin { root } => {
read_copilot_plugin_servers(root).map(|(_, map)| map).unwrap_or_default()
}
SourceFormat::CodexToml => {
let Ok(text) = std::fs::read_to_string(&spec.path) else {
return BTreeMap::new();
};
parse_codex_toml_servers(&text)
}
SourceFormat::Jsonc => {
let Ok(text) = std::fs::read_to_string(&spec.path) else {
return BTreeMap::new();
};
let Ok(root) = parse_jsonc_value(&text) else {
return BTreeMap::new();
};
let mut map = extract_servers_from_root(&root, None);
if spec.claude_project_lookup
&& let Some(ws) = workspace_root
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
{
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
for (proj_key, proj_val) in projects {
let matches =
Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
if matches {
for (name, srv) in extract_servers_from_root(proj_val, None) {
map.insert(name, srv);
}
}
}
}
map
}
};
for name in spec.disabled_servers.iter() {
if let Some(srv) = servers.get_mut(name) {
srv.enabled = false;
}
}
servers
@@ -612,8 +878,8 @@ pub fn discover_external_sources(home_dir: Option<&Path>, workspace_root: Option
})
.collect();
out.push(McpExternalSource {
id: spec.id.to_owned(),
label: spec.label.to_owned(),
id: spec.id,
label: spec.label,
path: IpcPath(spec.path),
suggested_scope: spec.suggested_scope,
native_provider: spec.native_provider.map(str::to_owned),
@@ -641,7 +907,7 @@ pub fn apply_import_selected(
let mut by_source: BTreeMap<&str, BTreeMap<String, AgentMcpServer>> = BTreeMap::new();
for spec in &specs {
if selections.iter().any(|s| s.source_id == spec.id) {
by_source.insert(spec.id, read_source_servers(spec, workspace_root));
by_source.insert(spec.id.as_str(), read_source_servers(spec, workspace_root));
}
}
let target = match scope {
@@ -1370,4 +1636,125 @@ mod tests {
assert_eq!(workspace["events-sse"].transport, McpTransport::Sse);
assert_eq!(workspace["events-sse"].url.as_deref(), Some("https://sse.example.com/events"));
}
#[test]
fn discovers_and_imports_copilot_installed_plugin_mcp_servers() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let copilot = home.join(".copilot");
let azure_root = copilot.join("installed-plugins/_direct/azure-skills");
let inline_root = copilot.join("installed-plugins/awesome-copilot/inline-tools");
let disabled_root = copilot.join("installed-plugins/_direct/disabled-plug");
let outside_root = tmp.path().join("outside");
std::fs::create_dir_all(azure_root.join(".plugin")).unwrap();
std::fs::create_dir_all(inline_root.join(".claude-plugin")).unwrap();
std::fs::create_dir_all(&disabled_root).unwrap();
std::fs::create_dir_all(&outside_root).unwrap();
std::fs::write(
azure_root.join(".plugin/plugin.json"),
r#"{"name":"azure","version":"1.2.106","mcpServers":"./.mcp.json"}"#,
)
.unwrap();
std::fs::write(
azure_root.join(".mcp.json"),
r#"{"mcpServers":{"azure":{"command":"npx","args":["-y","@azure/mcp@latest","${COPILOT_PLUGIN_ROOT}/cfg"],"env":{"PLUG_DIR":"${CLAUDE_PLUGIN_ROOT}"}}}}"#,
)
.unwrap();
std::fs::write(
inline_root.join(".claude-plugin/plugin.json"),
r#"{"name":"inline-tools","version":"0.1.0","mcpServers":{"inline-srv":{"command":"${PLUGIN_ROOT}/bin/run","args":["--stdio"]},"muted-srv":{"command":"echo","args":["off"]}}}"#,
)
.unwrap();
std::fs::write(
disabled_root.join(".mcp.json"),
r#"{"mcpServers":{"never":{"command":"npx","args":["never"]}}}"#,
)
.unwrap();
std::fs::write(outside_root.join("secret.json"), r#"{"mcpServers":{"escaped":{"command":"sh"}}}"#).unwrap();
let escape_root = copilot.join("installed-plugins/_direct/escape-plug");
std::fs::create_dir_all(escape_root.join(".plugin")).unwrap();
std::fs::write(
escape_root.join(".plugin/plugin.json"),
r#"{"name":"escape-plug","mcpServers":"../../../../outside/secret.json"}"#,
)
.unwrap();
// `~/.copilot/config.json` includes leading `//` comments in Copilot CLI.
let config_json = format!(
"// Managed automatically.\n{}",
serde_json::json!({
"installedPlugins": [
{
"name": "azure",
"marketplace": "",
"enabled": true,
"cache_path": azure_root,
},
{
"name": "inline-tools",
"marketplace": "awesome-copilot",
"enabled": true,
"cache_path": inline_root,
},
{
"name": "disabled-plug",
"marketplace": "",
"enabled": false,
"cache_path": disabled_root,
},
{
"name": "escape-plug",
"marketplace": "",
"enabled": true,
"cache_path": escape_root,
}
]
})
);
std::fs::write(copilot.join("config.json"), config_json).unwrap();
std::fs::write(copilot.join("settings.json"), r#"{"disabledMcpServers":["muted-srv"]}"#).unwrap();
let sources = discover_external_sources(Some(&home), None);
assert_eq!(sources.len(), 2);
let azure_src = sources.iter().find(|s| s.id == "copilot-plugin:azure").unwrap();
assert_eq!(azure_src.label, "GitHub Copilot Plugin (azure)");
assert_eq!(azure_src.native_provider.as_deref(), Some("copilot"));
assert_eq!(azure_src.path.0, azure_root.join(".mcp.json"));
assert_eq!(azure_src.servers.len(), 1);
assert!(azure_src.servers[0].enabled);
assert_eq!(
azure_src.servers[0].args,
vec!["-y", "@azure/mcp@latest", &format!("{}/cfg", azure_root.display())]
);
let inline_src = sources.iter().find(|s| s.id == "copilot-plugin:awesome-copilot/inline-tools").unwrap();
assert_eq!(inline_src.label, "GitHub Copilot Plugin (inline-tools · awesome-copilot)");
assert_eq!(inline_src.path.0, inline_root.join(".claude-plugin/plugin.json"));
let active = inline_src.servers.iter().find(|s| s.name == "inline-srv").unwrap();
assert!(active.enabled);
assert_eq!(active.command.as_deref(), Some(format!("{}/bin/run", inline_root.display()).as_str()));
let muted = inline_src.servers.iter().find(|s| s.name == "muted-srv").unwrap();
assert!(!muted.enabled);
let mut user = BTreeMap::new();
let mut workspace = BTreeMap::new();
let imported = apply_import_selected(
&mut user,
&mut workspace,
Some(&home),
None,
McpScope::User,
&[McpImportSelection { source_id: "copilot-plugin:azure".into(), name: "azure".into() }],
false,
)
.unwrap();
assert_eq!(imported, vec!["azure".to_string()]);
assert_eq!(user["azure"].env.get("PLUG_DIR").map(String::as_str), Some(azure_root.to_str().unwrap()));
}
}
+2
Переглянути файл
@@ -672,6 +672,8 @@ pub enum AgentChangesView {
SinceStart,
/// The uncommitted files against `HEAD`; commits made since the start stay.
Group,
/// What the last turn changed, against the checkout as that turn started.
LastTurn,
}
/// A task's uncommitted files and the commits made since it started.
+182 -3
Переглянути файл
@@ -2852,7 +2852,10 @@ async fn task_project_root_controls_local_and_worktree_repositories() {
let changes = mgr.changes(&task.id).await.unwrap();
assert_eq!(changes.len(), 1);
assert_eq!(changes[0].path.0, task.cwd.0.join("file.txt"));
assert_eq!(mgr.base_text(&task.id, changes[0].path.0.clone()).await.unwrap().as_deref(), Some("original\n"));
assert_eq!(
mgr.base_text(&task.id, changes[0].path.0.clone(), AgentChangesView::SinceStart).await.unwrap().as_deref(),
Some("original\n")
);
let saved = std::fs::read(root.join("store").join(format!("{}.json", task.id))).unwrap();
assert!(String::from_utf8(saved).unwrap().contains("projectRoot"));
let mut old = serde_json::to_value(&task).unwrap();
@@ -3636,6 +3639,178 @@ async fn changed(mgr: &AgentManager, id: &str) -> Vec<String> {
mgr.changes(id).await.unwrap().into_iter().map(|c| c.rel_path).collect()
}
/// Waits until the turn asks for permission, runs `work` (what the agent does), then stops it.
async fn one_turn(mgr: &AgentManager, id: &str, prompt: Option<&str>, work: impl FnOnce()) {
if let Some(prompt) = prompt {
mgr.prompt(id, text(prompt), false).await.unwrap();
}
wait_for(mgr, id, AgentStatus::NeedsInput).await;
work();
mgr.cancel(id, None).unwrap();
wait_for(mgr, id, AgentStatus::Ready).await;
}
async fn turn_changed(mgr: &AgentManager, id: &str) -> Vec<(String, ide_vcs::ChangeKind, u32, u32)> {
let changes = mgr.turn_changes(id).await.unwrap();
changes.into_iter().map(|c| (c.rel_path, c.kind, c.added, c.removed)).collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn the_last_turn_lists_and_rolls_back_only_its_own_changes() {
use ide_vcs::ChangeKind::{Added, Deleted, Modified};
for isolation in [Isolation::Local, Isolation::Worktree] {
for eol in EOLS {
let repo = Checkout::new(eol);
repo.write("a.txt", "base\n");
repo.write("gone.txt", "base\n");
repo.write("mine.txt", "base\n");
repo.commit("init");
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
prompt: text("Hello"),
provider: "claude".into(),
isolation,
..Default::default()
})
.await
.unwrap();
let cwd = task.cwd.0.clone();
let write = |rel: &str, text: &str| {
let text = match eol {
Eol::Lf => text.to_owned(),
Eol::Crlf => text.replace('\n', "\r\n"),
};
std::fs::write(cwd.join(rel), text).unwrap();
};
let read = |rel: &str| std::fs::read_to_string(cwd.join(rel)).unwrap().replace("\r\n", "\n");
let case = format!("{isolation:?} {eol:?}");
assert!(mgr.turn_changes(&task.id).await.unwrap().is_empty(), "{case}: no turn has ended yet");
one_turn(&mgr, &task.id, None, || {
write("a.txt", "base\nturn 1\n");
write("one.txt", "one\n");
})
.await;
// The user's own work between the turns belongs to neither.
write("mine.txt", "base\nmine\n");
one_turn(&mgr, &task.id, Some("more"), || {
write("a.txt", "base\nturn 1\nturn 2\n");
write("one.txt", "one\ntwo\n");
write("two.txt", "two\n");
std::fs::remove_file(cwd.join("gone.txt")).unwrap();
})
.await;
// And after the turn.
write("later.txt", "mine\n");
assert_eq!(
turn_changed(&mgr, &task.id).await,
[
("a.txt".into(), Modified, 1, 0),
("gone.txt".into(), Deleted, 0, 1),
("one.txt".into(), Modified, 1, 0),
("two.txt".into(), Added, 1, 0),
],
"{case}"
);
let turn_base = |rel: &str| {
let path = cwd.join(rel);
let mgr = &mgr;
let id = task.id.clone();
async move {
let text = mgr.base_text(&id, path, AgentChangesView::LastTurn).await.unwrap();
text.map(|t| t.replace("\r\n", "\n"))
}
};
assert_eq!(turn_base("a.txt").await.as_deref(), Some("base\nturn 1\n"), "{case}");
assert_eq!(turn_base("gone.txt").await.as_deref(), Some("base\n"), "{case}");
assert_eq!(turn_base("two.txt").await, None, "{case}");
let whole: Vec<String> = changed(&mgr, &task.id).await;
assert!(["a.txt", "one.txt"].iter().all(|f| whole.iter().any(|w| w == f)), "{case}: {whole:?}");
// One file, then the rest, after a restart: from the copies saved as the turn started.
mgr.rollback_changes(&task.id, Some(vec!["one.txt".into()]), AgentChangesView::LastTurn).await.unwrap();
assert_eq!(read("one.txt"), "one\n", "{case}");
assert_eq!(turn_changed(&mgr, &task.id).await.len(), 3, "{case}");
mgr.shutdown();
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
mgr.rollback_changes(&task.id, None, AgentChangesView::LastTurn).await.unwrap();
assert_eq!(read("a.txt"), "base\nturn 1\n", "{case}");
assert_eq!(read("gone.txt"), "base\n", "{case}");
assert!(!cwd.join("two.txt").exists(), "{case}");
assert_eq!(read("mine.txt"), "base\nmine\n", "{case}: the user's edit between turns stays");
assert_eq!(read("later.txt"), "mine\n", "{case}: and the one after");
assert!(mgr.turn_changes(&task.id).await.unwrap().is_empty(), "{case}");
// The task's own changes from its first turn stay.
let whole: Vec<String> = changed(&mgr, &task.id).await;
assert!(["a.txt", "one.txt"].iter().all(|f| whole.iter().any(|w| w == f)), "{case}: {whole:?}");
mgr.delete(&task.id, true).await.unwrap();
assert!(!repo.dir.join("store").join(format!("{}.turn", task.id)).exists(), "{case}");
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn rolling_back_the_whole_task_leaves_the_last_turn_nothing_to_list() {
let repo = Checkout::new(Eol::Lf);
repo.write("a.txt", "base\n");
repo.commit("init");
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), ..Default::default() })
.await
.unwrap();
one_turn(&mgr, &task.id, None, || repo.write("a.txt", "base\nturn 1\n")).await;
one_turn(&mgr, &task.id, Some("more"), || repo.write("a.txt", "base\nturn 1\nturn 2\n")).await;
assert_eq!(turn_changed(&mgr, &task.id).await.len(), 1);
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
assert_eq!(repo.read("a.txt"), "base\n");
assert!(mgr.turn_changes(&task.id).await.unwrap().is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn a_commit_made_in_the_last_turn_is_among_its_changes() {
let repo = Checkout::new(Eol::Lf);
repo.write("a.txt", "base\n");
repo.commit("init");
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
prompt: text("Hello"),
provider: "claude".into(),
isolation: Isolation::Worktree,
..Default::default()
})
.await
.unwrap();
let cwd = task.cwd.0.clone();
let git = |args: &[&str]| {
let ok = std::process::Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
.args(args)
.current_dir(&cwd)
.status()
.unwrap()
.success();
assert!(ok, "{args:?}");
};
one_turn(&mgr, &task.id, None, || {
std::fs::write(cwd.join("a.txt"), "base\nagent\n").unwrap();
std::fs::write(cwd.join("new.txt"), "new\n").unwrap();
git(&["add", "."]);
git(&["commit", "-q", "-m", "agent"]);
})
.await;
let rel: Vec<String> = mgr.turn_changes(&task.id).await.unwrap().into_iter().map(|c| c.rel_path).collect();
assert_eq!(rel, ["a.txt", "new.txt"]);
mgr.rollback_changes(&task.id, None, AgentChangesView::LastTurn).await.unwrap();
assert_eq!(std::fs::read_to_string(cwd.join("a.txt")).unwrap(), "base\n");
assert!(!cwd.join("new.txt").exists());
mgr.delete(&task.id, true).await.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn work_uncommitted_by_a_reset_during_a_local_task_is_not_rolled_back() {
for eol in EOLS {
@@ -3652,7 +3827,7 @@ async fn work_uncommitted_by_a_reset_during_a_local_task_is_not_rolled_back() {
repo.git(&["reset", "-q", "--soft", "HEAD~1"]);
assert_eq!(changed(&mgr, &task.id).await, ["a.txt"], "{eol:?}");
let base = mgr.base_text(&task.id, repo.dir.join("a.txt")).await.unwrap();
let base = mgr.base_text(&task.id, repo.dir.join("a.txt"), AgentChangesView::SinceStart).await.unwrap();
assert_eq!(base.map(|b| b.replace("\r\n", "\n")).as_deref(), Some("base\n"), "{eol:?}");
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
assert_eq!(repo.read("a.txt"), "base\n", "{eol:?}");
@@ -3792,7 +3967,11 @@ async fn a_local_task_in_a_repository_without_commits_lists_and_rolls_back_its_c
let (mgr, task) = repo.task().await;
repo.write("new.txt", "agent\n");
assert_eq!(changed(&mgr, &task.id).await, ["new.txt"], "{eol:?}");
assert_eq!(mgr.base_text(&task.id, repo.dir.join("new.txt")).await.unwrap(), None, "{eol:?}");
assert_eq!(
mgr.base_text(&task.id, repo.dir.join("new.txt"), AgentChangesView::SinceStart).await.unwrap(),
None,
"{eol:?}"
);
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
assert!(!repo.dir.join("new.txt").exists(), "{eol:?}");
+249 -2
Переглянути файл
@@ -3,6 +3,7 @@
use crate::model::{AgentChange, AgentChanges, AgentCommit};
use ide_core::{IdeError, IdeResult, IpcPath};
use ide_vcs::{ChangeKind, LogQuery, Repo};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::time::{Duration, UNIX_EPOCH};
@@ -610,7 +611,6 @@ pub(crate) fn restore(
before: &BTreeMap<String, Stamp>,
saved: Option<&Path>,
) -> IdeResult<()> {
let path = &change.path.0;
let content = match before.get(&change.rel_path) {
Some(None) => None,
Some(Some(_)) => {
@@ -626,11 +626,16 @@ pub(crate) fn restore(
None => match rev {
Some(rev) => {
let repo = Repo::discover(cwd)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
repo.file_bytes_at(path, Some(rev))?
repo.file_bytes_at(&change.path.0, Some(rev))?
}
None => None,
},
};
put(&change.path.0, content)
}
/// Writes `content` to `path`, or removes the file when there is none.
fn put(path: &Path, content: Option<Vec<u8>>) -> IdeResult<()> {
match content {
Some(bytes) => {
if let Some(parent) = path.parent() {
@@ -646,6 +651,187 @@ pub(crate) fn restore(
Ok(())
}
/// The bytes of the copy of `rel` saved in `dir`, if there is one.
pub(crate) fn saved_copy(dir: &Path, rel: &str) -> Option<Vec<u8>> {
std::fs::read(dir.join(saved_name(rel))).ok()
}
/// The checkout as the task's last turn started: what that turn's changes are compared with
/// and rolled back to. Recorded like the task's own start: `HEAD`, the files already changed,
/// and copies of those.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct TurnStart {
/// `HEAD` then (`None` outside a repository or before its first commit).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub head: Option<String>,
/// The files already changed then, stamped.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub before: BTreeMap<String, Stamp>,
/// The files among `before` with a copy in the task's turn folder.
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
pub saved: BTreeSet<String>,
/// The files that changed while the turn ran, recorded as it ended (`None` while it runs).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub changed: Option<BTreeSet<String>>,
}
/// Records the checkout at `cwd` as a turn starts, with copies of its changed files in `dir`.
/// The copies `previous` saved of files unchanged since are kept rather than made again, so
/// starting a turn copies little more than what the turn before it changed.
pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -> IdeResult<TurnStart> {
let Some(repo) = discover(cwd)? else { return Ok(TurnStart::default()) };
let head = repo.head()?.1;
// As the turn's end is read, so the two compare.
let before = snapshot(cwd)?;
let mut saved = BTreeSet::new();
match previous {
Some(previous) => {
for rel in &previous.saved {
let unchanged =
before.get(rel).is_some_and(|now| now.is_some() && previous.before.get(rel) == Some(now));
if unchanged {
saved.insert(rel.clone());
} else {
let _ = std::fs::remove_file(dir.join(saved_name(rel)));
}
}
}
None => {
let _ = std::fs::remove_dir_all(dir);
}
}
for (rel, stamp) in &before {
let path = repo.root().join(rel);
if stamp.is_none()
|| saved.contains(rel)
|| !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
{
continue;
}
std::fs::create_dir_all(dir)?;
// One that can't be copied is listed but can't be rolled back, as a large one.
if std::fs::copy(&path, dir.join(saved_name(rel))).is_ok() {
saved.insert(rel.clone());
}
}
Ok(TurnStart { head, before, saved, changed: None })
}
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
/// `changed_between` sees them), and in the commits made since.
pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec<String>, BTreeSet<String>)> {
let end = snapshot(cwd)?;
let worktree = changed_between(&start.before, &end);
let mut all: BTreeSet<String> = worktree.iter().cloned().collect();
if let Some(repo) = discover(cwd)?
&& let (Some(from), Some(to)) = (&start.head, repo.head()?.1)
&& *from != to
{
for f in repo.diff_revisions(from, &to)? {
all.extend(f.old_path);
all.insert(f.path);
}
}
Ok((worktree, all))
}
/// The content of `rel` as the turn `start` began (`None`: no file), its copies in `dir`.
fn at_turn_start(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
match start.before.get(rel) {
Some(None) => Ok(None),
Some(Some(_)) => match start.saved.contains(rel).then(|| saved_copy(dir, rel)).flatten() {
Some(bytes) => Ok(Some(bytes)),
None => Err(IdeError::invalid(format!(
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
))),
},
None => match &start.head {
Some(head) => repo.file_bytes_at(&repo.root().join(rel), Some(head)),
None => Ok(None),
},
}
}
/// Added and removed lines from `old` to `new`; none for binary content.
fn line_stats(old: Option<&[u8]>, new: Option<&[u8]>) -> (u32, u32) {
if [old, new].iter().flatten().any(|b| b.contains(&0)) {
return (0, 0);
}
let text = |b: Option<&[u8]>| b.map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default();
ide_vcs::diff_hunks(&text(old), &text(new))
.iter()
.fold((0, 0), |(added, removed), h| (added + h.lines, removed + h.old_lines))
}
/// The files among `changed` that differ from how they were as the turn `start` began.
pub(crate) fn turn_changes(
cwd: &Path,
start: &TurnStart,
dir: &Path,
changed: &BTreeSet<String>,
) -> IdeResult<Vec<AgentChange>> {
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
let mut out = Vec::new();
for rel in changed {
let path = repo.root().join(rel);
// A folder (a submodule, say) or a file that can't be read has nothing to compare.
let Some(now) = existing(&path) else { continue };
let (kind, (added, removed)) = match at_turn_start(&repo, rel, start, dir) {
Ok(then) if then == now => continue,
Ok(then) => {
let kind = match (&then, &now) {
(None, _) => ChangeKind::Added,
(_, None) => ChangeKind::Deleted,
_ => ChangeKind::Modified,
};
(kind, line_stats(then.as_deref(), now.as_deref()))
}
// Its start wasn't saved: listed, without counts.
Err(_) => (ChangeKind::Modified, (0, 0)),
};
out.push(AgentChange { path: IpcPath(path), rel_path: rel.clone(), kind, added, removed, old_path: None });
}
Ok(out)
}
/// The text of `path` as the turn `start` began, `None` when there was no file.
pub(crate) fn turn_text(cwd: &Path, path: &Path, start: &TurnStart, dir: &Path) -> IdeResult<Option<String>> {
let Some(repo) = discover(cwd)? else { return Ok(None) };
let rel = rel_in(repo.root(), path)?;
if let (None, Some(head)) = (start.before.get(&rel), &start.head) {
return file_at(cwd, path, head);
}
let Some(bytes) = at_turn_start(&repo, &rel, start, dir)? else { return Ok(None) };
let encoding = match ide_vfs::load_text(path) {
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
Err(_) => ide_vfs::detect_encoding(&bytes, None),
};
Ok(Some(encoding.decode(&bytes).0.into_owned()))
}
/// `path` relative to the repository at `root`, with `/` separators.
fn rel_in(root: &Path, path: &Path) -> IdeResult<String> {
let rel = path
.strip_prefix(root)
.map(Path::to_path_buf)
.ok()
.or_else(|| {
// Another spelling of the same place (a link, `/var` and `/private/var`); the file may be gone.
let root = dunce::canonicalize(root).ok()?;
let parent = dunce::canonicalize(path.parent()?).ok()?;
Some(parent.strip_prefix(&root).ok()?.join(path.file_name()?))
})
.ok_or_else(|| IdeError::invalid(format!("{} is outside the repository", path.display())))?;
Ok(rel.components().map(|c| c.as_os_str().to_string_lossy()).collect::<Vec<_>>().join("/"))
}
/// Puts `change` back as it was when the turn `start` began.
pub(crate) fn restore_turn(cwd: &Path, start: &TurnStart, dir: &Path, change: &AgentChange) -> IdeResult<()> {
let repo = repo_at(cwd)?;
put(&change.path.0, at_turn_start(&repo, &change.rel_path, start, dir)?)
}
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
let Some(repo) = discover(cwd)? else { return Ok(None) };
let encoding = match ide_vfs::load_text(path) {
@@ -815,6 +1001,67 @@ mod tests {
assert!(!created.path.exists());
}
#[test]
fn a_turn_copies_only_what_changed_since_the_last_one() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("a.txt"), "base\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let dir = tmp.path().join("turn");
let set = |names: &[&str]| names.iter().map(|n| (*n).to_owned()).collect::<BTreeSet<_>>();
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
std::fs::write(repo.join("b.txt"), "b\n").unwrap();
let first = start_turn(&repo, &dir, None).unwrap();
assert_eq!(first.saved, set(&["a.txt", "b.txt"]));
// A copy made again would replace this mark.
std::fs::write(dir.join(saved_name("b.txt")), "kept\n").unwrap();
std::thread::sleep(std::time::Duration::from_millis(10));
std::fs::write(repo.join("a.txt"), "turn two\n").unwrap();
let second = start_turn(&repo, &dir, Some(&first)).unwrap();
assert_eq!(second.saved, set(&["a.txt", "b.txt"]));
assert_eq!(saved_copy(&dir, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"kept\n"[..]));
// Back as committed: nothing to keep a copy of.
git(&repo, &["checkout", "--", "a.txt"]);
let third = start_turn(&repo, &dir, Some(&second)).unwrap();
assert_eq!(third.saved, set(&["b.txt"]));
assert_eq!(saved_copy(&dir, "a.txt"), None);
// Without a record of the last turn (a task from before), every copy is made afresh.
let fresh = start_turn(&repo, &dir, None).unwrap();
assert_eq!(fresh.saved, set(&["b.txt"]));
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"b\n"[..]));
}
#[cfg(unix)]
#[test]
fn a_turns_start_is_found_through_another_spelling_of_the_checkout() {
let tmp = tempfile::tempdir().unwrap();
let repo = dunce::canonicalize(tmp.path()).unwrap().join("repo");
std::fs::create_dir(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("a.txt"), "base\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
let dir = tmp.path().join("turn");
let start = start_turn(&repo, &dir, None).unwrap();
std::fs::write(repo.join("a.txt"), "turn 2\n").unwrap();
std::fs::write(repo.join("new.txt"), "new\n").unwrap();
let link = tmp.path().join("link");
std::os::unix::fs::symlink(&repo, &link).unwrap();
for at in [&repo, &link] {
assert_eq!(turn_text(&repo, &at.join("a.txt"), &start, &dir).unwrap().as_deref(), Some("turn 1\n"));
assert_eq!(turn_text(&repo, &at.join("new.txt"), &start, &dir).unwrap(), None);
}
assert!(turn_text(&repo, &tmp.path().join("elsewhere.txt"), &start, &dir).is_err());
}
#[test]
fn commits_since_the_base_are_listed_with_their_files() {
let tmp = tempfile::tempdir().unwrap();
+19 -1
Переглянути файл
@@ -536,7 +536,9 @@ impl PathMap {
let abs = if p.is_absolute() {
p.to_path_buf()
} else {
let in_base = base.map(|b| Path::new(b).join(p)).filter(|c| c.exists());
// rustc prints workspace members' files relative to the workspace root, above
// the member's manifest directory (`base`) when a member is built on its own.
let in_base = base.and_then(|b| Path::new(b).ancestors().map(|a| a.join(p)).find(|c| c.exists()));
in_base.unwrap_or_else(|| cwd.join(p))
};
let abs = normalize(&abs);
@@ -1303,6 +1305,22 @@ mod tests {
assert_eq!(identifier_len("x é_1 c", 2), 3);
}
#[test]
fn resolves_a_member_build_s_workspace_relative_paths() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
write(&root, "client/src/main.rs", "fn main() {}\n");
write(&root, "client/src/lib.rs", "\n");
write(&root, "src/lib.rs", "\n");
let map = PathMap { root: root.clone(), canonical: None };
let member = root.join("client");
let base = member.to_str();
// Build Module runs in the member; rustc names its files from the workspace root.
assert_eq!(map.resolve("client/src/main.rs", &member, base), root.join("client/src/main.rs"));
// A crate built from its own directory names them from there.
assert_eq!(map.resolve("src/lib.rs", &member, base), member.join("src/lib.rs"));
}
// Uses Unix absolute paths for the canonical root.
#[cfg(unix)]
#[test]
+8
Переглянути файл
@@ -1875,6 +1875,14 @@ pub fn goto_declaration(text: &str, path: &Path, pos: Pos, local_repo: Option<Pa
goto_declaration_in(text, path, pos, local_repo, Vec::new)
}
/// The declaration of the property `name` in the pom at `path`, for files it configures
/// outside the pom itself (a YAML resource's `@name@`): the first `<properties>` entry
/// along the parent chain declaring it, `project.*` built-ins included.
pub fn property_declaration(pom: &Path, name: &str, local_repo: Option<PathBuf>) -> Option<PomGoto> {
let text = xml::read_text(pom)?;
property_target(&text, pom, name, local_repo)
}
/// [`goto_declaration`], where a `<parent>` and a dependency or plugin whose version no
/// management entry provides (or a management entry itself) go to the artifact's own
/// POM: the project module among `modules` with its coordinates, else the local
+117 -11
Переглянути файл
@@ -19,10 +19,16 @@ struct State {
settings: Vec<(String, String)>,
read_only: bool,
session_id: String,
session: Mutex<bool>,
session: Mutex<Session>,
closed: CancellationToken,
}
#[derive(Default)]
struct Session {
initialized: bool,
strict_read_only: bool,
}
/// The response format: a names line, a types line, then one JSON array per row, so rows past
/// the grid's limit are skipped without being parsed.
const FORMAT: &str = "JSONCompactEachRowWithNamesAndTypes";
@@ -109,12 +115,23 @@ impl ClickhousePool {
settings: setup.params,
read_only: source.read_only,
session_id: uuid::Uuid::new_v4().to_string(),
session: Mutex::new(false),
session: Mutex::new(Session::default()),
closed: CancellationToken::new(),
}));
let cancel = CancellationToken::new();
let initialize = async {
pool.execute("SELECT 1", 1, &cancel).await?;
if let Err(error) = pool.execute("SELECT 1", 1, &cancel).await {
if !rejects_driver_setting(&error) {
return Err(error);
}
// Retry only the connection probe. Keep relying on the server for write protection
// only after verifying strict read-only mode in this same session.
pool.0.session.lock().await.strict_read_only = true;
let result = pool.execute("SELECT getSetting('readonly')", 1, &cancel).await?;
if result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) != Some("1") {
return Err(error);
}
}
for sql in setup.statements {
pool.execute(&sql, 0, &cancel).await?;
}
@@ -151,7 +168,7 @@ impl ClickhousePool {
}
/// `max_rows`: the rows the server may send (the skipped ones included).
fn request(&self, client: &Client, query_id: &str, max_rows: usize, initialized: bool) -> RequestBuilder {
fn request(&self, client: &Client, query_id: &str, max_rows: usize, session: &Session) -> RequestBuilder {
let mut request = client
.post(self.0.endpoint.clone())
.basic_auth(&self.0.user, Some(&self.0.password))
@@ -162,16 +179,20 @@ impl ClickhousePool {
("session_timeout", "3600".into()),
("query_id", query_id.to_owned()),
("default_format", FORMAT.into()),
]);
if !session.strict_read_only {
request = request.query(&[
("output_format_json_quote_denormals", "1".into()),
("max_result_rows", max_rows.saturating_add(1).to_string()),
("result_overflow_mode", "break".into()),
]);
if initialized {
}
if session.initialized {
request = request.query(&[("session_check", "1")]);
} else {
request = request.query(&[("database", &self.0.database)]);
}
if self.0.read_only {
if self.0.read_only && !session.strict_read_only {
request = request.query(&[("readonly", "1")]);
}
request
@@ -200,7 +221,7 @@ impl ClickhousePool {
};
let client = self.client()?;
let query_id = uuid::Uuid::new_v4().to_string();
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), *session).body(sql.to_owned());
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), &session).body(sql.to_owned());
let started = Instant::now();
let fetch = async {
let mut response = request.send().await.map_err(http_error)?;
@@ -254,7 +275,7 @@ impl ClickhousePool {
match result {
Some(result) => {
if result.is_ok() {
*session = true;
session.initialized = true;
}
result
}
@@ -323,9 +344,9 @@ type DecodedResult = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, bool);
/// Decodes a streamed [`FORMAT`] body. Reads past the first `skip` rows unparsed (a later
/// page), then keeps `max_rows` rows; later rows only set `has_more` and are read past
/// unparsed, so a grid limit bounds memory however large the block
/// `result_overflow_mode=break` lets the server send. A line that is not a JSON array
/// starts the exception ClickHouse writes when a query fails mid-stream.
/// unparsed, so a grid limit bounds memory even if a strict read-only server does not allow
/// per-query result limits. A line that is not a JSON array starts the exception ClickHouse
/// writes when a query fails mid-stream.
struct RowReader {
skip: usize,
max_rows: usize,
@@ -479,6 +500,20 @@ fn read_pem(path: &str, label: &str) -> IdeResult<Vec<u8>> {
.map_err(|error| IdeError::new(ErrorKind::Io, format!("cannot read ClickHouse {label}: {error}")))
}
fn rejects_driver_setting(error: &IdeError) -> bool {
error
.message
.split_once(": ")
.and_then(|(_, detail)| detail.strip_prefix("Code: 164. DB::Exception: Cannot modify '"))
.and_then(|detail| detail.split_once("' setting in readonly mode"))
.is_some_and(|(name, _)| {
matches!(
name,
"output_format_json_quote_denormals" | "max_result_rows" | "result_overflow_mode" | "readonly"
)
})
}
fn reserved_setting(name: &str) -> bool {
let name = name.to_ascii_lowercase();
name.starts_with("output_format_json_")
@@ -726,6 +761,77 @@ mod tests {
task.await.unwrap();
}
#[tokio::test]
async fn connects_when_server_forbids_settings_in_readonly_mode() {
let (port, requests) = server(vec![
(
"500 Internal Server Error",
"X-ClickHouse-Exception-Code: 164\r\n",
"Code: 164. DB::Exception: Cannot modify 'output_format_json_quote_denormals' setting in readonly mode. (READONLY)",
),
("200 OK", "", ONE),
("200 OK", "", "[\"n\"]\n[\"UInt64\"]\n[1]\n[2]\n"),
])
.await;
let source = DataSource {
read_only: true,
properties: vec![DbProperty { name: "max_threads".into(), value: "2".into() }],
..source(port)
};
let pool = Pool::connect(&source, None, None).await.unwrap();
let result = pool.execute("SELECT number FROM numbers(2)", 1, &CancellationToken::new()).await.unwrap();
assert_eq!(result.rows, vec![vec![Some("1".into())]]);
assert!(result.has_more);
let requests = requests.await.unwrap();
assert!(requests[0].ends_with("SELECT 1"));
assert!(requests[0].contains("output_format_json_quote_denormals=1"));
assert!(requests[1].ends_with("SELECT getSetting('readonly')"));
assert!(requests[2].contains("session_check=1"));
for request in &requests[1..] {
assert!(request.contains("default_format=JSONCompactEachRowWithNamesAndTypes"));
assert!(request.contains("max_threads=2"));
for setting in
["output_format_json_quote_denormals=", "max_result_rows=", "result_overflow_mode=", "readonly="]
{
assert!(!request.contains(setting), "{setting} is not allowed in a strict read-only session");
}
}
}
#[tokio::test]
async fn readonly_probe_does_not_disable_settings_on_a_writable_session() {
let (port, requests) = server(vec![
(
"500 Internal Server Error",
"X-ClickHouse-Exception-Code: 164\r\n",
"Code: 164. DB::Exception: Cannot modify 'max_result_rows' setting in readonly mode. (READONLY)",
),
("200 OK", "", "[\"readonly\"]\n[\"UInt64\"]\n[0]\n"),
])
.await;
let source = DataSource { read_only: true, ..source(port) };
let error = Pool::connect(&source, None, None).await.err().expect("writable session must stay rejected");
assert!(error.message.contains("Cannot modify 'max_result_rows'"));
assert!(requests.await.unwrap()[1].ends_with("SELECT getSetting('readonly')"));
}
#[test]
fn readonly_probe_matches_only_the_driver_settings() {
for (code, setting, expected) in [
(164, "max_result_rows", true),
(164, "result_overflow_mode", true),
(164, "readonly", true),
(164, "max_threads", false),
(516, "max_result_rows", false),
] {
let error = IdeError::invalid(format!(
"ClickHouse HTTP 500: Code: {code}. DB::Exception: Cannot modify '{setting}' setting in readonly mode. (READONLY)"
));
assert_eq!(rejects_driver_setting(&error), expected, "{setting}");
}
}
#[tokio::test]
async fn server_errors_keep_details_and_hide_passwords() {
let (port, requests) = server(vec![(
+31
Переглянути файл
@@ -916,6 +916,37 @@ impl DbManager {
self.tunnels.lock().remove(id);
}
/// Creates a database on the server of data source `id` by running `statement` on the data
/// source's own database, after closing the IDE's connections to `template`, the database
/// the server copies (PostgreSQL and SQL Server refuse to copy one that has sessions).
pub async fn create_database(&self, id: &str, template: &str, statement: &str) -> IdeResult<()> {
let id = split_target(id).0;
if self.source(id)?.read_only {
return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only"));
}
self.disconnect(&format!("{id}:{template}")).await;
self.pool(id).await?.execute(statement, 0, &CancellationToken::new()).await?;
self.remember_statement(id, statement);
Ok(())
}
/// Drops `database` of the server of data source `id` by running `statement` on the data
/// source's own database, after closing the IDE's connections to `database`.
/// Refuses the database the data source connects to and read-only data sources.
pub async fn drop_database(&self, id: &str, database: &str, statement: &str) -> IdeResult<()> {
let id = split_target(id).0;
if self.source(id)?.read_only {
return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only"));
}
if self.databases(id).await?.current == database {
return Err(IdeError::invalid(format!("the data source connects to {database}; it cannot drop it")));
}
self.disconnect(&format!("{id}:{database}")).await;
self.pool(id).await?.execute(statement, 0, &CancellationToken::new()).await?;
self.remember_statement(id, statement);
Ok(())
}
/// The databases of the server of data source `id` (PostgreSQL), the connected one first.
pub async fn databases(&self, id: &str) -> IdeResult<Databases> {
let id = split_target(id).0;
+38
Переглянути файл
@@ -230,6 +230,44 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
}
/// Runs `job` with the newest installed copy of its tool, the way the dialogs do.
#[tokio::test]
async fn drops_a_database_the_ide_holds_connections_to() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
db.execute("p", "DROP DATABASE IF EXISTS oi_drop_me", 0, &c).await?;
db.execute("p", "CREATE DATABASE oi_drop_me TEMPLATE template0", 0, &c).await?;
// What the tree and a manual-commit console leave open on the database.
db.schemas("p:oi_drop_me").await?;
db.set_manual_commit("p:oi_drop_me", true).await?;
db.execute("p:oi_drop_me", "SELECT 1", 1, &c).await?;
db.drop_database("p", "oi_drop_me", "drop database oi_drop_me").await?;
assert!(!db.is_connected("p:oi_drop_me"));
assert!(!db.databases("p").await?.names.iter().any(|n| n == "oi_drop_me"));
let current = db.databases("p").await?.current;
let refused = db.drop_database("p", &current, &format!("drop database \"{current}\"")).await;
assert!(refused.is_err());
Ok(())
}
#[tokio::test]
async fn creates_a_database_from_a_template_the_ide_holds_connections_to() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
db.execute("p", "DROP DATABASE IF EXISTS oi_from_template", 0, &c).await?;
db.schemas("p:template1").await?;
db.create_database("p", "template1", "create database oi_from_template").await?;
assert!(!db.is_connected("p:template1"));
assert!(db.databases("p").await?.names.iter().any(|n| n == "oi_from_template"));
db.execute("p", "DROP DATABASE oi_from_template", 0, &c).await?;
Ok(())
}
async fn run_tool(db: &DbManager, target: &str, job: ide_db::tools::DbToolJob) -> IdeResult<()> {
let install = ide_db::tools::find_installs(job.tool()).into_iter().next().expect("installed");
let mut lines = Vec::new();
+41
Переглянути файл
@@ -95,3 +95,44 @@ async fn sqlserver_values_paging_transactions_and_cancellation() {
task.await.unwrap();
assert_eq!(pool.rows("SELECT 1", 1).await.unwrap()[0][0].as_deref(), Some("1"));
}
#[tokio::test]
async fn sqlserver_creates_from_a_held_model_and_force_drops_a_held_database() {
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
let mut parts = server.splitn(4, ':');
let (host, port, user, password) = (
parts.next().unwrap(),
parts.next().unwrap().parse().unwrap(),
parts.next().unwrap(),
parts.next().unwrap_or(""),
);
let source = |database: &str| DataSource {
id: "s".into(),
name: "sqlserver".into(),
driver: DbDriver::SqlServer,
host: host.into(),
port: Some(port),
user: user.into(),
database: database.into(),
ssl: DbSslMode::Disable,
..Default::default()
};
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
let db = ide_db::DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
db.save_sources(vec![source("master")]).await.unwrap();
db.set_password("s", Some(password.into()), false).await.unwrap();
let name = format!("oi_force_drop_{}", std::process::id());
// The tree's connection to `model` would keep SQL Server from copying it.
db.schemas("s:model").await.unwrap();
db.create_database("s", "model", &format!("create database {name};")).await.unwrap();
assert!(!db.is_connected("s:model"));
let other = Pool::connect(&source(&name), Some(password), None).await.unwrap();
let held = Held::acquire(&other).await.unwrap();
let force = format!("alter database {name} set single_user with rollback immediate;\ndrop database {name};");
db.drop_database("s", &name, &force).await.unwrap();
assert!(!db.databases("s").await.unwrap().names.contains(&name));
drop(held);
}
+1 -1
Переглянути файл
@@ -236,7 +236,7 @@ impl Tool {
destructive: false,
output_schema: None,
input_schema: json!({ "type": "object", "properties": {
"projectPath": { "type": "string", "description": "Any directory inside an open project. Optional when only one project is open." }
"projectPath": { "type": "string", "description": "Any directory inside an open project. Defaults to the connection's project (`?project=`) or the only open one." }
}, "required": [] }),
},
handler: Arc::new(move |call| Box::pin(handler(call))),
+22 -5
Переглянути файл
@@ -369,10 +369,21 @@ pub async fn agent_delete(host: &Host, window: &str, task: String, remove_worktr
host.project(window)?.agents.delete(&task, remove_worktree).await
}
/// The task's changed files as `view` compares them (without: since it started).
#[command(trust = trusted)]
pub async fn agent_changes(host: &Host, window: &str, task: String) -> IdeResult<Vec<AgentChange>> {
pub async fn agent_changes(
host: &Host,
window: &str,
task: String,
view: Option<AgentChangesView>,
) -> IdeResult<Vec<AgentChange>> {
host.require_trust(window)?;
host.project(window)?.agents.changes(&task).await
let agents = &host.project(window)?.agents;
match view.unwrap_or_default() {
AgentChangesView::SinceStart => agents.changes(&task).await,
AgentChangesView::Group => Ok(agents.grouped_changes(&task).await?.uncommitted),
AgentChangesView::LastTurn => agents.turn_changes(&task).await,
}
}
/// The task's uncommitted changes and the commits made since it started.
@@ -382,11 +393,17 @@ pub async fn agent_grouped_changes(host: &Host, window: &str, task: String) -> I
host.project(window)?.agents.grouped_changes(&task).await
}
/// Content of `path` when the task started (left side of its diff).
/// Content of `path` as `view` compares it (without: when the task started), the left side of its diff.
#[command(trust = trusted)]
pub async fn agent_base_text(host: &Host, window: &str, task: String, path: IpcPath) -> IdeResult<Option<String>> {
pub async fn agent_base_text(
host: &Host,
window: &str,
task: String,
path: IpcPath,
view: Option<AgentChangesView>,
) -> IdeResult<Option<String>> {
host.require_trust(window)?;
host.project(window)?.agents.base_text(&task, path.into_path_buf()).await
host.project(window)?.agents.base_text(&task, path.into_path_buf(), view.unwrap_or_default()).await
}
/// Rollback: the task's changed files among `paths` (all without) back as `view` compares them.
+28
Переглянути файл
@@ -139,6 +139,32 @@ pub async fn db_disconnect(host: &Host, window: &str, id: String) -> IdeResult<(
Ok(())
}
#[command(trust = trusted)]
pub async fn db_create_database(
host: &Host,
window: &str,
id: String,
template: String,
statement: String,
) -> IdeResult<()> {
// Creates a database on the server of data source `id` with `statement`, copied from `template` (New › Database).
let db = host.project(window)?.db.clone();
db.create_database(&id, &template, &statement).await
}
#[command(trust = trusted)]
pub async fn db_drop_database(
host: &Host,
window: &str,
id: String,
database: String,
statement: String,
) -> IdeResult<()> {
// Drops `database` of the server of data source `id` with `statement` (Drop… on a database node).
let db = host.project(window)?.db.clone();
db.drop_database(&id, &database, &statement).await
}
#[command(trust = trusted)]
pub async fn db_databases(host: &Host, window: &str, id: String) -> IdeResult<Databases> {
// Databases of the server of data source `id` (PostgreSQL); connect to one as `<id>:<database>`.
@@ -478,10 +504,12 @@ ide_command::domain!(
db_connected,
db_console_path,
db_consoles,
db_create_database,
db_database_catalog,
db_databases,
db_ddl,
db_disconnect,
db_drop_database,
db_execute,
db_explain,
db_finish_transaction,
+15 -3
Переглянути файл
@@ -359,10 +359,22 @@ pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: Got
if kind != GotoKind::Definition {
return result;
}
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Definition) else { return result };
// A Maven placeholder (`@profileActive@` in `application.yml` or `.properties`) navigates to its pom.
let maven = super::maven_placeholder::definition(host, window, doc, pos).await;
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Definition) else {
return match maven {
None => result,
Some(found) => {
let in_string = in_string_literal(host, window, doc, pos).await;
definition_targets(result, vec![found], in_string)
}
};
};
let found = plugin_call(move || plugins.provide_definition(&d, pos)).await.unwrap_or_default();
let found: Vec<Location> =
found.into_iter().map(|l| Location { path: l.path.into(), range: l.range, uri: None }).collect();
let found: Vec<Location> = maven
.into_iter()
.chain(found.into_iter().map(|l| Location { path: l.path.into(), range: l.range, uri: None }))
.collect();
let in_string = !found.is_empty() && in_string_literal(host, window, doc, pos).await;
definition_targets(result, found, in_string)
}
+154
Переглянути файл
@@ -0,0 +1,154 @@
//! ⌘B on a Maven resource-filtering placeholder: `@property@` in a YAML or properties
//! resource (Spring's `application.yml` / `application.properties`) jumps to the `<properties>` entry that defines it,
//! in the nearest `pom.xml` above the file, up through the project root. Parent
//! poms the nearest pom declares itself are followed from there; a parent outside
//! that walk that no pom declares is not.
use super::doc::blocking;
use crate::Host;
use ide_build::maven;
use ide_core::{DocId, Location, Pos};
use std::path::Path;
/// The definition location of the placeholder under `pos` in `doc`, when `doc` is a
/// YAML or properties file holding a `@token@` there and a pom above it defines that property.
pub(crate) async fn definition(host: &Host, window: &str, doc: DocId, pos: Pos) -> Option<Location> {
let project = host.project(window).ok()?;
blocking(move || {
let snap = project.documents.text_snapshot(doc)?;
if snap.large || !matches!(snap.language.as_str(), "yaml" | "properties") {
return Ok(None);
}
let path = project.documents.identity(doc)?.0;
let Some((name, _token_at)) = placeholder_at(&snap.text, pos) else { return Ok(None) };
Ok(pom_defining(&project.root, &path, &name))
})
.await
.ok()
.flatten()
}
/// The `@token@` enclosing `pos` on its line, with the token's range (UTF-16 columns).
fn placeholder_at(text: &str, pos: Pos) -> Option<(String, ide_core::Range)> {
let line = text.split_inclusive('\n').nth(pos.line as usize)?;
let line = line.trim_end_matches(['\n', '\r']);
let cursor = utf16_to_byte(line, pos.col)?;
let mut opener: Option<usize> = None;
for (i, b) in line.as_bytes().iter().enumerate() {
if *b != b'@' {
continue;
}
if let Some(start) = opener.replace(i) {
let token = &line[start + 1..i];
let valid =
!token.is_empty() && token.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'));
if valid && start <= cursor && cursor <= i {
let col = |byte: usize| line[..byte].encode_utf16().count() as u32;
return Some((
token.to_owned(),
ide_core::Range::new(Pos::new(pos.line, col(start)), Pos::new(pos.line, col(i + 1))),
));
}
opener = None;
}
}
None
}
/// The nearest `pom.xml` above `from` (up to and including `root`) defining `name`.
fn pom_defining(root: &Path, from: &Path, name: &str) -> Option<Location> {
let mut dir = from.parent()?.to_path_buf();
loop {
let pom = dir.join("pom.xml");
if pom.is_file()
&& let Some(found) = maven::property_declaration(&pom, name, maven::default_local_repo())
{
return Some(Location::file(found.path, found.range));
}
if dir == root || !dir.starts_with(root) {
return None;
}
dir = dir.parent()?.to_path_buf();
}
}
/// UTF-16 column → byte offset within one line.
fn utf16_to_byte(line: &str, col: u32) -> Option<usize> {
let col = col as usize;
let mut units = 0usize;
for (byte, c) in line.char_indices() {
if units == col {
return Some(byte);
}
units += c.len_utf16();
if units > col {
return None;
}
}
(units == col).then_some(line.len())
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::Pos;
fn at(line: u32, col: u32) -> Pos {
Pos::new(line, col)
}
#[test]
fn finds_the_placeholder_under_the_cursor_and_its_range() {
let text = "spring:\n profiles:\n active: @profileActive@\n";
let (name, range) = placeholder_at(text, at(2, 20)).unwrap();
assert_eq!(name, "profileActive");
assert_eq!(range.start, at(2, 12));
assert_eq!(range.end, at(2, 27));
// The `@`s themselves and inside the token navigate; just past the token does not.
for col in [12u32, 13, 26] {
assert_eq!(placeholder_at(text, at(2, col)).unwrap().0, "profileActive");
}
// A second pair on the line and unrelated cursors stay unresolved.
let multi = "a: @one@ @two@\n";
assert_eq!(placeholder_at(multi, at(0, 4)).unwrap().0, "one");
assert_eq!(placeholder_at(multi, at(0, 10)).unwrap().0, "two");
assert!(placeholder_at(multi, at(0, 8)).is_none(), "between the pairs");
assert!(placeholder_at(multi, at(0, 9)).is_some(), "the opening @ of the next pair");
assert!(placeholder_at(multi, at(0, 14)).is_none(), "just past the last pair");
assert!(placeholder_at("value: plain\n", at(0, 7)).is_none());
}
#[test]
fn the_nearest_pom_wins_and_the_walk_stops_at_the_project_root() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let root = base.join("project");
let deep = root.join("core/src/main/resources");
std::fs::create_dir_all(&deep).unwrap();
std::fs::write(
root.join("pom.xml"),
"<project>\n <properties>\n <parentName>parent</parentName>\n </properties>\n</project>\n",
)
.unwrap();
std::fs::create_dir_all(root.join("core")).unwrap();
std::fs::write(
root.join("core/pom.xml"),
"<project>\n <properties>\n <name>module</name>\n </properties>\n</project>\n",
)
.unwrap();
let from = deep.join("application.yml");
// The module pom defines `name` first: its file wins, pointing at its `<name>` entry.
let found = pom_defining(&root, &from, "name").unwrap();
assert_eq!(found.path, root.join("core/pom.xml"));
assert_eq!(found.range.start.line, 2);
// A property only the parent defines resolves there; unknown ones resolve nowhere.
let parent = pom_defining(&root, &from, "parentName").unwrap();
assert_eq!(parent.path, root.join("pom.xml"));
assert_eq!(parent.range.start.line, 2);
assert!(pom_defining(&root, &from, "missing").is_none());
// A file outside the project root has no pom walk.
let outside = tmp.path().join("elsewhere/application.yml");
std::fs::create_dir_all(tmp.path().join("elsewhere")).unwrap();
assert!(pom_defining(&root, &outside, "name").is_none());
}
}
+1
Переглянути файл
@@ -21,6 +21,7 @@ pub mod history;
pub mod java;
pub mod jvm_icons;
pub mod lsp;
pub mod maven_placeholder;
pub mod nav;
pub mod notebook;
pub mod project;
+6 -3
Переглянути файл
@@ -15,6 +15,9 @@ impl ReplaceHost for DocumentsHost<'_> {
Some(doc) => (doc, false),
None => (docs.open(path)?.id, true),
};
// A buffer without unsaved changes (open only for the search preview, or a clean
// tab) is saved like a closed file; one the user is editing is left unsaved.
let save = transient || !docs.is_dirty(doc)?;
let result = (|| {
// Recompute if the user typed between reading the text and applying.
for _ in 0..3 {
@@ -27,7 +30,7 @@ impl ReplaceHost for DocumentsHost<'_> {
continue;
}
docs.apply_edits(doc, &edits)?;
if transient {
if save {
docs.save(doc)?;
}
return Ok(edits.len() as u32);
@@ -46,8 +49,8 @@ impl ReplaceHost for DocumentsHost<'_> {
///
/// Edits go through the document layer as one patch per file, so open editors
/// update live and undo the whole file's replacements in one step. Unsaved
/// editor buffers are replaced in place and left unsaved; files that were not
/// open are opened transiently, saved and closed.
/// editor buffers are replaced in place and left unsaved; other open documents
/// are saved, and files that were not open are opened transiently, saved and closed.
///
/// With `all_in_scope` (Replace All after the search hit its match limit) the
/// scope is searched again without the limit and every match in it is replaced,
+35 -5
Переглянути файл
@@ -286,6 +286,8 @@ impl Host {
effective.languages.java.gradle.linked_projects.as_deref(),
build_files.as_deref(),
);
// After the import settings: they extend the workspace folder's name.
ide_sdk::jdtls_workspaces::use_own_temp(cfg, &data_dir);
}
}));
}
@@ -322,7 +324,7 @@ impl Host {
let syntax = Arc::new(SyntaxCache::new(self.syntax()));
documents.add_observer(Arc::new(SyntaxObserver(syntax.clone())));
documents.add_observer(Arc::new(LspObserver(lsp.clone())));
documents.add_observer(Arc::new(HistoryObserver(history.clone())));
documents.add_observer(Arc::new(HistoryObserver::new(history.clone())));
documents.add_observer(Arc::new(DeployObserver {
remote: self.remote.clone(),
settings: settings.clone(),
@@ -783,7 +785,7 @@ impl Host {
lsp.set_servers_hook(Box::new(|_, _| Vec::new()));
let syntax = Arc::new(SyntaxCache::new(self.syntax()));
documents.add_observer(Arc::new(SyntaxObserver(syntax.clone())));
documents.add_observer(Arc::new(HistoryObserver(history.clone())));
documents.add_observer(Arc::new(HistoryObserver::new(history.clone())));
let watcher = match watch_dir {
Some(dir) => light_watcher(dir, &sink, &documents, &history)?,
// A quiet private folder stands in until the first save brings a
@@ -1888,14 +1890,42 @@ impl DocumentObserver for SyntaxObserver {
}
}
struct HistoryObserver(Arc<LocalHistory>);
struct HistoryObserver {
history: Arc<LocalHistory>,
/// Documents edited since they were opened: only the first edit looks for a missing original.
edited: Mutex<HashSet<ide_core::DocId>>,
}
impl HistoryObserver {
fn new(history: Arc<LocalHistory>) -> Self {
Self { history, edited: Mutex::default() }
}
}
impl DocumentObserver for HistoryObserver {
fn saved(&self, _doc: ide_core::DocId, path: &Path, text: &str) {
if let Err(e) = self.0.record(path, text, "Saved") {
fn changed(
&self,
doc: ide_core::DocId,
path: &Path,
_version: u32,
_changes: &[AppliedChange],
_full_text: &dyn Fn() -> String,
) {
// The file on disk still has its content from before the edit.
if self.edited.lock().insert(doc)
&& let Err(e) = self.history.record_original(path)
{
tracing::warn!("local history: {e}");
}
}
fn saved(&self, _doc: ide_core::DocId, path: &Path, text: &str) {
if let Err(e) = self.history.record(path, text, "Saved") {
tracing::warn!("local history: {e}");
}
}
fn closed(&self, doc: ide_core::DocId, _path: &Path) {
self.edited.lock().remove(&doc);
}
}
/// Uploads saved files: remote files' local copies, and automatic upload to the default server.
+11 -5
Переглянути файл
@@ -879,16 +879,15 @@ fn background_tasks_scale_and_renew_cpu_fuel_budget() {
// Room for activation (about 3_100 on macOS, more on Windows). A background task gets ten
// times it (5 s / 500 ms): enough for each step of `patient` with its CPU work (32_000 to
// 80_000), not for the whole run without the refill on each report.
let f = fixture(Limits {
let limits = Limits {
fuel: 40_000,
timeout: Duration::from_millis(500),
background: Duration::from_millis(5_000),
..Limits::default()
});
};
let f = fixture(limits);
f.install(&misbehave_pkg());
if f.host.set_capability("misbehave", "process:git", true).is_err() {
return;
}
f.host.set_capability("misbehave", "process:git", true).expect("grant Git capability");
// Warm up activation in its own call so `patient` starts with a fresh budget.
assert_eq!(f.run("misbehave", "echo", Some("warm")).unwrap().as_deref(), Some("warm"));
@@ -897,6 +896,13 @@ fn background_tasks_scale_and_renew_cpu_fuel_budget() {
let err = f.run("misbehave", "spin", None).unwrap_err();
assert!(err.contains("exceeded its CPU budget (40000 fuel per call)"), "{err}");
// Beginning a task alone must not renew its scaled budget.
let quiet = fixture(limits);
quiet.install(&misbehave_pkg());
quiet.host.set_capability("misbehave", "process:git", true).expect("grant Git capability");
let err = quiet.run("misbehave", "patient", Some("quiet:4000")).unwrap_err();
assert!(err.contains("exceeded its CPU budget (400000 fuel per call)"), "{err}");
}
#[test]
+49
Переглянути файл
@@ -146,3 +146,52 @@ async fn replace_all_covers_matches_past_the_limit() {
host.close_project("main");
}
}
/// #4202: a file the search preview holds open (no unsaved changes) is saved like a closed
/// one; a buffer with unsaved edits is replaced in place and left for the editor to save.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn replace_all_saves_open_buffers_without_unsaved_changes() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
for name in ["previewed.txt", "edited.txt", "closed.txt"] {
std::fs::write(root.join(name), "TOKEN\n").unwrap();
}
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let project = host.project("main").unwrap();
project.documents.open(&root.join("previewed.txt")).unwrap();
let edited = project.documents.open(&root.join("edited.txt")).unwrap().id;
project.documents.replace_all(edited, "TOKEN\nmore\n").unwrap();
ops::search::replace_in_files(
&host,
"main",
RequestId::next(),
query("TOKEN", false),
"DONE".into(),
false,
vec![],
true,
ops::Channel::new(|_| {}),
)
.await
.unwrap();
let disk = |name: &str| std::fs::read_to_string(root.join(name)).unwrap();
assert_eq!(disk("previewed.txt"), "DONE\n");
assert_eq!(disk("closed.txt"), "DONE\n");
assert_eq!(disk("edited.txt"), "TOKEN\n", "unsaved edits stay unsaved");
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
host.close_project("main");
}
+53
Переглянути файл
@@ -65,6 +65,28 @@ pub(crate) fn lenient_diagnostics(server: &str, items: Value) -> Vec<lsp::Diagno
parsed
}
/// rust-analyzer publishes its own analysis next to `cargo check`'s (flycheck): one type
/// mismatch then arrives as `rust-analyzer(E0308)` and `rustc(E0308)`. Its own entry is
/// dropped when the compiler reports the same code and severity over an overlapping range.
fn drop_compiler_duplicates(diagnostics: &mut Vec<lsp::Diagnostic>) {
let overlaps = |a: &lsp::Range, b: &lsp::Range| a.start <= b.end && b.start <= a.end;
let compiler: Vec<(lsp::Range, Option<lsp::NumberOrString>, Option<lsp::DiagnosticSeverity>)> = diagnostics
.iter()
.filter(|d| d.source.as_deref() == Some("rustc") && d.code.is_some())
.map(|d| (d.range, d.code.clone(), d.severity))
.collect();
if compiler.is_empty() {
return;
}
diagnostics.retain(|d| {
d.source.as_deref() != Some("rust-analyzer")
|| d.code.is_none()
|| !compiler
.iter()
.any(|(range, code, severity)| code == &d.code && severity == &d.severity && overlaps(range, &d.range))
});
}
impl ClientHandler {
pub fn new(mgr: Weak<LspManager>, server: Arc<Server>, generation: u64) -> Self {
Self { mgr, server, generation }
@@ -293,11 +315,20 @@ impl ClientHandler {
}
};
params.diagnostics = lenient_diagnostics(&self.server.name, raw.unwrap_or(Value::Null));
drop_compiler_duplicates(&mut params.diagnostics);
let Some(path) = uri_to_path(params.uri.as_str())
.or_else(|| crate::notebook::is_cell_uri(params.uri.as_str()).then(|| PathBuf::from(params.uri.as_str())))
else {
return;
};
if self.server.name == crate::compose::SERVER {
// Maven resource-filtering placeholders (`@profileActive@`) parse as invalid
// YAML but are replaced before the file is ever read: their parser error is noise.
let text = mgr.docs.lock().values().find(|d| d.path == path).map(|d| d.text.as_str().to_owned());
if let Some(text) = text {
params.diagnostics.retain(|d| !crate::maven_placeholder::false_positive(&text, d));
}
}
if self.server.name == "jdtls"
&& let Some(failure) = crate::jdtls::build_plan_failure(&path, &self.server.root, &params.diagnostics)
{
@@ -701,6 +732,28 @@ mod tests {
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
#[test]
fn rust_analyzer_s_own_entry_yields_to_the_compiler_s_for_the_same_error() {
let diagnostic = |source: &str, code: &str, line: u32, severity| lsp::Diagnostic {
range: lsp::Range::new(lsp::Position::new(line, 21), lsp::Position::new(line, 27)),
severity: Some(severity),
code: Some(lsp::NumberOrString::String(code.into())),
source: Some(source.into()),
message: format!("{source} {code}"),
..Default::default()
};
let error = lsp::DiagnosticSeverity::ERROR;
let mut items = vec![
diagnostic("rust-analyzer", "E0308", 1, error),
diagnostic("rustc", "E0308", 1, error),
diagnostic("rust-analyzer", "E0308", 5, error),
diagnostic("rust-analyzer", "unused_variables", 1, lsp::DiagnosticSeverity::WARNING),
];
drop_compiler_duplicates(&mut items);
let left: Vec<_> = items.iter().map(|d| (d.message.as_str(), d.range.start.line)).collect();
assert_eq!(left, [("rustc E0308", 1), ("rust-analyzer E0308", 5), ("rust-analyzer unused_variables", 1)]);
}
#[test]
fn tsserver_aborts_are_out_of_memory() {
assert!(tsserver_ran_out_of_memory("TSServer exited. Code: 134. Signal: null"));
+1
Переглянути файл
@@ -25,6 +25,7 @@ mod kotlin_lsp;
mod launch;
mod library_source;
mod loading;
mod maven_placeholder;
mod message_requests;
mod notebook;
mod phoxite;
+113
Переглянути файл
@@ -0,0 +1,113 @@
//! `@property@` placeholders in YAML resources: Maven resource filtering replaces
//! them before the file is ever read as YAML, so Spring projects use them unquoted
//! (`spring.profiles.active: @profileActive@`). The YAML spec reserves `@` and the
//! `yaml` parser behind `yaml-language-server` therefore reports
//! "Plain value cannot start with reserved character @" for every one of them.
//! The diagnostic is dropped when the reported scalar is exactly a Maven
//! placeholder; anything else the parser flags keeps showing.
use lsp_types as lsp;
const RESERVED_AT: &str = "Plain value cannot start with reserved character @";
/// Whether `diagnostic` is the reserved-`@` parser error on a scalar whose text in
/// `text` is exactly a Maven placeholder (`@token@`).
pub(crate) fn false_positive(text: &str, diagnostic: &lsp::Diagnostic) -> bool {
diagnostic.message == RESERVED_AT && placeholder_at(text, &diagnostic.range).is_some()
}
/// The name between the `@`s of the diagnostic range, when it covers one whole placeholder.
fn placeholder_at(text: &str, range: &lsp::Range) -> Option<String> {
if range.start.line != range.end.line {
return None;
}
let line = text.split_inclusive('\n').nth(range.start.line as usize)?;
let line = line.trim_end_matches(['\n', '\r']);
let start = utf16_to_byte(line, range.start.character)?.min(line.len());
// The parser's scalar range ends one past the line (its newline), so the end clamps.
let end = utf16_to_byte(line, range.end.character).unwrap_or(line.len());
if end < start {
return None;
}
let inner = line[start..end].strip_prefix('@')?.strip_suffix('@')?;
(!inner.is_empty() && inner.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')))
.then(|| inner.to_owned())
}
/// UTF-16 column → byte offset within one line, `None` inside a surrogate pair or past the line.
fn utf16_to_byte(line: &str, col: u32) -> Option<usize> {
let col = col as usize;
let mut units = 0usize;
for (byte, c) in line.char_indices() {
if units == col {
return Some(byte);
}
units += c.len_utf16();
if units > col {
return None;
}
}
(units == col).then_some(line.len())
}
#[cfg(test)]
mod tests {
use super::*;
use lsp_types::{Position, Range};
fn at(line: u32, from: u32, to: u32) -> Range {
Range { start: Position::new(line, from), end: Position::new(line, to) }
}
fn across(from: (u32, u32), to: (u32, u32)) -> Range {
Range { start: Position::new(from.0, from.1), end: Position::new(to.0, to.1) }
}
fn diagnostic(range: Range) -> lsp::Diagnostic {
lsp::Diagnostic { range, message: RESERVED_AT.to_owned(), ..Default::default() }
}
#[test]
fn a_maven_placeholder_placeholder_is_a_false_positive() {
let text = "spring:\n profiles:\n active: @profileActive@\n";
assert!(false_positive(text, &diagnostic(at(2, 12, 27))));
// The parser ends the scalar's range one past the line (its newline): still caught.
assert!(false_positive(text, &diagnostic(at(2, 12, 28))));
// Columns also decode on a line with non-ASCII text before the scalar.
let text = "name: 项目\nvalue: @profileActive@\n";
assert!(false_positive(text, &diagnostic(at(1, 7, 22))));
}
#[test]
fn other_reserved_character_errors_and_shapes_still_show() {
let text = "active: @profileActive@\n";
// Not the parser's message (a backtick, a different wording).
assert!(!false_positive(
text,
&lsp::Diagnostic {
message: "Plain value cannot start with reserved character `".to_owned(),
..diagnostic(at(0, 8, 11))
}
));
// The error's range is stale and no longer covers a placeholder.
assert!(!false_positive(text, &diagnostic(at(0, 0, 10))));
// A single `@`, an unpaired one or a name with spaces is no placeholder.
assert!(!false_positive("active: @\n", &diagnostic(at(0, 8, 9))));
assert!(!false_positive("active: @profile\n", &diagnostic(at(0, 8, 16))));
assert!(!false_positive("active: @pro file@\n", &diagnostic(at(0, 8, 18))));
// A range crossing lines is kept.
assert!(!false_positive("a: @x@\nb: y\n", &diagnostic(across((0, 3), (1, 0)))));
}
#[test]
fn utf16_columns_decode_multi_byte_and_surrogate_pairs() {
// "é" is one UTF-16 unit; "😀" is two, and a column inside it is out of range.
let line = "é😀@token@";
assert_eq!(utf16_to_byte(line, 0), Some(0));
assert_eq!(utf16_to_byte(line, 1), Some(2));
assert_eq!(utf16_to_byte(line, 2), None);
assert_eq!(utf16_to_byte(line, 3), Some(6));
assert_eq!(utf16_to_byte(line, 4), Some(7));
assert_eq!(utf16_to_byte(line, 10), Some(line.len()));
}
}
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
1056d650117bc2216ac518aa26b27cf898f58db62369ae285b9d8925ada74dff
b24fb8d5161006104698fb07a43432601b4f16fdc4a34cc70058cbef7e973066
+9 -3
Переглянути файл
@@ -181,9 +181,13 @@ impl commands::Guest for Misbehave {
};
let child = process::start(&cmd, None)?;
// CPU work per step (loop iterations), for fuel budget tests.
let work: u64 = arg.as_deref().and_then(|a| a.parse().ok()).unwrap_or(0);
let arg = arg.as_deref().unwrap_or("");
let report = !arg.starts_with("quiet:");
let work: u64 = arg.strip_prefix("quiet:").unwrap_or(arg).parse().unwrap_or(0);
for step in 0..25 {
task.report(step, Some(25), Some("waiting"));
if report {
task.report(step, Some(25), Some("waiting"));
}
let mut x: u64 = 0;
for _ in 0..work {
x = std::hint::black_box(x.wrapping_add(1));
@@ -195,7 +199,9 @@ impl commands::Guest for Misbehave {
// Let it finish on its own: no kill, no slow teardown.
child.close_stdin()?;
let _ = child.wait(5_000);
task.report(25, Some(25), Some("done"));
if report {
task.report(25, Some(25), Some("done"));
}
Ok(Some("still here".into()))
}
// `editor.write` is not granted: an error, not a trap.
+93 -3
Переглянути файл
@@ -21,10 +21,63 @@ fn root(data_dir: &Path) -> PathBuf {
data_dir.join("lsp").join("jdtls")
}
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder).
/// jdtls' temporary folder, inside its workspace.
const TEMP_DIR: &str = ".tmp";
fn workspace(cfg: &LanguageServerConfig) -> Option<&Path> {
cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)).map(Path::new)
}
fn temp_arg(workspace: &Path) -> String {
format!("-Djava.io.tmpdir={}", workspace.join(TEMP_DIR).to_string_lossy())
}
/// Gives jdtls a temporary folder inside a workspace of ours (`<workspace>/.tmp`) unless the
/// user's JVM arguments choose one. JDT APT copies a project's annotation processor jars into a
/// new `jdt-apt-*` folder for each processor class loader and deletes it only when the JVM exits
/// normally — never on Windows, where the jars are still open then — so in the system temp
/// folder they pile up with every start; [`mark_used`] empties this one before each start.
pub fn use_own_temp(cfg: &mut LanguageServerConfig, data_dir: &Path) {
if cfg.name != "jdtls" || cfg.args.iter().any(|a| a.contains("-Djava.io.tmpdir=")) {
return;
}
let Some(arg) = workspace(cfg).filter(|w| w.starts_with(root(data_dir))).map(temp_arg) else { return };
// Launched directly, JVM options go before `-jar`; through the script, as `--jvm-arg=`.
match cfg.args.iter().position(|a| a == "-jar") {
Some(jar) => cfg.args.insert(jar, arg),
None => cfg.args.push(format!("--jvm-arg={arg}")),
}
}
/// Empties the temporary folder [`use_own_temp`] gave the workspace. Best effort: files a server
/// still has open on Windows stay until a later start.
fn clear_temp(cfg: &LanguageServerConfig, workspace: &Path) {
let arg = temp_arg(workspace);
if !cfg.args.iter().any(|a| a.strip_prefix("--jvm-arg=").unwrap_or(a) == arg) {
return;
}
let temp = workspace.join(TEMP_DIR);
for entry in std::fs::read_dir(&temp).into_iter().flatten().flatten() {
let path = entry.path();
let removed = if entry.file_type().is_ok_and(|t| t.is_dir()) {
std::fs::remove_dir_all(&path)
} else {
std::fs::remove_file(&path)
};
if let Err(e) = removed {
tracing::debug!("jdtls: cannot remove temporary {}: {e}", path.display());
}
}
if let Err(e) = std::fs::create_dir_all(&temp) {
tracing::warn!("jdtls: cannot create its temporary folder {}: {e}", temp.display());
}
}
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder), and empties
/// the workspace's temporary folder.
pub fn mark_used(cfg: &LanguageServerConfig) {
let Some(dir) = cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)) else { return };
let dir = Path::new(dir);
let Some(dir) = workspace(cfg) else { return };
clear_temp(cfg, dir);
if let Err(e) = std::fs::create_dir_all(dir).and_then(|()| {
let marker = std::fs::File::create(dir.join(USED_MARKER))?;
marker.set_modified(SystemTime::now())
@@ -142,6 +195,43 @@ mod tests {
assert!(ws.exists());
}
#[test]
fn jdtls_keeps_its_temporary_files_in_its_workspace_and_starts_with_none() {
let tmp = tempfile::tempdir().unwrap();
let ws = root(tmp.path()).join("p");
let temp = format!("-Djava.io.tmpdir={}", ws.join(TEMP_DIR).to_string_lossy());
// Through the launcher script.
let mut script = cfg(&ws);
use_own_temp(&mut script, tmp.path());
assert_eq!(script.args.last(), Some(&format!("--jvm-arg={temp}")));
// Launched directly: a JVM option, before `-jar`.
let mut direct = cfg(&ws);
direct.args.splice(0..0, ["-Xmx2G".to_owned(), "-jar".to_owned(), "launcher.jar".to_owned()]);
use_own_temp(&mut direct, tmp.path());
assert_eq!(direct.args[..3], ["-Xmx2G".to_owned(), temp.clone(), "-jar".to_owned()]);
let stale = ws.join(TEMP_DIR).join("jdt-apt-1");
std::fs::create_dir_all(&stale).unwrap();
std::fs::write(stale.join("0_processor.jar"), "").unwrap();
std::fs::write(ws.join(TEMP_DIR).join("file.tmp"), "").unwrap();
mark_used(&direct);
assert!(ws.join(TEMP_DIR).is_dir());
assert_eq!(std::fs::read_dir(ws.join(TEMP_DIR)).unwrap().count(), 0);
// The user's own choice, and a workspace that is not ours, are left alone.
let mut own = cfg(&ws);
own.args.push("--jvm-arg=-Djava.io.tmpdir=/elsewhere".into());
use_own_temp(&mut own, tmp.path());
assert_eq!(own.args.iter().filter(|a| a.contains("java.io.tmpdir")).count(), 1);
let mut theirs = cfg(&tmp.path().join("their-workspace"));
use_own_temp(&mut theirs, tmp.path());
assert!(!theirs.args.iter().any(|a| a.contains("java.io.tmpdir")));
std::fs::create_dir_all(ws.join(TEMP_DIR).join("kept")).unwrap();
mark_used(&cfg(&ws));
assert!(ws.join(TEMP_DIR).join("kept").exists());
}
#[cfg(unix)]
#[test]
fn a_workspace_from_before_markers_is_judged_by_its_folders_and_log() {
+257 -9
Переглянути файл
@@ -239,7 +239,7 @@ fn event_handler(state: Weak<DirState>, polled: bool) -> impl FnMut(notify::Resu
Ok(event) if !is_change_event(&event) => {}
Ok(event) if polled && is_dir_touch(&event) => {}
Ok(event) => {
state.queue.lock().push((event, Instant::now()));
state.queue.lock().push(event, Instant::now());
state.wake.notify_one();
}
Err(e) => tracing::warn!("file watcher: {e}"),
@@ -280,13 +280,53 @@ fn watcher_error(what: &str, error: notify::Error) -> IdeError {
}
}
/// Only adjacent identical file modifications are redundant before classification.
/// Keep the arrival window separately so compaction cannot extend MAX_DELAY.
#[derive(Default)]
struct PendingEvents {
events: Vec<Event>,
first: Option<Instant>,
last: Option<Instant>,
received: usize,
}
impl PendingEvents {
fn is_empty(&self) -> bool {
self.events.is_empty()
}
fn push(&mut self, event: Event, now: Instant) {
self.first.get_or_insert(now);
self.last = Some(now);
self.received += 1;
let redundant = event.paths.len() == 1
&& event.flag().is_none()
&& matches!(event.kind, EventKind::Modify(ModifyKind::Any | ModifyKind::Data(_) | ModifyKind::Metadata(_)))
&& self.events.last().is_some_and(|previous| {
// Reject different spellings before Path's component-wise equality.
// Keeping a normalized alias is safe; only exact duplicates compact.
previous.paths.len() == 1
&& previous.paths[0].as_os_str() == event.paths[0].as_os_str()
&& previous == &event
&& previous.attrs.process_id() == event.attrs.process_id()
});
if !redundant {
self.events.push(event);
}
}
fn deadline(&self) -> Option<Instant> {
Some((self.last? + DEBOUNCE).min(self.first? + MAX_DELAY))
}
}
/// Shared with the notify callback (weakly) and the debounce thread.
struct DirState {
filter: EventFilter,
mode: WatchMode,
watcher: Mutex<Option<Box<dyn notify::Watcher + Send>>>,
watched: Mutex<HashSet<PathBuf>>,
queue: Mutex<Vec<(notify::Event, Instant)>>,
queue: Mutex<PendingEvents>,
wake: Condvar,
stop: AtomicBool,
/// Set when a `watch()` call reports the OS watch limit (inotify
@@ -317,34 +357,48 @@ impl DirState {
if self.stopped() {
return;
}
let first = q[0].1;
loop {
let last = q.last().map_or(first, |e| e.1);
let deadline = q.deadline().expect("nonempty event queue");
let now = Instant::now();
if self.stopped() {
return;
}
if now >= last + DEBOUNCE || now >= first + MAX_DELAY {
if now >= deadline {
break;
}
let wait = (last + DEBOUNCE).min(first + MAX_DELAY) - now;
let wait = deadline - now;
self.wake.wait_for(&mut q, wait);
}
std::mem::take(&mut *q)
};
// A scan may publish a path before its create event is delivered:
// keep create + remove pairs so the consumer still sees the removal.
let events: Vec<Event> = events.into_iter().map(|(e, _)| e).collect();
let (mut batch, rule_dirs) = self.filter.batch_detailed(&events);
let processing = Instant::now();
let queue_age_ms = processing.duration_since(events.first.expect("nonempty event queue")).as_millis();
let received = events.received;
let queued = events.events.len();
let (mut batch, rule_dirs) = self.filter.batch_detailed(&events.events);
if self.mode == WatchMode::PerDirectory {
self.update_watches(&mut batch, &rule_dirs);
// Again once polling: a refused directory was not read, and
// the poller won't report what is already in it.
polled = polled || self.poll_if_exhausted(|| self.update_watches(&mut batch, &rule_dirs));
}
let processing_ms = processing.elapsed().as_millis();
let callback = Instant::now();
if !batch.is_empty() && !self.stopped() {
emit(&batch);
}
tracing::debug!(
received,
queued,
coalesced = received - queued,
queue_age_ms,
processing_ms,
callback_ms = callback.elapsed().as_millis(),
"file watcher batch"
);
}
}
@@ -785,6 +839,10 @@ impl EventFilter {
}
}
#[cfg(test)]
#[path = "watch_pipeline_tests.rs"]
mod pipeline_tests;
#[cfg(test)]
mod tests {
use super::*;
@@ -794,6 +852,196 @@ mod tests {
Event { kind, paths, attrs: Default::default() }
}
#[test]
fn pending_modifications_keep_the_original_debounce_window() {
let start = Instant::now();
// ReadDirectoryChangesW reports ordinary Windows writes as Modify(Any).
let event = ev(EventKind::Modify(ModifyKind::Any), vec!["file.rs".into()]);
let mut pending = PendingEvents::default();
assert_eq!(pending.deadline(), None);
for n in 0..10_000 {
pending.push(event.clone(), start + Duration::from_micros(n * 95));
}
assert_eq!(pending.received, 10_000);
assert_eq!(pending.events.len(), 1);
assert_eq!(pending.first, Some(start));
assert_eq!(pending.last, Some(start + Duration::from_micros(9_999 * 95)));
assert_eq!(pending.deadline(), Some(start + MAX_DELAY));
let drained = std::mem::take(&mut pending);
assert_eq!(drained.events, vec![event.clone()]);
assert!(pending.is_empty());
assert_eq!(pending.deadline(), None);
pending.push(event, start + MAX_DELAY);
assert_eq!(pending.received, 1);
assert_eq!(pending.deadline(), Some(start + MAX_DELAY + DEBOUNCE));
}
#[test]
fn pending_events_preserve_boundaries_and_attributes() {
let now = Instant::now();
let modify = ev(EventKind::Modify(ModifyKind::Data(DataChange::Content)), vec!["a".into()]);
let variants = [
modify.clone().set_tracker(1),
modify.clone().set_info("backend detail"),
modify.clone().set_process_id(2),
modify.clone().set_flag(notify::event::Flag::Rescan),
modify.clone().add_path("b".into()),
ev(EventKind::Create(CreateKind::File), vec!["a".into()]),
ev(EventKind::Remove(RemoveKind::File), vec!["a".into()]),
ev(EventKind::Modify(ModifyKind::Name(RenameMode::Both)), vec!["a".into(), "b".into()]),
ev(EventKind::Modify(ModifyKind::Name(RenameMode::From)), vec!["a".into()]),
ev(EventKind::Modify(ModifyKind::Name(RenameMode::To)), vec!["a".into()]),
ev(EventKind::Any, vec!["a".into()]),
];
for middle in variants {
let events = vec![modify.clone(), middle, modify.clone()];
let mut pending = PendingEvents::default();
for event in &events {
pending.push(event.clone(), now);
}
assert_eq!(pending.events, events);
}
let mut interleaved = PendingEvents::default();
for event in [
modify.clone(),
modify.clone().set_kind(EventKind::Create(CreateKind::File)).add_path("b".into()),
modify.clone(),
] {
interleaved.push(event, now);
}
assert_eq!(interleaved.events.len(), 3);
let mut interleaved = PendingEvents::default();
for event in [modify.clone(), ev(modify.kind, vec!["b".into()]), modify.clone()] {
interleaved.push(event, now);
}
assert_eq!(interleaved.events.len(), 3);
for event in [
modify.set_flag(notify::event::Flag::Rescan),
ev(EventKind::Modify(ModifyKind::Name(RenameMode::From)), vec!["a".into()]),
] {
let mut pending = PendingEvents::default();
pending.push(event.clone(), now);
pending.push(event, now);
assert_eq!(pending.events.len(), 2);
}
}
#[test]
fn pending_keeps_different_spellings_of_the_same_path() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
std::fs::create_dir(root.join("src")).unwrap();
std::fs::write(root.join("src/a.rs"), "x").unwrap();
let paths = [root.join("src/a.rs"), root.join("src/./a.rs"), root.join("src//a.rs")];
assert_eq!(paths[0], paths[1]);
assert_ne!(paths[0].as_os_str(), paths[1].as_os_str());
let events: Vec<_> =
paths.into_iter().map(|path| Event::new(EventKind::Modify(ModifyKind::Any)).add_path(path)).collect();
let mut pending = PendingEvents::default();
for event in &events {
pending.push(event.clone(), Instant::now());
}
assert_eq!(pending.events.len(), events.len());
assert_same_batch(
&EventFilter::new(root.clone(), &[]).batch(&events),
&EventFilter::new(root, &[]).batch(&pending.events),
);
}
fn assert_same_batch(left: &FsBatch, right: &FsBatch) {
assert_eq!(left.created, right.created);
assert_eq!(left.modified, right.modified);
assert_eq!(left.removed, right.removed);
assert_eq!(left.vcs, right.vcs);
assert_eq!(left.excluded_dirs, right.excluded_dirs);
assert_eq!(left.ignored, right.ignored);
assert_eq!(left.ignore_rules, right.ignore_rules);
}
#[test]
fn pending_compaction_matches_uncompressed_change_sequences() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
std::fs::create_dir(root.join(".git")).unwrap();
std::fs::create_dir(root.join("excluded")).unwrap();
std::fs::write(root.join(".gitignore"), "*.ignored\n").unwrap();
let excludes = vec!["excluded".to_owned()];
let kinds = [
EventKind::Create(CreateKind::File),
EventKind::Remove(RemoveKind::File),
EventKind::Modify(ModifyKind::Any),
EventKind::Modify(ModifyKind::Data(DataChange::Content)),
EventKind::Modify(ModifyKind::Metadata(MetadataKind::WriteTime)),
EventKind::Modify(ModifyKind::Name(RenameMode::From)),
EventKind::Modify(ModifyKind::Name(RenameMode::To)),
];
// All four-event histories, with both present and absent final state.
for rel in ["source.rs", "file.ignored", "excluded/source.rs", ".git/HEAD"] {
let path = root.join(rel);
for exists in [false, true] {
if exists {
std::fs::write(&path, "x").unwrap();
}
for code in 0..kinds.len().pow(4) {
let mut code = code;
let mut events = Vec::new();
let mut pending = PendingEvents::default();
for _ in 0..4 {
let event = ev(kinds[code % kinds.len()], vec![path.clone()]);
code /= kinds.len();
// Each event is repeated to exercise compaction after transitions.
for _ in 0..2 {
events.push(event.clone());
pending.push(event.clone(), Instant::now());
}
}
let plain = EventFilter::new(root.clone(), &excludes).batch(&events);
let compact = EventFilter::new(root.clone(), &excludes).batch(&pending.events);
assert_same_batch(&plain, &compact);
}
}
}
}
#[test]
fn pending_compaction_keeps_rule_reload_and_rename_endpoints() {
let excludes = vec!["excluded".to_owned()];
for rule in [".gitignore", ".ignore", ".git/info/exclude"] {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
std::fs::create_dir_all(root.join(".git/info")).unwrap();
std::fs::create_dir(root.join("excluded")).unwrap();
std::fs::write(root.join(rule), "").unwrap();
std::fs::write(root.join("file.ignored"), "x").unwrap();
let plain = EventFilter::new(root.clone(), &excludes);
let compact = EventFilter::new(root.clone(), &excludes);
let touch = ev(EventKind::Modify(ModifyKind::Data(DataChange::Content)), vec![root.join("file.ignored")]);
for filter in [&plain, &compact] {
assert_eq!(filter.batch(std::slice::from_ref(&touch)).modified, vec![root.join("file.ignored")]);
}
std::fs::write(root.join(rule), "*.ignored\n").unwrap();
let mut events = Vec::new();
for path in ["file.ignored", rule] {
let event = ev(EventKind::Modify(ModifyKind::Data(DataChange::Content)), vec![root.join(path)]);
events.extend([event.clone(), event]);
}
events.push(ev(
EventKind::Modify(ModifyKind::Name(RenameMode::Both)),
vec![root.join("excluded/old.rs"), root.join("new.rs")],
));
std::fs::write(root.join("new.rs"), "x").unwrap();
let mut pending = PendingEvents::default();
for event in &events {
pending.push(event.clone(), Instant::now());
}
let expected = plain.batch(&events);
assert_eq!(expected.ignore_rules, vec![root.clone()]);
assert_eq!(expected.ignored, vec![root.join("file.ignored")]);
assert!(!expected.modified.contains(&root.join("file.ignored")));
assert_same_batch(&expected, &compact.batch(&pending.events));
}
}
const TRANSIENT_PATHS: &[&str] = &["fresh.txt", "src/fresh.rs", "src/tasks/fresh.py"];
/// Delivers a whole debounce window without depending on OS scheduling.
@@ -1530,7 +1778,7 @@ mod tests {
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(&file, "x").unwrap();
let created = Event::new(EventKind::Create(notify::event::CreateKind::Folder)).add_path(root.join("new"));
inner.state.queue.lock().push((created, Instant::now()));
inner.state.queue.lock().push(created, Instant::now());
inner.state.wake.notify_all();
// Written before polling took over, so the poller never reports it.
assert!(wait_for(&batches, |b| all_paths(b).contains(&file)), "{:?}", batches.lock());
+177
Переглянути файл
@@ -0,0 +1,177 @@
//! Queue-to-filter correctness comparisons, without timing or OS delivery.
use super::*;
use notify::event::{CreateKind, Flag, RemoveKind};
fn compare_batches(left: &FsBatch, right: &FsBatch) {
assert_eq!(
(
&left.created,
&left.modified,
&left.removed,
&left.vcs,
&left.excluded_dirs,
&left.ignored,
&left.ignore_rules
),
(
&right.created,
&right.modified,
&right.removed,
&right.vcs,
&right.excluded_dirs,
&right.ignored,
&right.ignore_rules
)
);
}
// Preserve the pre-change queue and drain operation for the comparison.
fn original(input: &[Event], filter: &EventFilter) -> (usize, FsBatch) {
let mut queue = Vec::new();
for event in input {
queue.push((event.clone(), Instant::now()));
}
let retained = queue.len();
let events: Vec<Event> = std::mem::take(&mut queue).into_iter().map(|(event, _)| event).collect();
(retained, filter.batch(&events))
}
fn compact(input: &[Event], filter: &EventFilter) -> (usize, FsBatch) {
let mut queue = PendingEvents::default();
for event in input {
queue.push(event.clone(), Instant::now());
}
let events = std::mem::take(&mut queue);
(events.events.len(), filter.batch(&events.events))
}
fn event(kind: EventKind, root: &Path, rel: &str) -> Event {
Event::new(kind).add_path(root.join(rel))
}
fn modify(root: &Path, n: usize) -> Event {
event(EventKind::Modify(ModifyKind::Any), root, &format!("src/{n}.rs"))
}
fn fixture(files: usize) -> tempfile::TempDir {
let tmp = tempfile::tempdir().unwrap();
for dir in ["src", "excluded", ".git/info", "renamed"] {
std::fs::create_dir_all(tmp.path().join(dir)).unwrap();
}
std::fs::write(tmp.path().join(".gitignore"), "*.ignored\n").unwrap();
std::fs::write(tmp.path().join("file.ignored"), "x").unwrap();
for n in 0..files {
std::fs::write(tmp.path().join(format!("src/{n}.rs")), "x").unwrap();
if n % 8 == 4 {
std::fs::write(tmp.path().join(format!("excluded/{n}.js")), "x").unwrap();
}
}
tmp
}
fn cases(root: &Path, count: usize) -> Vec<(&'static str, Vec<Event>)> {
let repeated = vec![modify(root, 0); count];
let distinct = (0..count).map(|n| modify(root, n)).collect();
let interleaved = (0..count).map(|n| modify(root, n % 2)).collect();
let pairs = (0..count).map(|n| modify(root, n / 2)).collect();
let runs = (0..count).map(|n| modify(root, n / 10)).collect();
let mixed = (0..count)
.map(|n| match n % 8 {
0 | 1 => modify(root, n / 8),
2 => event(EventKind::Create(CreateKind::File), root, &format!("src/{}.rs", n / 8)),
3 => event(EventKind::Remove(RemoveKind::File), root, &format!("gone/{n}.rs")),
4 => event(EventKind::Create(CreateKind::File), root, &format!("excluded/{n}.js")),
5 => event(EventKind::Remove(RemoveKind::File), root, &format!("excluded/{n}.js")),
6 => event(EventKind::Modify(ModifyKind::Any), root, "file.ignored"),
_ => event(EventKind::Modify(ModifyKind::Any), root, ".git/HEAD"),
})
.collect();
vec![
("repeated", repeated),
("distinct", distinct),
("interleaved", interleaved),
("pairs", pairs),
("runs10", runs),
("mixed", mixed),
]
}
fn pair(input: &[Event], root: &Path, warm: bool, reverse: bool) -> (usize, usize) {
let excludes = vec!["excluded".to_owned()];
let a = EventFilter::new(root.to_path_buf(), &excludes);
let b = EventFilter::new(root.to_path_buf(), &excludes);
if warm {
compare_batches(&a.batch(input), &b.batch(input));
}
let (a_retained, a_batch, b_retained, b_batch) = if reverse {
let (b_retained, b_batch) = compact(input, &b);
let (a_retained, a_batch) = original(input, &a);
(a_retained, a_batch, b_retained, b_batch)
} else {
let (a_retained, a_batch) = original(input, &a);
let (b_retained, b_batch) = compact(input, &b);
(a_retained, a_batch, b_retained, b_batch)
};
compare_batches(&a_batch, &b_batch);
(a_retained, b_retained)
}
#[test]
fn pipeline_comparison_preserves_batches_and_rule_changes() {
let tmp = fixture(32);
let root = dunce::canonicalize(tmp.path()).unwrap();
for (name, input) in cases(&root, 32) {
for warm in [false, true] {
for reverse in [false, true] {
let (old, new) = pair(&input, &root, warm, reverse);
assert_eq!(old, 32);
let expected = match name {
"repeated" => 1,
"distinct" | "interleaved" => 32,
"pairs" => 16,
"runs10" => 4,
"mixed" => 28,
_ => unreachable!(),
};
assert_eq!(new, expected, "{name}");
}
}
}
let mut special = vec![
modify(&root, 0).set_flag(Flag::Rescan),
modify(&root, 0).set_flag(Flag::Rescan),
modify(&root, 0).set_tracker(1),
modify(&root, 0).set_tracker(2),
modify(&root, 0).set_process_id(1),
modify(&root, 0).set_process_id(2),
modify(&root, 0).add_path(root.join("src/1.rs")),
];
for mode in [RenameMode::Both, RenameMode::From, RenameMode::To] {
let rename = event(EventKind::Modify(ModifyKind::Name(mode)), &root, "old.rs");
special.push(if mode == RenameMode::Both { rename.add_path(root.join("src/0.rs")) } else { rename });
}
let (old, new) = pair(&special, &root, true, false);
assert_eq!(old, special.len());
assert_eq!(new, special.len());
for rule in [".gitignore", ".ignore", ".git/info/exclude"] {
let tmp = fixture(1);
let root = dunce::canonicalize(tmp.path()).unwrap();
std::fs::write(root.join(".gitignore"), "").unwrap();
std::fs::write(root.join(rule), "").unwrap();
let a = EventFilter::new(root.clone(), &[]);
let b = EventFilter::new(root.clone(), &[]);
let touch = event(EventKind::Modify(ModifyKind::Any), &root, "file.ignored");
for filter in [&a, &b] {
assert_eq!(filter.batch(std::slice::from_ref(&touch)).modified, vec![root.join("file.ignored")]);
}
std::fs::write(root.join(rule), "*.ignored\n").unwrap();
let change = event(EventKind::Modify(ModifyKind::Any), &root, rule);
let input = [touch.clone(), touch, change.clone(), change];
let (_, old) = original(&input, &a);
let (_, new) = compact(&input, &b);
compare_batches(&old, &new);
assert_eq!(new.ignored, vec![root.join("file.ignored")]);
assert_eq!(new.ignore_rules, vec![root]);
}
}
+110 -4
Переглянути файл
@@ -92,6 +92,8 @@ pub const DEFAULT_MAX_AGE_DAYS: u32 = 5;
pub const DEFAULT_MAX_BYTES: u64 = 512 * 1024 * 1024;
/// Label of the snapshot taken before a file is deleted.
pub const DELETED: &str = "Deleted";
/// The label of a file's content from before its first edit ([`LocalHistory::record_original`]).
pub const ORIGINAL: &str = "Original";
/// Files larger than this are not snapshotted automatically (watcher, deletes, VCS).
const AUTO_SNAPSHOT_LIMIT: u64 = 2 * 1024 * 1024;
const DAY_MS: f64 = 86_400_000.0;
@@ -121,7 +123,14 @@ fn read_snapshot_text(path: &Path) -> Option<String> {
if bytes.iter().take(8192).any(|b| *b == 0) {
return None;
}
String::from_utf8(bytes).ok()
String::from_utf8(bytes).ok().map(|text| document_text(&text).into_owned())
}
/// `text` as a document holds it: without the UTF-8 BOM and with `\n` line endings. Saves
/// record the document's text, so a file read from disk must match it to dedupe, and
/// Revert writes it back through the document, which adds the file's BOM and line endings.
fn document_text(text: &str) -> std::borrow::Cow<'_, str> {
ide_text::normalize_line_endings(text.strip_prefix('\u{feff}').unwrap_or(text))
}
impl LocalHistory {
@@ -188,6 +197,18 @@ impl LocalHistory {
if !force && state.last.get(path) == Some(&id) {
return Ok(());
}
self.store_locked(&mut state, path, id, content, label, now_ms())
}
fn store_locked(
&self,
state: &mut HistoryState,
path: &Path,
id: String,
content: &str,
label: &str,
timestamp_ms: f64,
) -> IdeResult<()> {
let blob = self.blob_path(&id);
if !blob.exists() {
fs::create_dir_all(blob.parent().expect("blob has a parent"))?;
@@ -196,12 +217,12 @@ impl LocalHistory {
let entry = HistoryEntry {
id,
path: path.into(),
timestamp_ms: now_ms(),
timestamp_ms,
label: label.to_owned(),
size: content.len() as u64,
kind: HistoryKind::Snapshot,
};
self.append(&mut state, entry)
self.append(state, entry)
}
/// Records a snapshot unless it equals the latest one recorded for `path`.
@@ -223,6 +244,31 @@ impl LocalHistory {
}
}
/// Before the first edit of a file with no history: its content on disk, so a label put
/// before the edit can be reverted to. Dated by the file's modification time, since it
/// has had that content from then on, but not before the oldest entry kept, so it neither
/// adds a working day of its own nor falls to retention first. Returns whether one was recorded.
pub fn record_original(&self, path: &Path) -> IdeResult<bool> {
let Some(text) = read_snapshot_text(path) else { return Ok(false) };
let modified = fs::metadata(path)
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs_f64() * 1000.0);
let mut state = self.state.lock();
if state.entries.iter().any(|e| e.kind == HistoryKind::Snapshot && e.path == path) {
return Ok(false);
}
let now = now_ms();
let oldest = state.entries.iter().map(|e| e.timestamp_ms).reduce(f64::min);
let timestamp = match (modified, oldest) {
(Some(modified), Some(oldest)) => modified.max(oldest - 1.0).min(now),
_ => now,
};
let id = blake3::hash(text.as_bytes()).to_hex().to_string();
self.store_locked(&mut state, path, id, &text, ORIGINAL, timestamp).map(|()| true)
}
/// Snapshots `path`, or every file below it when it is a folder (at most `limit`
/// files), before it is deleted. Returns how many files were recorded.
pub fn record_deletion(&self, path: &Path, limit: usize) -> usize {
@@ -338,7 +384,10 @@ impl LocalHistory {
return Err(IdeError::invalid(format!("invalid history id {id:?}")));
}
match fs::read(self.blob_path(id)) {
Ok(bytes) => Ok(String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into())),
Ok(bytes) => {
let text = String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into());
Ok(document_text(&text).into_owned())
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
Err(IdeError::not_found(format!("history snapshot {id} not found")))
}
@@ -532,6 +581,25 @@ mod tests {
}
}
#[test]
fn a_file_read_from_disk_matches_the_saved_document_text() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
fs::create_dir_all(&root).unwrap();
let h = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
let a = root.join("a.txt");
// A save records the document's text; the file on disk has a BOM and CRLF.
fs::write(&a, b"\xEF\xBB\xBFheader\r\nbody\r\n").unwrap();
h.record(&a, "header\nbody\n", "Saved").unwrap();
assert!(h.record_file(&a, "External change", false).unwrap());
let list = h.list(&a).unwrap();
assert_eq!(list.iter().map(|e| e.label.as_str()).collect::<Vec<_>>(), ["Saved"], "no second revision");
// A snapshot stored with its BOM before reads back as document text.
h.record(&a, "\u{feff}old\r\n", "External change").unwrap();
let old = &h.list(&a).unwrap()[0];
assert_eq!(h.content(&old.id).unwrap(), "old\n");
}
#[test]
fn events_labels_and_deletions() {
let tmp = tempfile::tempdir().unwrap();
@@ -630,4 +698,42 @@ mod tests {
assert_eq!(h.list(Path::new("/p/a")).unwrap().len(), 1);
assert_eq!(h.content(&old).unwrap_err().kind, ide_core::error::ErrorKind::NotFound);
}
#[test]
fn a_files_original_content_is_there_at_a_label_put_before_its_first_edit() {
use std::time::{Duration, SystemTime};
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
std::fs::create_dir_all(&root).unwrap();
let h = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
let set_modified = |path: &Path, at: SystemTime| {
std::fs::File::options().write(true).open(path).unwrap().set_modified(at).unwrap();
};
let old = root.join("old.txt");
std::fs::write(&old, "as it was").unwrap();
set_modified(&old, SystemTime::now() - Duration::from_secs(3600));
h.record(&root.join("other.txt"), "x", "Saved").unwrap();
std::thread::sleep(Duration::from_millis(2));
h.put_label(&root, "checkpoint").unwrap();
// Written after the label: it didn't have this content at the label.
let new = root.join("new.txt");
std::fs::write(&new, "fresh").unwrap();
set_modified(&new, SystemTime::now() + Duration::from_secs(1));
assert!(h.record_original(&old).unwrap());
assert!(h.record_original(&new).unwrap());
// Only a file without history gets one.
assert!(!h.record_original(&old).unwrap());
h.record(&old, "edited", "Saved").unwrap();
let entries = h.list(&old).unwrap();
let label = entries.iter().find(|e| e.kind == HistoryKind::Label).unwrap();
let original = entries.iter().find(|e| e.label == ORIGINAL).unwrap();
assert!(original.timestamp_ms < label.timestamp_ms);
assert_eq!(h.content(&original.id).unwrap(), "as it was");
// Not dated before the oldest entry kept: no working day of its own.
let oldest = h.list(&root.join("other.txt")).unwrap().last().unwrap().timestamp_ms;
assert!(original.timestamp_ms >= oldest - 1.0);
let fresh = h.list(&new).unwrap().into_iter().find(|e| e.label == ORIGINAL).unwrap();
assert!(fresh.timestamp_ms > label.timestamp_ms);
}
}
+2 -2
Переглянути файл
@@ -96,7 +96,7 @@ Once an agent has run a task, new tasks start in its mode that approves everythi
### Review the changes
Click **Show changes** in the task header to list the files the task changed. A task in the project's own checkout lists only the files that changed while the agent was working, not what you or another task changed while it was idle. Click a file to open a diff between the task's starting point and now. For a worktree task, the changes live on its `agent/…` branch: open a terminal there with **Open in Terminal**, and merge or cherry-pick the branch with the Git tools (see [Version control](/en/guide/vcs)) when you are happy with it.
Click **Show changes** in the task header to list the files the task changed. A task in the project's own checkout lists only the files that changed while the agent was working, not what you or another task changed while it was idle. Click a file to open a diff between the task's starting point and now. Switch the list from **Whole Task** to **Last Turn** to see only what the last turn changed, against the files as that turn started; rolling back then undoes only that turn. For a worktree task, the changes live on its `agent/…` branch: open a terminal there with **Open in Terminal**, and merge or cherry-pick the branch with the Git tools (see [Version control](/en/guide/vcs)) when you are happy with it.
Drag the pane's left edge to resize it. The width applies to every task and is remembered across restarts.
@@ -131,7 +131,7 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
- **Global (`User`)**: saved in `settings.toml` with environment variable and HTTP header values stored in the OS credential store, shared across projects and agents (or scoped to selected agents).
- **Project (`Workspace`)**: saved in `.openidea/settings.toml`; entries with the same name override Global servers, and servers added outside OpenIDEA stay off until approved.
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json`, `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json` (and installed Copilot CLI plugins), `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
- **Per-session (`MCP` / `/mcp`)**: in both **New Agent Task** and active task conversations, open **MCP** in the composer toolbar (or run `/mcp`) to enable or disable individual servers—including the built-in `openidea` server—for that task only, or click **Reset** to return to the inherited defaults.
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply. **Settings › Agents › Working Status** can show playful words for what it does there instead; they are off by default. Once turned on, they take turns from the moment the work changes, or only after the agent reports nothing new for a number of seconds (0 to 600, 0 by default); screen readers still hear what the agent is doing. Each word stays eight seconds while the agent keeps at the same work, and at least three when it moves on, so the line doesn't flicker. The same page replaces the words: pick what the status says (**Reading…**, **Running a command…**…) and add or remove its words. **Restore Built-in Words** brings back OpenIDEA's; an activity left without words keeps its plain status.
+4 -2
Переглянути файл
@@ -45,14 +45,16 @@ If navigation, search or highlighting doesn't match the files, rebuild the cache
The Windows packages aren't code-signed yet, so Microsoft Defender SmartScreen may show an unknown-publisher warning. Choose **More info**, then **Run anyway**. See [Install](/en/guide/install#windows).
## The window stays blank on Linux
## The window stays blank or stops responding on Linux
WebKitGTK's DMA-BUF renderer fails on Wayland with the NVIDIA driver. OpenIDEA detects this combination and sets `WEBKIT_DISABLE_DMABUF_RENDERER=1` itself. If you see a blank or broken window in another setup, quit OpenIDEA and start it from a terminal with that variable set, for example:
WebKitGTK's DMA-BUF renderer fails on some Wayland setups. With the NVIDIA driver on Wayland, OpenIDEA turns the driver's explicit sync off for itself (`__NV_DISABLE_EXPLICIT_SYNC=1`), which avoids the failure and keeps the renderer. If the window stays blank, draws incorrectly, or stops reacting to the keyboard and mouse a few seconds after launch in another setup, quit OpenIDEA and start it from a terminal with the DMA-BUF renderer turned off, for example:
```sh
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
```
The page is then drawn without the GPU, so dragging large panels can be slower. To keep the setting for launches from the application menu with the deb or rpm package, copy `/usr/share/applications/OpenIDEA.desktop` to `~/.local/share/applications/` and change its `Exec=` line to `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`.
## OpenIDEA exits at startup with a data directory error
`OPENIDEA_LOCAL_DATA_DIR` is set to a relative path or to a folder that can't be written. Fix or remove the variable. See [Move the local data](/en/reference/data-directories#move-the-local-data).
+2 -2
Переглянути файл
@@ -96,7 +96,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
### 查看改动
在任务标题栏中单击 **显示更改**,列出任务改动过的文件。直接在项目中运行的任务只列出 agent 工作期间改动的文件,不包括它空闲时你自己或其他任务做的修改。单击文件可以打开它从任务开始到现在的 diff。worktree 任务的改动在它的 `agent/…` 分支上:用 **在终端中打开** 在那里打开终端,满意后用 Git 工具合并或 cherry-pick 这个分支(见 [版本控制](/zh/guide/vcs))。
在任务标题栏中单击 **显示更改**,列出任务改动过的文件。直接在项目中运行的任务只列出 agent 工作期间改动的文件,不包括它空闲时你自己或其他任务做的修改。单击文件可以打开它从任务开始到现在的 diff。把列表从 **整个任务** 切换到 **最近一轮**,就只列出最近一轮的改动,对比的是这一轮开始时的文件;此时回滚也只撤销这一轮的改动。worktree 任务的改动在它的 `agent/…` 分支上:用 **在终端中打开** 在那里打开终端,满意后用 Git 工具合并或 cherry-pick 这个分支(见 [版本控制](/zh/guide/vcs))。
拖动改动面板的左边缘可以调整宽度。宽度对所有任务生效,重启后保留。
@@ -131,7 +131,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
- **全局(`用户`)**:保存在 `settings.toml` 中,环境变量与 HTTP 请求头的值保存在系统凭据存储里,跨项目与各智能体共享(也可限定给选定的智能体)。
- **项目(`工作区`)**:保存在 `.openidea/settings.toml` 中,同名服务器覆盖全局配置;在 OpenIDEA 外部写入的项目服务器在批准启用前保持关闭。
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`(及已安装的 Copilot CLI 插件)、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
- **按会话覆盖(`MCP` / `/mcp`)**:在 **新建 Agent 任务** 和进行中的任务对话中,单击输入框工具栏的 **MCP**(或输入 `/mcp`),即可仅针对当前任务开启或关闭任意服务器(包括内置的 `openidea` 服务器),或点击 **重置** 恢复继承的默认状态。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。在 **设置 › 智能体 › 工作状态** 中可以让这里改为显示与当前工作相关的趣味文字,默认关闭。开启后,工作一变化就轮换显示,也可以设置在 agent 无新进展多少秒后才显示(0 到 600,默认 0);屏幕阅读器读出的仍是 agent 实际在做的事。agent 持续做同一类工作时,每条文字停留八秒;转向其他工作时也至少停留三秒,状态行不会频繁跳动。同一页面还可以替换这些文字:选择状态(**正在读取…**、**正在运行命令…**…),再添加或移除对应的文字。**恢复内置文字** 会换回 OpenIDEA 自带的文字;没有任何文字的状态只显示实际进展。
+4 -2
Переглянути файл
@@ -45,14 +45,16 @@ Java 语言服务器(jdtls)会分析它导入的每个模块,所以大型
Windows 安装包目前还没有代码签名,Microsoft Defender SmartScreen 可能提示“未知发布者”。点击 **更多信息**,再点击 **仍要运行**。参见[安装](/zh/guide/install)。
## Linux 上窗口一片空白
## Linux 上窗口空白或无响应
在使用 NVIDIA 驱动的 Wayland 会话中,WebKitGTK 的 DMA-BUF 渲染器会出错。OpenIDEA 检测到这种组合时会自动设置 `WEBKIT_DISABLE_DMABUF_RENDERER=1`。如果在其他环境下也出现空白或显示异常的窗口,先退出 OpenIDEA,再在终端中带上这个变量启动,例如:
在部分 Wayland 环境中,WebKitGTK 的 DMA-BUF 渲染器会出错。在使用 NVIDIA 驱动的 Wayland 会话中,OpenIDEA 会为自身关闭驱动的显式同步(`__NV_DISABLE_EXPLICIT_SYNC=1`),这样既能避开问题,又能保留该渲染器。如果在其他环境下窗口一片空白、显示异常,或启动几秒后键盘和鼠标都没有反应,先退出 OpenIDEA,再在终端中关闭 DMA-BUF 渲染器启动,例如:
```sh
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
```
这样页面不再用 GPU 绘制,拖动较大的面板可能变慢。使用 deb 或 rpm 包时,如果希望从应用菜单启动也带上这个设置,把 `/usr/share/applications/OpenIDEA.desktop` 复制到 `~/.local/share/applications/`,并把其中的 `Exec=` 一行改成 `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`。
## 启动时提示数据目录错误并退出
`OPENIDEA_LOCAL_DATA_DIR` 被设成了相对路径或不可写的文件夹。修正或删除这个变量即可。参见[数据目录与日志](/zh/reference/data-directories)。
+117
Переглянути файл
@@ -0,0 +1,117 @@
import type { Locator, Page } from "@playwright/test";
import type { AgentTask } from "../src/bindings";
import { expect, test } from "./fixtures";
const task: AgentTask = {
id: "composer-popup",
title: "Composer popup task",
provider: "codex",
status: "ready",
isolation: "local",
model: null,
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
async function openTask(page: Page, delayFiles = false) {
await page.evaluate(
async ({ task, delayFiles }) => {
// Load the workbench modules in Vite's browser realm, not the Playwright runner.
const storePath = "/src/features/agents/store.ts";
const ipcPath = "/src/platform/ipc.ts";
const store = await import(storePath);
const { commands } = await import(ipcPath);
const { promise: filesReady, resolve } = Promise.withResolvers<void>();
if (delayFiles) window.addEventListener("test:release-composer-files", () => resolve(), { once: true });
else resolve();
const file = (name: string) => ({ path: `${task.cwd}/${name}`, relPath: name, score: 1, indices: [] });
commands.agentChanges = async () => ({ status: "ok", data: [] });
commands.findFiles = async (query: string) => {
if (!query) await filesReady;
return {
status: "ok",
data: query ? [file("a.ts")] : Array.from({ length: 12 }, (_, i) => file(`file${i}.ts`)),
};
};
commands.findDirs = async () => ({ status: "ok", data: [] });
store.useAgents.setState({
loaded: true,
error: null,
providers: [],
tasks: new Map([[task.id, task]]),
entries: new Map([[task.id, [{ type: "agent", text: "Reply" }]]]),
composers: new Map(),
unread: new Set(),
docked: null,
homeOpen: false,
sessionLocation: "editor",
});
store.openTask(task.id);
},
{ task, delayFiles },
);
const editor = page.getByRole("textbox", { name: "Message", exact: true });
await editor.click();
return { editor, list: page.getByRole("listbox", { name: "Files", exact: true }) };
}
function geometry(list: Locator) {
return list.evaluate((list) => {
const popup = list.closest<HTMLElement>("[data-popup]")!;
const rect = popup.getBoundingClientRect();
const caret = getSelection()!.getRangeAt(0).getBoundingClientRect();
const footer = popup.querySelector("span:last-child > kbd")!.getBoundingClientRect();
return {
side: rect.bottom <= caret.top ? "above" : rect.top >= caret.bottom ? "below" : "overlap",
height: popup.offsetHeight,
listHeight: list.clientHeight,
inViewport: rect.top >= 0 && rect.bottom <= innerHeight && rect.left >= 0 && rect.right <= innerWidth,
footerVisible: footer.height > 0 && footer.top >= rect.top && footer.bottom <= rect.bottom,
};
});
}
const fullList = { side: "above", listHeight: 300, inViewport: true, footerVisible: true };
test("erasing the @ filter restores the popup's fitting side and height", async ({ workbench: page }) => {
const { editor, list } = await openTask(page);
await editor.pressSequentially("@");
await expect(list.getByText("file0.ts", { exact: true })).toBeVisible();
await expect.poll(() => geometry(list)).toMatchObject(fullList);
const initial = await geometry(list);
await editor.pressSequentially("a");
await expect(list.getByText("a.ts", { exact: true })).toBeVisible();
await expect.poll(() => geometry(list)).toMatchObject({ side: "below", footerVisible: true });
await editor.press("Backspace");
await expect(list.getByText("file0.ts", { exact: true })).toBeVisible();
await expect.poll(() => geometry(list)).toEqual(initial);
await expect(editor).toBeFocused();
await expect(editor).toHaveText("@");
});
test("first-open @ results can grow and flip after asynchronous file search", async ({ workbench: page }) => {
const { editor, list } = await openTask(page, true);
for (let i = 0; i < 3; i++) await editor.press("Shift+Enter");
await editor.press("ArrowUp");
await editor.press("ArrowUp");
await editor.press("ArrowUp");
await editor.pressSequentially("@");
await expect(list.getByRole("option").first()).toBeVisible();
await expect.poll(() => geometry(list)).toMatchObject({ side: "below", footerVisible: true });
await expect(list.getByText("file0.ts", { exact: true })).toHaveCount(0);
await page.evaluate(() => window.dispatchEvent(new Event("test:release-composer-files")));
await expect(list.getByText("file0.ts", { exact: true })).toBeVisible();
await expect.poll(() => geometry(list)).toMatchObject(fullList);
await expect(editor).toBeFocused();
});
+1
Переглянути файл
@@ -416,6 +416,7 @@ test("dragging the Changes pane's edge resizes it for the next session too", asy
// The next session starts with the dragged width.
await page.reload();
await expect(page.getByRole("tree", { name: "Project" })).toBeVisible();
await seedTasks(page, "editor");
await seedChanges(page);
await expect.poll(async () => Math.round((await changes.boundingBox())!.width)).toBe(Math.round(widened));
+34
Переглянути файл
@@ -1024,3 +1024,37 @@ test("aligns Mermaid diagrams in replies to their container align attribute", as
expect(Math.abs(offsets[2]!.rightGap)).toBeLessThanOrEqual(1);
expect(Math.abs(offsets[3]!.leftGap - offsets[3]!.rightGap)).toBeLessThanOrEqual(1.5);
});
test("renders LaTeX math formulas with KaTeX and keeps wide equations scrollable", async ({ page }) => {
const reply = await openReply(
page,
[
"Inline $E = mc^2$ and \\(a^2 + b^2 = c^2\\), prices $5 and $10 stay plain.",
"",
"$$",
"\\int_{-\\infty}^{\\infty} e^{-x^2} \\, dx = \\sqrt{\\pi}",
"$$",
"",
"```math",
"\\sum_{k=1}^{n} k = \\frac{n(n+1)}{2} + a_1 + a_2 + a_3 + a_4 + a_5 + a_6 + a_7 + a_8 + a_9 + a_{10}",
"```",
].join("\n"),
);
await expect(reply.locator(".katex")).toHaveCount(4);
await expect(reply.locator(".katex-display")).toHaveCount(2);
await expect(reply).toContainText("prices $5 and $10 stay plain.");
const layout = await reply.evaluate((el) => {
const firstKatex = el.querySelector<HTMLElement>(".katex")!;
const display = el.querySelectorAll<HTMLElement>(".katex-display");
const font = getComputedStyle(firstKatex).fontFamily;
return {
font,
height: firstKatex.getBoundingClientRect().height,
overflowX: getComputedStyle(display[1]!).overflowX,
};
});
expect(layout.font).toContain("KaTeX_Main");
expect(layout.height).toBeGreaterThan(10);
expect(layout.overflowX).toBe("auto");
});
+1 -1
Переглянути файл
@@ -102,7 +102,7 @@ test("stripe themes inherit base tooltip tokens and keep shortcut text readable"
delete root.dataset.colorTheme;
root.dataset.theme = kind;
root.dataset.pluginTheme = "test/base-tooltip";
const path = "/src/features/plugins/bridge.ts";
const path = "/src/features/plugins/themeRuntime.ts";
const { pluginThemeCss } = await import(/* @vite-ignore */ path);
const style = document.createElement("style");
style.id = "test-plugin-theme";
+1
Переглянути файл
@@ -80,6 +80,7 @@
"dompurify": "^3.4.17",
"emmet": "2.4.11",
"immer": "^11.1.21",
"katex": "^0.19.1",
"marked": "^18.1.1",
"mermaid": "12.1.0",
"react": "^19.1.0",
Створено
+11
Переглянути файл
@@ -119,6 +119,9 @@ importers:
immer:
specifier: ^11.1.21
version: 11.1.21
katex:
specifier: ^0.19.1
version: 0.19.1
marked:
specifier: ^18.1.1
version: 18.1.1
@@ -1799,6 +1802,10 @@ packages:
resolution: {integrity: sha512-/B6p9eY9DX7aHBfpkHdpirDTZ5QH9xTwL9y837PWuzuv41O5jFdqNQwVQEQsimY0/iVNkwBY4+4hMfhQ7d4Dbw==}
hasBin: true
[email protected]:
resolution: {integrity: sha512-jG8uKntjSEcm2EpQOh0XturpPuuC9r3Sq5HLHdsFdWZT27E672SF19QEi+of0/YeOy15lDgRhKvr5614uRrEfA==}
hasBin: true
[email protected]:
resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==}
@@ -3792,6 +3799,10 @@ snapshots:
dependencies:
commander: 15.1.0
[email protected]:
dependencies:
commander: 15.1.0
[email protected]: {}
[email protected]:
+19 -5
Переглянути файл
@@ -136,34 +136,48 @@
window.removeEventListener("unhandledrejection", onRejection);
window.removeEventListener("openidea:boot-error", onBootError);
window.removeEventListener("openidea:boot-ready", onReady);
window.removeEventListener("openidea:boot-question", onQuestion);
window.removeEventListener("openidea:boot-answer", onAnswer);
document.removeEventListener("visibilitychange", onVisibility);
};
// The timeout counts only while the window shows: a hidden or covered window gets no
// animation frames, and the splash waits for those to finish startup.
// The timeout counts only while the window shows and nothing waits for the user: a hidden
// or covered window gets no animation frames, and the splash waits for those to finish
// startup; a question asked over the splash (Trust Project) holds it until answered.
let remaining = 60_000;
let armedAt = 0;
let timer;
let questions = 0;
const arm = () => {
if (failed || ready || timer !== undefined || document.hidden) return;
if (failed || ready || timer !== undefined || document.hidden || questions > 0) return;
armedAt = Date.now();
timer = window.setTimeout(
() => show(rejection === undefined ? text.timeout : `${text.timeout}\n\nUnhandled rejection: ${rejection}`),
remaining,
);
};
const onVisibility = () => {
if (!document.hidden) return arm();
const pause = () => {
if (timer === undefined) return;
window.clearTimeout(timer);
timer = undefined;
remaining -= Date.now() - armedAt;
};
const onVisibility = () => (document.hidden ? pause() : arm());
const onQuestion = () => {
questions += 1;
pause();
};
const onAnswer = () => {
questions = Math.max(0, questions - 1);
arm();
};
arm();
document.addEventListener("visibilitychange", onVisibility);
window.addEventListener("error", onError, true);
window.addEventListener("unhandledrejection", onRejection);
window.addEventListener("openidea:boot-error", onBootError);
window.addEventListener("openidea:boot-ready", onReady);
window.addEventListener("openidea:boot-question", onQuestion);
window.addEventListener("openidea:boot-answer", onAnswer);
})();
// Runs before the app's CSS loads: restores the last theme (theme.ts stores it)
+2
Переглянути файл
@@ -93,10 +93,12 @@ db_connect trusted project_host bin
db_connected trusted project_host bindings sync
db_console_path always project_host bindings sync
db_consoles always project_host bindings sync
db_create_database trusted project_host bindings async
db_database_catalog trusted project_host bindings async
db_databases trusted project_host bindings async
db_ddl trusted project_host bindings async
db_disconnect trusted project_host bindings async
db_drop_database trusted project_host bindings async
db_dump_info trusted desktop bindings async
db_execute trusted project_host bindings async
db_explain trusted project_host bindings async
+29
Переглянути файл
@@ -0,0 +1,29 @@
import type { AuxKind } from "./platform/auxWindow";
import { mountWindowRoot } from "./windowBoot";
import { activateSecondaryWindow } from "./workbench/activateSecondary";
export async function bootAuxiliaryWindow(aux: { kind: AuxKind; parent: string }): Promise<void> {
activateSecondaryWindow();
switch (aux.kind) {
case "settings": {
const { bootSettingsWindow } = await import("./settingsWindowBoot");
mountWindowRoot(bootSettingsWindow(aux.parent));
return;
}
case "comparison": {
const { bootComparisonWindow } = await import("./comparisonWindowBoot");
mountWindowRoot(bootComparisonWindow(aux.parent));
return;
}
case "diff": {
const { bootDiffWindow } = await import("./diffWindowBoot");
mountWindowRoot(bootDiffWindow(aux.parent));
return;
}
case "deployment": {
const { bootDeploymentWindow } = await import("./deploymentWindowBoot");
mountWindowRoot(bootDeploymentWindow(aux.parent));
return;
}
}
}
+26 -7
Переглянути файл
@@ -15,11 +15,24 @@ export const commands = {
/** Answers a non-blocking question, without cancelling the current turn. */
agentAnswerQuestion: (task: string, question: string, answer: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_answer_question", { task, question, answer })),
agentArchive: (task: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_archive", { task })),
/** Content of `path` when the task started (left side of its diff). */
agentBaseText: (task: string, path: IpcPath) => typedError<string | null, IdeError>(__TAURI_INVOKE("agent_base_text", { task, path })),
/** Content of `path` as `view` compares it (without: when the task started), the left side of its diff. */
agentBaseText: (task: string, path: IpcPath, view:
/** Everything since the commit the task started from. */
"sinceStart" |
/** The uncommitted files against `HEAD`; commits made since the start stay. */
"group" |
/** What the last turn changed, against the checkout as that turn started. */
"lastTurn" | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("agent_base_text", { task, path, view })),
/** Stops the task's current turn, or with `subagent` only that subagent's work. */
agentCancel: (task: string, subagent: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_cancel", { task, subagent })),
agentChanges: (task: string) => typedError<AgentChange[], IdeError>(__TAURI_INVOKE("agent_changes", { task })),
/** The task's changed files as `view` compares them (without: since it started). */
agentChanges: (task: string, view:
/** Everything since the commit the task started from. */
"sinceStart" |
/** The uncommitted files against `HEAD`; commits made since the start stay. */
"group" |
/** What the last turn changed, against the checkout as that turn started. */
"lastTurn" | null) => typedError<AgentChange[], IdeError>(__TAURI_INVOKE("agent_changes", { task, view })),
/**
* Slash commands to complete for `provider` in `task`'s directory, or in the project
* before a task exists (skills and custom commands on disk included).
@@ -103,7 +116,9 @@ export const commands = {
/** Everything since the commit the task started from. */
"sinceStart" |
/** The uncommitted files against `HEAD`; commits made since the start stay. */
"group" | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_rollback_changes", { task, paths, view })),
"group" |
/** What the last turn changed, against the checkout as that turn started. */
"lastTurn" | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_rollback_changes", { task, paths, view })),
/** Sends a queued message now, interrupting the current turn. */
agentSendQueuedNow: (task: string, queued: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_send_queued_now", { task, queued })),
/**
@@ -272,10 +287,12 @@ export const commands = {
dbConsolePath: (id: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("db_console_path", { id })),
/** The query consoles of data source `id`; `create` adds the next one first. */
dbConsoles: (id: string, create: boolean) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("db_consoles", { id, create })),
dbCreateDatabase: (id: string, template: string, statement: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_create_database", { id, template, statement })),
dbDatabaseCatalog: (id: string, database: string) => typedError<DbCatalogSchema[], IdeError>(__TAURI_INVOKE("db_database_catalog", { id, database })),
dbDatabases: (id: string) => typedError<DbDatabases, IdeError>(__TAURI_INVOKE("db_databases", { id })),
dbDdl: (id: string, schema: string, table: string) => typedError<string, IdeError>(__TAURI_INVOKE("db_ddl", { id, schema, table })),
dbDisconnect: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_disconnect", { id })),
dbDropDatabase: (id: string, database: string, statement: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_drop_database", { id, database, statement })),
/** What made the dump at `path` and whether it creates its own database (from its first bytes). */
dbDumpInfo: (path: string) => typedError<DbDumpInfo, IdeError>(__TAURI_INVOKE("db_dump_info", { path })),
dbExecute: (request: RequestId, id: string, statements: SqlStatement[], skip: number, maxRows: number, schema: string | null) => typedError<DbStatementOutcome[], IdeError>(__TAURI_INVOKE("db_execute", { request, id, statements, skip, maxRows, schema })),
@@ -1293,8 +1310,8 @@ export const commands = {
*
* Edits go through the document layer as one patch per file, so open editors
* update live and undo the whole file's replacements in one step. Unsaved
* editor buffers are replaced in place and left unsaved; files that were not
* open are opened transiently, saved and closed.
* editor buffers are replaced in place and left unsaved; other open documents
* are saved, and files that were not open are opened transiently, saved and closed.
*
* With `all_in_scope` (Replace All after the search hit its match limit) the
* scope is searched again without the limit and every match in it is replaced,
@@ -2069,7 +2086,9 @@ export type AgentChangesView =
/** Everything since the commit the task started from. */
"sinceStart" |
/** The uncommitted files against `HEAD`; commits made since the start stay. */
"group";
"group" |
/** What the last turn changed, against the checkout as that turn started. */
"lastTurn";
export type AgentCommand = {
/** Without the leading `/`. */
+27
Переглянути файл
@@ -0,0 +1,27 @@
import type { ComponentType } from "react";
import { activate as editor } from "./editor/core";
import { confirmLeave } from "./features/app/closeGuard";
import { installLocaleSync } from "./features/app/locale";
import { installMenuBridge } from "./features/app/menuBridge";
import { trackRuntimeSettings } from "./features/settings/runtime";
import { activate as vcs } from "./features/vcs";
import { activateComparisonWindow, ComparisonWindow } from "./features/vcs/ComparisonWindow";
import { installKeyboardDispatcher } from "./platform/keymap";
import { activateList } from "./windowBoot";
/**
* Comparison window of project window `parent`: changed files between two
* revisions and their diffs, with the editor and Git but no workbench.
*/
export function bootComparisonWindow(parent: string): ComponentType {
activateList("comparison window", [
["locale", installLocaleSync],
["settings", trackRuntimeSettings],
["menu", installMenuBridge],
["editor", editor],
["vcs", vcs],
["comparison", () => activateComparisonWindow(parent, (project) => confirmLeave(undefined, project))],
]);
installKeyboardDispatcher();
return ComparisonWindow;
}
+20
Переглянути файл
@@ -0,0 +1,20 @@
import type { ComponentType } from "react";
import { installLocaleSync } from "./features/app/locale";
import { activateDeploymentWindow, DeploymentWindow } from "./features/deployment/window";
import { trackRuntimeSettings } from "./features/settings/runtime";
import { activateDiffViewer } from "./features/vcs/diffViewer";
import { activateList } from "./windowBoot";
/**
* Sync with Deployed window of project window `parent`: local files next to
* their copies on a deployment server, with the diff viewer but no workbench.
*/
export function bootDeploymentWindow(parent: string): ComponentType {
activateList("deployment window", [
["locale", installLocaleSync],
["settings", trackRuntimeSettings],
["diff", activateDiffViewer],
["deployment", () => activateDeploymentWindow(parent)],
]);
return DeploymentWindow;
}
+24
Переглянути файл
@@ -0,0 +1,24 @@
import type { ComponentType } from "react";
import { installLocaleSync } from "./features/app/locale";
import { installMenuBridge } from "./features/app/menuBridge";
import { trackRuntimeSettings } from "./features/settings/runtime";
import { activate as vcs } from "./features/vcs";
import { activateDiffWindow, DiffWindow } from "./features/vcs/DiffWindow";
import { installKeyboardDispatcher } from "./platform/keymap";
import { activateList } from "./windowBoot";
/**
* Diff window of project window `parent`: one file's diff, with Git and its own
* documents but no workbench.
*/
export function bootDiffWindow(parent: string): ComponentType {
activateList("diff window", [
["locale", installLocaleSync],
["settings", trackRuntimeSettings],
["menu", installMenuBridge],
["vcs", vcs],
["diff", () => activateDiffWindow(parent)],
]);
installKeyboardDispatcher();
return DiffWindow;
}
+16 -1
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { registerEditorKind, type EditorKindContribution } from "@/workbench/contributions";
import { registerEditorKind, setFileDecorations, type EditorKindContribution } from "@/workbench/contributions";
import { t } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import { confirm } from "@/workbench/messages";
@@ -166,3 +166,18 @@ describe("editor kinds' isBusy on tab-limit eviction", () => {
}
});
});
describe("Close non-modified files first", () => {
it("keeps a tab with a VCS change, as Close Unmodified Tabs does", async () => {
controller = new EditorController(createMemoryBackend({ "/p/a.ts": "a", "/p/b.ts": "b", "/p/c.ts": "c" }));
controller.start();
useProject.setState({ settings: { editor: { tabs: { tabLimit: 2, closingPolicy: "unchanged" } } } as never });
setFileDecorations("vcs", new Map([["/p/a.ts", { color: "modified" }]]));
try {
for (const path of ["/p/a.ts", "/p/b.ts", "/p/c.ts"]) await controller.openFile(path);
expect(pane().tabs.map((tab) => tab.input.path)).toEqual(["/p/a.ts", "/p/c.ts"]);
} finally {
setFileDecorations("vcs", new Map());
}
});
});
+14 -9
Переглянути файл
@@ -272,6 +272,14 @@ export function tabTrailing(input: EditorInput, kinds: EditorKinds): ReactNode {
}
}
/** Unsaved changes or a VCS status: what Close Unmodified Tabs and the tab limit's policy keep. */
function tabModified(tab: Tab): boolean {
return (
(inputDirty(tab.input, useContributions.getState().editorKinds) ?? false) ||
!!(tab.input.path && (useDocMeta.getState()[tab.input.path]?.dirty || getFileDecoration(tab.input.path)?.color))
);
}
export class EditorController implements SlotHost {
manager: DocumentManager;
readonly slots = new Map<string, EditorSlot>();
@@ -387,10 +395,11 @@ export class EditorController implements SlotHost {
// Untitled buffers belong to the window, not a project: their tabs
// survive the switch (the backend carries them into the new
// registry) and their slots rebuild against the carried documents.
// Closing to Welcome drops them; the leave guard already asked about them.
const carriedUntitled: Tab[] = [];
let carriedActive: string | null = null;
const cs = useTabs.getState();
for (const pane of Object.values(cs.panes)) {
for (const pane of root || s.lightEdit ? Object.values(cs.panes) : []) {
for (const tab of pane.tabs) {
if (isUntitledUri(tab.input.path ?? "")) {
carriedUntitled.push(tab);
@@ -1440,8 +1449,7 @@ export class EditorController implements SlotHost {
paneId,
prefs.tabLimit,
prefs.closingPolicy,
(tab) =>
inputDirty(tab.input, kinds) ?? !!(tab.input.path && useDocMeta.getState()[tab.input.path]?.dirty),
tabModified,
keep ?? current.panes[paneId]?.active ?? undefined,
protect,
)
@@ -1725,13 +1733,10 @@ export class EditorController implements SlotHost {
protect: (tab) => tab.pinned,
});
}
/** Keeps tabs with unsaved changes or a VCS status (IDEA: tabs shown as modified). */
/** Keeps tabs with unsaved changes or a VCS status (tabs shown as modified). */
closeUnmodified(paneId: string): Promise<boolean> {
const modified = (tab: Tab) =>
(inputDirty(tab.input, useContributions.getState().editorKinds) ?? false) ||
!!(tab.input.path && (useDocMeta.getState()[tab.input.path]?.dirty || getFileDecoration(tab.input.path)?.color));
return this.removeGuarded((s) => (s.panes[paneId] ? closeUnmodified(s, paneId, modified) : s), {
protect: (tab) => tab.pinned || modified(tab),
return this.removeGuarded((s) => (s.panes[paneId] ? closeUnmodified(s, paneId, tabModified) : s), {
protect: (tab) => tab.pinned || tabModified(tab),
});
}
closeReadOnly(paneId: string): Promise<boolean> {
+14
Переглянути файл
@@ -15,6 +15,7 @@ const { serializeSession } = await import("./model/session");
const { useDocMeta } = await import("./model/document");
const { save } = await import("@/platform/dialog");
const editorKinds = await import("@/workbench/contributions");
const { useProject } = await import("@/platform/project");
let ctrl: InstanceType<typeof EditorController> | null = null;
let backend: MemoryBackend;
@@ -158,6 +159,19 @@ describe("untitled editor input", () => {
expect([...backend.files.keys()]).toEqual(["/p/main.rs"]);
});
it("follows the window into another project but not to the Welcome screen", async () => {
const project = (root: string) => ({ root, name: root, trusted: true, isGit: false, settings: {} }) as never;
try {
await ctrl!.openUntitled({ focus: false });
useProject.setState({ project: project("/a") });
expect(activeTab().input.kind).toBe("untitled");
useProject.setState({ project: null });
expect(Object.values(useTabs.getState().panes).flatMap((p) => p.tabs)).toEqual([]);
} finally {
useProject.setState({ project: null });
}
});
it("reuses the buffer for a re-opened untitled name and shares it across tabs", async () => {
const info = await backend.openUntitled(null);
const twice = await backend.openUntitled("untitled:Untitled-1");
+8
Переглянути файл
@@ -69,6 +69,14 @@ describe("markdown rendering", () => {
expect(md.markupToHtml({ kind: "markdown", value: "`x`" })).toBe("<p><code>x</code></p>\n");
expect(md.markupToHtml({ kind: "plaintext", value: "<b>" })).toBe('<p class="cm-lsp-plain">&#60;b&#62;</p>');
});
it("renders LaTeX math in LSP / documentation markdown", async () => {
const md = await freshMarkdown();
await md.loadMarkdown();
const root = document.createElement("div");
root.innerHTML = md.markupToHtml({ kind: "markdown", value: "Complexity $O(n \\log n)$" });
expect(root.querySelector(".katex")).not.toBeNull();
});
});
// On Windows, opening `//server/share` signs in to that server with the user's credentials.
+13
Переглянути файл
@@ -0,0 +1,13 @@
.katex {
overflow-wrap: normal;
}
.katex-display {
overflow-x: auto;
overflow-y: hidden;
padding: 2px 0;
}
.katex-error {
color: var(--danger) !important;
}
+85
Переглянути файл
@@ -0,0 +1,85 @@
import { describe, expect, it } from "vitest";
import { Marked } from "marked";
import DOMPurify from "dompurify";
import { mathExtension, renderMath } from "./markdownMath";
const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension());
function parseSafe(md: string): HTMLElement {
const html = marked.parse(md, { async: false }) as string;
const root = DOMPurify.sanitize(html, {
USE_PROFILES: { html: true },
ADD_ATTR: ["data-math"],
FORBID_TAGS: ["style", "form"],
FORBID_ATTR: ["style"],
RETURN_DOM: true,
}) as HTMLElement;
renderMath(root);
return root;
}
describe("markdown LaTeX math", () => {
it("renders inline $...$ and avoids currency false positives", () => {
const root = parseSafe(
"Energy $E = mc^2$ and CJK 设$x=1$时.\n\nPrices: $5 and $10, or $5-$10, or $ 5 $, or \\$x\\$.",
);
expect(root.querySelectorAll(".katex")).toHaveLength(2);
expect(root.querySelectorAll(".katex-display")).toHaveLength(0);
const paras = [...root.querySelectorAll("p")];
expect(paras[1]!.textContent).toBe("Prices: $5 and $10, or $5-$10, or $ 5 $, or $x$.");
});
it("prevents * and _ inside math from triggering emphasis while allowing emphasis around math", () => {
const root = parseSafe("Formula $(a)_1 + (b)_2$ and $a * b$ and $c * d$, plus **$x^2$**.");
expect(root.querySelector("em")).toBeNull();
expect(root.querySelectorAll(".katex")).toHaveLength(4);
expect(root.querySelector("strong .katex")).not.toBeNull();
});
it("renders multi-line, single-line, inline, and adjacent $$...$$ blocks", () => {
const root = parseSafe(
"Para\n$$\n\\begin{aligned}\na &= b \\\\\nc &= d\n\\end{aligned}\n$$\n\n$$E = mc^2$$\n\n$$a$$ and $$b$$",
);
expect(root.querySelectorAll(".katex-display")).toHaveLength(4);
expect(root.querySelector("p")?.textContent).toBe("Para");
const lastP = [...root.querySelectorAll("p")].at(-1)!;
expect(lastP.querySelectorAll(".katex-display")).toHaveLength(2);
expect(lastP.textContent).toContain("and");
});
it("renders \\(...\\) and \\[...\\] without breaking escaped links", () => {
const root = parseSafe("Inline \\(x + y\\).\n\n\\[\nx^2 + y^2 = z^2\n\\]\n\n\\[text\\](https://example.com)");
expect(root.querySelectorAll(".katex")).toHaveLength(2);
expect(root.querySelectorAll(".katex-display")).toHaveLength(1);
const lastP = [...root.querySelectorAll("p")].at(-1)!;
expect(lastP.textContent).toBe("[text](https://example.com)");
});
it("renders ```math code blocks while keeping ```latex and inline code literal", () => {
const root = parseSafe("```math\n\\int_0^1 x^2 dx\n```\n\n```latex\n$x$\n```\n\nInline `$y$`.");
expect(root.querySelectorAll(".katex-display")).toHaveLength(1);
expect(root.querySelector("pre > code.language-latex")?.textContent).toBe("$x$\n");
expect(root.querySelector("p > code")?.textContent).toBe("$y$");
});
it("renders invalid LaTeX as an error node instead of throwing", () => {
const root = parseSafe("Bad $\\unknowncommand{x}$ and $$\\frac{1$$");
expect(root.querySelectorAll(".katex")).toHaveLength(1);
expect(root.querySelector(".katex-error")).not.toBeNull();
expect(root.textContent).toContain("\\unknowncommand");
});
it("blocks unsafe LaTeX trust commands and raw HTML style/script injection", () => {
const root = parseSafe(
[
"$\\href{javascript:alert(1)}{click}$",
'<div style="position:fixed">x</div>',
'<span data-math="inline"><img src=x onerror=alert(1)>a</span>',
].join("\n\n"),
);
expect(root.querySelector("a")).toBeNull();
expect(root.querySelector("img")).toBeNull();
expect(root.querySelector("div[style]")).toBeNull();
expect(root.querySelectorAll(".katex")).toHaveLength(2);
});
});
+215
Переглянути файл
@@ -0,0 +1,215 @@
/**
* LaTeX math support for Markdown (`marked` + `DOMPurify` + KaTeX).
*
* `mathExtension()` tokenizes `$$...$$`, `$...$`, `\[...\]`, `\(...\)`, and
* ```` ```math ```` blocks into sanitized-safe `<div|span data-math="display|inline">`
* placeholders, which survive `DOMPurify` (with `data-math` allowed) and are
* rendered synchronously into KaTeX DOM by `renderMath()` right after sanitization.
*/
import katex from "katex";
import "katex/dist/katex.min.css";
import "./markdownMath.css";
import type { MarkedExtension, Tokens } from "marked";
interface MathToken extends Tokens.Generic {
type: "blockMath" | "inlineMath";
raw: string;
text: string;
display: boolean;
}
const escapeHtml = (s: string) =>
s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
export function mathPlaceholder(tex: string, display: boolean, block = display): string {
const tag = block ? "div" : "span";
const mode = display ? "display" : "inline";
return `<${tag} data-math="${mode}">${escapeHtml(tex)}</${tag}>`;
}
/** Finds the closing `delim` (`$$`, `\)`, or `\]`) skipping `\` escapes. Returns content end index or -1. */
function findClosingDelimiter(src: string, from: number, delim: string): number {
for (let i = from; i < src.length; i++) {
if (src.startsWith(delim, i)) return i;
if (src[i] === "\\") {
i++;
continue;
}
}
return -1;
}
/**
* Matches inline `$...$` from index 0 using Pandoc-style guards so currency
* like `$5 and $10` or `$5-$10` stays plain text while `$x$`, `设$x=1$`, etc. match.
*/
function matchInlineDollar(src: string): { end: number; text: string } | null {
if (src[0] !== "$" || src[1] === "$" || !src[1] || /\s/.test(src[1])) return null;
for (let i = 1; i < src.length; i++) {
const ch = src[i]!;
if (ch === "\\") {
i++;
continue;
}
if (ch === "\n" && (src[i + 1] === "\n" || (src[i + 1] === "\r" && src[i + 2] === "\n"))) {
return null;
}
if (ch === "$") {
if (i <= 1 || /\s/.test(src[i - 1]!)) continue;
const next = src[i + 1] ?? "";
if (next === "$" || /\d/.test(next)) return null;
const text = src.slice(1, i);
if (!text.trim()) return null;
return { end: i + 1, text };
}
}
return null;
}
/** Matches inline `$$...$$`, `$...$`, `\(...\)`, or `\[...\]` starting at index 0 of `src`. */
function matchInlineMath(src: string): { raw: string; text: string; display: boolean } | null {
if (src.startsWith("$$")) {
const close = findClosingDelimiter(src, 2, "$$");
if (close > 2) {
const text = src.slice(2, close);
if (text.trim()) return { raw: src.slice(0, close + 2), text, display: true };
}
return null;
}
if (src[0] === "$") {
const m = matchInlineDollar(src);
return m ? { raw: src.slice(0, m.end), text: m.text, display: false } : null;
}
if (src.startsWith("\\(")) {
const close = findClosingDelimiter(src, 2, "\\)");
if (close > 2) {
const text = src.slice(2, close);
if (text.trim()) return { raw: src.slice(0, close + 2), text, display: false };
}
return null;
}
if (src.startsWith("\\[")) {
const close = findClosingDelimiter(src, 2, "\\]");
if (close > 2 && src[close + 2] !== "(") {
const text = src.slice(2, close);
if (text.trim()) return { raw: src.slice(0, close + 2), text, display: true };
}
return null;
}
return null;
}
const BLOCK_DOLLAR_MULTI = /^ {0,3}\$\$[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*\$\$[ \t]*(?:\r?\n+|$)/;
const BLOCK_DOLLAR_SINGLE = /^ {0,3}\$\$((?:\\[\s\S]|[^$\n]|\$(?!\$))+?)\$\$[ \t]*(?:\r?\n+|$)/;
const BLOCK_BRACKET_MULTI = /^ {0,3}\\\[[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*\\\][ \t]*(?:\r?\n+|$)/;
const BLOCK_BRACKET_SINGLE = /^ {0,3}\\\[((?:\\[\s\S]|[^\\\n]|\\(?!\]))+?)\\\][ \t]*(?:\r?\n+|$)/;
function matchBlockMath(src: string): { raw: string; text: string } | null {
for (const re of [BLOCK_DOLLAR_MULTI, BLOCK_DOLLAR_SINGLE, BLOCK_BRACKET_MULTI, BLOCK_BRACKET_SINGLE]) {
const m = re.exec(src);
if (m && m[1]!.trim()) return { raw: m[0], text: m[1]! };
}
return null;
}
/** Masks math spans with `a`s (preserving newlines) so `*` and `_` inside math never trigger emphasis. */
function maskInlineMath(src: string): string {
let out = "";
let i = 0;
while (i < src.length) {
if (src[i] === "\\" && src[i + 1] !== "(" && src[i + 1] !== "[") {
out += src.slice(i, i + 2);
i += 2;
continue;
}
if (src[i] === "$" || (src[i] === "\\" && (src[i + 1] === "(" || src[i + 1] === "["))) {
const m = matchInlineMath(src.slice(i));
if (m) {
out += m.raw.replace(/[^\r\n]/g, "a");
i += m.raw.length;
continue;
}
}
out += src[i]!;
i++;
}
return out;
}
export function mathExtension(): MarkedExtension {
return {
hooks: {
emStrongMask(src) {
return maskInlineMath(src);
},
},
renderer: {
code({ text, lang }) {
if (lang?.trim().split(/\s+/)[0]?.toLowerCase() !== "math") return false;
return `${mathPlaceholder(text, true, true)}\n`;
},
},
extensions: [
{
name: "blockMath",
level: "block",
start(src) {
const m = /\n {0,3}(?:\$\$|\\\[)/.exec(src);
return m ? m.index : undefined;
},
tokenizer(src): MathToken | undefined {
const m = matchBlockMath(src);
if (!m) return undefined;
return { type: "blockMath", raw: m.raw, text: m.text, display: true };
},
renderer(token) {
const t = token as MathToken;
return `${mathPlaceholder(t.text, true, true)}\n`;
},
},
{
name: "inlineMath",
level: "inline",
start(src) {
for (let i = 0; i < src.length; i++) {
const ch = src[i]!;
if (ch === "\\") {
const next = src[i + 1];
if (next === "(" || next === "[") return i;
i++;
continue;
}
if (ch === "$") return i;
}
return undefined;
},
tokenizer(src): MathToken | undefined {
const m = matchInlineMath(src);
if (!m) return undefined;
return { type: "inlineMath", raw: m.raw, text: m.text, display: m.display };
},
renderer(token) {
const t = token as MathToken;
return mathPlaceholder(t.text, t.display, false);
},
},
],
};
}
/** Renders every `[data-math]` placeholder inside `root` synchronously using KaTeX. */
export function renderMath(root: ParentNode): void {
root.querySelectorAll<HTMLElement>("[data-math]").forEach((el) => {
const mode = el.getAttribute("data-math");
el.removeAttribute("data-math");
if (mode !== "inline" && mode !== "display") return;
const tex = (el.textContent ?? "").trim();
if (!tex) return;
katex.render(tex, el, {
displayMode: mode === "display",
throwOnError: false,
strict: false,
trust: false,
});
});
}
+8 -3
Переглянути файл
@@ -1,19 +1,24 @@
/** Markdown → sanitized HTML (marked + DOMPurify); loaded on demand by `markdown.ts`. */
import { Marked } from "marked";
import DOMPurify from "dompurify";
import { mathExtension, renderMath } from "./markdownMath";
/** DOMPurify's default link schemes plus `file:` and jdtls' `jdt:` (library classes). */
const ALLOWED_URI = /^(?:(?:(?:f|ht)tps?|mailto|tel|file|jdt):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i;
const marked = new Marked({ gfm: true, breaks: false });
const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension());
export function markdownToSafeHtml(markdown: string): string {
const html = marked.parse(markdown, { async: false }) as string;
// Comments and docs come from anyone; a `<style>` here would restyle the whole IDE.
return DOMPurify.sanitize(html, {
const root = DOMPurify.sanitize(html, {
USE_PROFILES: { html: true },
ALLOWED_URI_REGEXP: ALLOWED_URI,
ADD_ATTR: ["data-math"],
FORBID_TAGS: ["style", "form"],
FORBID_ATTR: ["style"],
});
RETURN_DOM: true,
}) as HTMLElement;
renderMath(root);
return root.innerHTML;
}
+14
Переглянути файл
@@ -36,6 +36,20 @@ describe("Go to Test / Test Subject", () => {
expect(d.open).toHaveBeenCalledWith("/p/src/test/java/a/FooTest.java");
});
it("uses the top-level class at the caret when a file declares several", async () => {
const files = [
"/p/src/main/java/a/Widget.java",
"/p/src/test/java/a/WidgetTest.java",
"/p/src/test/java/a/HelperTest.java",
];
const d = { ...deps(files), classAtCaret: async () => "Helper" };
await gotoTestOrSubject("/p/src/main/java/a/Widget.java", "", d);
expect(d.open).toHaveBeenCalledWith("/p/src/test/java/a/HelperTest.java");
const other = { ...deps(files), classAtCaret: async () => null };
await gotoTestOrSubject("/p/src/main/java/a/Widget.java", "", other);
expect(other.open).toHaveBeenCalledWith("/p/src/test/java/a/WidgetTest.java");
});
it("goes back from a test to its subject", async () => {
const d = deps(["/p/src/main/java/a/Foo.java", "/p/src/test/java/a/FooTest.java"]);
await gotoTestOrSubject("/p/src/test/java/a/FooTest.java", "", d);
+14 -1
Переглянути файл
@@ -36,6 +36,19 @@ export interface TestNavDeps {
/** Create New Test… in `directory` (file templates), or a Rust test module in the file itself. */
createTest: (req: { directory: string; name: string; extension: string; subject: string }) => void;
createRustTestModule: () => void;
/** Name of the top-level class, interface, enum or object around the caret, if any. */
classAtCaret?: () => Promise<string | null>;
}
/** Languages whose files are named after a class but may declare several top-level ones. */
const CLASS_FILE = /\.(java|kt|scala|groovy|cs)$/;
/** The file name as the class at the caret would have it (`Helper.java` inside `Widget.java`), else the file's own. */
async function subjectFileName(path: string, deps: TestNavDeps): Promise<string> {
const name = basename(path);
if (!CLASS_FILE.test(name) || !deps.classAtCaret) return name;
const cls = await deps.classAtCaret().catch(() => null);
return cls ? cls + splitName(name).ext : name;
}
const isRustIntegrationTest = (path: string) => path.endsWith(".rs") && /\/tests\/[^/]+\.rs$/.test(path);
@@ -88,7 +101,7 @@ function relLabel(root: string | null, path: string) {
export async function gotoTestOrSubject(path: string, text: string, deps: TestNavDeps): Promise<void> {
const roots = deps.roots();
const root = deps.projectRoot();
const name = basename(path);
const name = await subjectFileName(path, deps);
const rank = (paths: string[]) => rankCandidates(path, paths, belowRoot(root, roots));
if (isTestSide(path, roots)) {
+5 -1
Переглянути файл
@@ -22,7 +22,7 @@ import { registerRelatedProvider, relatedItems } from "@/editor/relatedProviders
import { gotoTestOrSubject, type TestNavDeps } from "./gotoTest";
import { headerSourceItems } from "./headerSource";
import { projectPythonHierarchy, pythonSuperDeps } from "./pythonHierarchy";
import { baseName, memberAt, methodStop, superMethods, type SuperDeps } from "./structureNav";
import { baseName, memberAt, methodStop, superMethods, topLevelTypeAt, type SuperDeps } from "./structureNav";
import { tx } from "@/platform/i18n";
const EDITOR_WHEN = "textEditorActive && (editorFocus || !toolWindowFocus)";
@@ -150,6 +150,10 @@ function testDeps(view: EditorView, ctx: EditorDocContext): TestNavDeps {
})),
}),
hint: (text) => showHint(view, text),
classAtCaret: async () => {
const outline = await call(commands.docOutline(ctx.doc));
return topLevelTypeAt(outline, offsetToPos(view.state.doc, view.state.selection.main.head))?.name ?? null;
},
createTest: ({ directory, name, extension }) =>
void executeAction("templates.newFromTemplate", { directory, name, extension, kindId: "test" }),
createRustTestModule: () => {
+10 -1
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { HierarchyItem, OutlineItem, SymbolKind } from "@/platform/ipc";
import { memberAt, methodStop, methodStops, superMethods } from "./structureNav";
import { memberAt, methodStop, methodStops, superMethods, topLevelTypeAt } from "./structureNav";
const r = (l1: number, l2: number) => ({ start: { line: l1, col: 0 }, end: { line: l2, col: 1 } });
function item(name: string, kind: SymbolKind, from: number, to: number, children: OutlineItem[] = []): OutlineItem {
@@ -100,3 +100,12 @@ describe("Super Method", () => {
expect(await lines("eat")).toEqual([2, 4]);
});
});
describe("topLevelTypeAt", () => {
it("answers the outermost type, through namespaces, and nothing outside a type", () => {
expect(topLevelTypeAt(OUTLINE, { line: 13, col: 2 })?.name).toBe("Foo");
expect(topLevelTypeAt(OUTLINE, { line: 23, col: 0 })).toBeNull();
const ns = [item("App", "namespace", 0, 30, [item("Widget", "class", 1, 10), item("Helper", "class", 12, 20)])];
expect(topLevelTypeAt(ns, { line: 15, col: 0 })?.name).toBe("Helper");
});
});
+11
Переглянути файл
@@ -36,6 +36,17 @@ export function methodStop(outline: readonly OutlineItem[], caret: Pos, dir: 1 |
return null;
}
/** The outermost type around `caret`, looking through namespaces and packages (C#, Kotlin scripts). */
export function topLevelTypeAt(outline: readonly OutlineItem[], caret: Pos): OutlineItem | null {
let level: readonly OutlineItem[] = outline;
for (;;) {
const hit = level.find((i) => inside(i, caret));
if (!hit) return null;
if (hit.kind !== "namespace" && hit.kind !== "package") return TYPES.has(hit.kind) ? hit : null;
level = hit.children;
}
}
export interface CaretMember {
/** Innermost method at the caret. */
method: OutlineItem | null;
+1 -1
Переглянути файл
@@ -444,7 +444,7 @@ function CostBadge({ category }: { category: string | null | undefined }) {
}
/** Accessible segmented pill selector (`role="radiogroup"`) with Left/Right arrow navigation. */
function SegmentedControl({
export function SegmentedControl({
ariaLabel,
options,
value,
+11
Переглянути файл
@@ -369,6 +369,17 @@ describe("streamed replies", () => {
expect(container.querySelector("details p")?.textContent).toBe("text");
});
it("renders LaTeX math across streamed blocks", () => {
const text = "Inline $a + b$.\n\n$$\n\\frac{1}{2}\n$$\n\nTail";
const blocks = markdownBlocks(text);
expect(blocks).toHaveLength(3);
expect(blocks.join("")).toBe(text);
const { container } = render(<Markdown text={text} cwd="/repo" />);
expect(container.querySelectorAll(".katex")).toHaveLength(2);
expect(container.querySelector(".katex-display")).not.toBeNull();
expect(screen.queryByRole("button", { name: "Copy Code" })).toBeNull();
});
it("cuts only what streamed on after the blocks that ended", () => {
const before = markdownBlocks("One.\n\nTwo.\n\nThr");
const after = markdownBlocks("One.\n\nTwo.\n\nThree.\n\n- a", before);
+5 -3
Переглянути файл
@@ -11,6 +11,7 @@ import { useEffect, useLayoutEffect, useRef, useSyncExternalStore } from "react"
import { Marked } from "marked";
import DOMPurify from "dompurify";
import { highlightInto } from "@/editor/lsp/markdown";
import { mathExtension, renderMath } from "@/editor/lsp/markdownMath";
import { iconNode } from "@/ui/iconNode";
import { tx } from "@/platform/i18n";
import { openExternalUrl } from "@/platform/openUrl";
@@ -37,7 +38,7 @@ const marked = new Marked({
return `<div data-mermaid=""><pre><code class="language-mermaid">${escapeHtml(text)}</code></pre></div>\n`;
},
},
});
}).use(mathExtension());
/** Rendered messages by text, least recently used first: reopening a conversation renders it again. */
const rendered = new Map<string, string>();
@@ -133,10 +134,11 @@ function renderHtml(text: string): string {
FORBID_TAGS: ["style", "form", "source"],
FORBID_ATTR: ["style", "srcset"],
ALLOW_DATA_ATTR: false,
// Only the mermaid placeholder written by the renderer above; data attributes
// Only the mermaid and math placeholders written by the renderer above; data attributes
// quoted in a reply stay out.
ADD_ATTR: ["data-mermaid"],
ADD_ATTR: ["data-mermaid", "data-math"],
}) as HTMLElement;
renderMath(root);
root.querySelectorAll("li").forEach(wrapLooseText);
// WebKit cuts controls inside <pre> out of a text selection, even when transparent.
root.querySelectorAll("pre").forEach((pre) => {
+4
Переглянути файл
@@ -1280,6 +1280,10 @@
flex: none;
white-space: nowrap;
}
.changesScope {
flex: none;
padding: 6px 10px 2px;
}
.changesSummary {
flex: none;
overflow: hidden;
+6 -3
Переглянути файл
@@ -46,6 +46,8 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
const review = useAgents((s) => s.groupedChanges.get(id));
const changes = grouped ? (review?.uncommitted ?? null) : (sinceStart ?? null);
const commits = grouped ? (review?.commits ?? []) : [];
const scope = useChangesOptions((s) => s.scope);
const lastTurn = useAgents((s) => s.turnChanges.get(id));
const project = useProject((s) => s.project);
const head = useLocalHead(
task?.isolation === "local" ? task.status : null,
@@ -189,9 +191,10 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
{changesOpen && (
<ChangesPane
task={task}
changes={changes ?? null}
commits={commits}
grouped={grouped}
changes={scope === "turn" ? (lastTurn ?? null) : (changes ?? null)}
commits={scope === "turn" ? [] : commits}
grouped={grouped && scope === "task"}
scope={scope}
head={head}
docked={docked}
onHide={() => setChangesOpen(false)}
+6 -1
Переглянути файл
@@ -1,15 +1,19 @@
/** Changes pane view options, persisted across sessions. */
import { create } from "zustand";
/** What the pane lists: the whole task's changes, or the last turn's. */
export type ChangesScope = "task" | "turn";
export interface ChangesOptions {
/** Files grouped by the commit that changed them; otherwise the flat list since the task started. */
groupByCommit: boolean;
scope: ChangesScope;
/** Width of the pane beside the conversation, in px; `null`: the stylesheet's default. */
width: number | null;
}
/** IDEA-like default: the review view. */
export const DEFAULT_CHANGES_OPTIONS: ChangesOptions = { groupByCommit: true, width: null };
export const DEFAULT_CHANGES_OPTIONS: ChangesOptions = { groupByCommit: true, scope: "task", width: null };
const MIN_CHANGES_WIDTH = 200;
const MAX_CHANGES_WIDTH = 1600;
@@ -26,6 +30,7 @@ function load(): ChangesOptions {
const o = raw ? (JSON.parse(raw) as Record<string, unknown>) : {};
return {
groupByCommit: typeof o.groupByCommit === "boolean" ? o.groupByCommit : DEFAULT_CHANGES_OPTIONS.groupByCommit,
scope: o.scope === "turn" ? "turn" : DEFAULT_CHANGES_OPTIONS.scope,
width: typeof o.width === "number" && Number.isFinite(o.width) ? clampChangesWidth(o.width) : null,
};
} catch {
+3 -52
Переглянути файл
@@ -17,24 +17,13 @@ import {
registerMenuGroup,
registerMenuSlotItem,
registerOverlay,
registerSettingsPages,
registerStatusItem,
registerToolWindow,
toolWindowService,
} from "@/workbench/contributions";
import { AgentsStatus } from "./AgentsStatus";
import {
AGENTS_GROUP,
HOME_KIND,
MCP_PAGE,
POLICY_PAGE,
REGISTRY_PAGE,
SESSION_KIND,
TASK_DRAG,
TOOL_WINDOW,
WORKING_STATUS_PAGE,
providerIcon,
} from "./model";
import { activateSettingsPages } from "./settingsPages";
import { HOME_KIND, MCP_PAGE, REGISTRY_PAGE, SESSION_KIND, TASK_DRAG, TOOL_WINDOW, providerIcon } from "./model";
import { sendPaths, sendSelection, trackEditorCopies } from "./references";
import { focusedSession, inputSession } from "./sessionFocus";
import { cycleFocusedEffort } from "./effortFocus";
@@ -54,45 +43,7 @@ import { TaskStatusMark } from "./TaskStatusMark";
import { taskActions, useAgentsHeaderMenu } from "./taskActions";
import { replyActions } from "./replyActions";
/** Settings › Agents › Coding Agents and Settings › Agents › External MCP Servers (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPages([
{
id: REGISTRY_PAGE,
title: "Coding Agents",
group: AGENTS_GROUP,
// First in Agents, which sits after Languages & Frameworks and before Tools.
order: 450,
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
},
{
id: WORKING_STATUS_PAGE,
title: "Working Status",
group: AGENTS_GROUP,
// After Chat.
order: 465,
keywords: ["agent", "status", "playful", "words", "working", "spinner", "fun", "delay", "seconds"],
component: lazyComponent(() => import("./WorkingStatusPage").then((m) => m.WorkingStatusPage)),
},
{
id: MCP_PAGE,
title: "External MCP Servers",
group: AGENTS_GROUP,
order: 475,
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
},
{
id: POLICY_PAGE,
title: "Command Permissions",
group: AGENTS_GROUP,
order: 490,
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "permission", "command", "exec"],
component: lazyComponent(() => import("./AgentPolicyPage").then((m) => m.AgentPolicyPage)),
},
]);
}
export { activateSettingsPages } from "./settingsPages";
export function activate(): () => void {
const sync = (root: string | null | undefined) => {
+60 -28
Переглянути файл
@@ -10,7 +10,8 @@ import { confirm } from "@/workbench/messages";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ChangesResizer } from "../ChangesResizer";
import styles from "../Session.module.css";
import { setChangesOptions } from "../changesOptions";
import { setChangesOptions, type ChangesScope } from "../changesOptions";
import { SegmentedControl } from "../ConfigPickers";
import { formatSentAt } from "../conversation";
import { branchLabel } from "../model";
import { acceptChanges, refreshChanges, rollbackChanges, useAgents } from "../store";
@@ -172,6 +173,7 @@ export function ChangesPane({
changes,
commits,
grouped,
scope,
head,
docked,
onHide,
@@ -180,20 +182,22 @@ export function ChangesPane({
changes: AgentChange[] | null;
commits: readonly AgentCommit[];
grouped: boolean;
scope: ChangesScope;
head: string | null;
docked: boolean;
onHide: () => void;
}) {
// The two views key their rows differently: a selection doesn't carry over.
// The views key their rows differently, and list different changes: a selection doesn't carry over.
const view = scope === "turn" ? "turn" : grouped ? "grouped" : "flat";
const [selection, setSelection] = useState<{
grouped: boolean;
view: string;
keys: ReadonlySet<string>;
}>(() => ({
grouped,
view,
keys: NO_SELECTION,
}));
const selected = selection.grouped === grouped ? selection.keys : NO_SELECTION;
const setSelected = (keys: ReadonlySet<string>) => setSelection({ grouped, keys });
const selected = selection.view === view ? selection.keys : NO_SELECTION;
const setSelected = (keys: ReadonlySet<string>) => setSelection({ view, keys });
const rows = useMemo(() => changeRows(changes ?? [], commits, grouped), [changes, commits, grouped]);
// Only the working files roll back; a commit's files are history.
const rollbackable = useMemo(() => {
@@ -226,13 +230,17 @@ export function ChangesPane({
: tx`Roll back the changes to ${count} files?`}
</p>
<p>
{grouped
? tx("They go back to the last commit; changes made after it are lost.")
: task.isolation === "worktree"
? tx("They go back to how they were when the task started, in the task's worktree.")
: tx(
"They go back to how they were when the task started. Edits of yours made to them since then are lost too; edits from before the task are kept.",
)}
{scope === "turn"
? tx(
"They go back to how they were when the last turn started. Edits of yours made to them since then are lost too.",
)
: grouped
? tx("They go back to the last commit; changes made after it are lost.")
: task.isolation === "worktree"
? tx("They go back to how they were when the task started, in the task's worktree.")
: tx(
"They go back to how they were when the task started. Edits of yours made to them since then are lost too; edits from before the task are kept.",
)}
</p>
</>
),
@@ -244,7 +252,7 @@ export function ChangesPane({
await rollbackChanges(
task.id,
picked.length ? picked.map((c) => c.relPath) : null,
grouped ? "group" : "sinceStart",
scope === "turn" ? "lastTurn" : grouped ? "group" : "sinceStart",
);
setSelected(new Set());
} catch (e) {
@@ -256,10 +264,11 @@ export function ChangesPane({
}
};
const accept = async () => {
// Accepting brings over the task's whole work, committed or not: grouping only changes the listing.
// Accepting brings over the task's whole work, committed or not: grouping and the last turn
// only change the listing.
const all =
grouped && !picked.length
? await call(commands.agentChanges(task.id)).catch(() => changes ?? [])
(grouped || scope === "turn") && !picked.length
? await call(commands.agentChanges(task.id, null)).catch(() => changes ?? [])
: (changes ?? []);
const targets = picked.length ? picked : all;
const count = targets.length;
@@ -334,7 +343,7 @@ export function ChangesPane({
onClick={() => void rollback()}
/>
<IconButton icon="refresh" title="Refresh" onClick={() => void refreshChanges(task.id)} />
{task.isolation === "worktree" && (
{task.isolation === "worktree" && scope === "task" && (
<IconButton
icon="eye"
title="View Options"
@@ -357,9 +366,29 @@ export function ChangesPane({
)}
{!docked && <IconButton icon="chevron-right" title={tx("Hide changes")} size="small" onClick={onHide} />}
</div>
{(grouped || head || task.base) && (
<div className={styles.changesScope}>
<SegmentedControl
ariaLabel={tx("Changes to show")}
options={[
{ value: "task", label: tx("Whole Task") },
{ value: "turn", label: tx("Last Turn") },
]}
value={scope}
onChange={(value) => {
setChangesOptions({ scope: value === "turn" ? "turn" : "task" });
void refreshChanges(task.id);
}}
/>
</div>
{(scope === "turn" || grouped || head || task.base) && (
<div className={styles.changesSummary}>
<T>vs</T> {grouped ? "HEAD" : (head ?? task.base)}
{scope === "turn" ? (
<T>Since the last turn started</T>
) : (
<>
<T>vs</T> {grouped ? "HEAD" : (head ?? task.base)}
</>
)}
{changes && changes.length > 0 && (
<>
{" "}
@@ -373,7 +402,7 @@ export function ChangesPane({
<Spinner />
) : (
<Tree<ChangeRow>
key={grouped ? "grouped" : "flat"}
key={view}
aria-label="Changed files"
roots={rows}
getKey={(n) => n.key}
@@ -392,7 +421,7 @@ export function ChangesPane({
if (n.type === "file") {
if (n.commit) void openCommitDiff(task, n.commit, n.change.path);
else if (grouped) void openUncommittedDiff(task, n.change.path);
else void openChangeDiff(task, n.change.path);
else void openChangeDiff(task, n.change.path, scope);
} else if (n.type === "commit") {
void openCommitDiff(task, n.commit, n.commit.files[0]?.path ?? "");
}
@@ -449,7 +478,7 @@ export function ChangesPane({
}}
empty={
<div className={styles.changesEmpty}>
<T>No changes yet</T>
{scope === "turn" ? <T>The last turn changed no files</T> : <T>No changes yet</T>}
</div>
}
/>
@@ -459,15 +488,18 @@ export function ChangesPane({
);
}
/** Opens the diff of `path` between the task's start and now. */
export async function openChangeDiff(task: AgentTask, path: string) {
const changed = (useAgents.getState().changes.get(task.id) ?? []).map((change) => change.path);
/** Opens the diff of `path` between the task's start (or its last turn's) and now. */
export async function openChangeDiff(task: AgentTask, path: string, scope: ChangesScope = "task") {
const { changes, turnChanges } = useAgents.getState();
const changed = ((scope === "turn" ? turnChanges : changes).get(task.id) ?? []).map((change) => change.path);
const paths = changed.includes(path) ? changed : [path];
const baseLabel = task.base ?? "Base";
const baseLabel = scope === "turn" ? tx("Before Last Turn") : (task.base ?? "Base");
const right = task.isolation === "worktree" ? branchLabel(task.branch) : "Working tree";
const diffs = await Promise.all(
paths.map(async (file): Promise<DiffData> => {
const base = await call(commands.agentBaseText(task.id, file)).catch(() => null);
const base = await call(commands.agentBaseText(task.id, file, scope === "turn" ? "lastTurn" : null)).catch(
() => null,
);
return {
path: file,
left: { type: "text", text: base ?? "", label: baseLabel },
+42 -2
Переглянути файл
@@ -33,6 +33,7 @@ const backend = vi.hoisted(() => ({
entries: new Map<string, AgentEntry[]>(),
changes: [] as AgentChange[],
changesCalls: 0,
turnChanges: [] as AgentChange[],
grouped: { uncommitted: [] as AgentChange[], commits: [] as AgentCommit[] },
groupedCalls: 0,
rolledBack: [] as Array<[string, string[] | null, string | null]>,
@@ -84,7 +85,8 @@ vi.mock("@/platform/ipc", async (original) => ({
};
return { status: "ok", data: backend.entries.get(key) ?? [] };
},
agentChanges: async () => {
agentChanges: async (_task: string, view: string | null) => {
if (view === "lastTurn") return { status: "ok", data: backend.turnChanges };
backend.changesCalls += 1;
return { status: "ok", data: backend.changes };
},
@@ -230,12 +232,13 @@ beforeEach(() => {
localStorage.clear();
backend.changes = [];
backend.changesCalls = 0;
backend.turnChanges = [];
backend.grouped = { uncommitted: [], commits: [] };
backend.groupedCalls = 0;
backend.rolledBack = [];
backend.external = [];
// The flat list unless a test asks for the grouped view, so counts and selections stay as before.
useChangesOptions.setState({ groupByCommit: false });
useChangesOptions.setState({ groupByCommit: false, scope: "task" });
backend.imported = [];
backend.importError = null;
backend.importErrors = new Map();
@@ -2970,6 +2973,43 @@ describe("accept changes", () => {
});
});
describe("last turn changes", () => {
const change = (path: string): AgentChange => ({
path: `/project/${path}`,
relPath: path,
kind: "modified",
added: 1,
removed: 0,
oldPath: null,
});
it("lists and rolls back only what the last turn changed, the session still counting the whole task", async () => {
backend.changes = [change("a.ts"), change("b.ts")];
backend.turnChanges = [change("b.ts")];
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
useAgents.setState({ tasks: new Map([["A", { ...task("A"), status: "ready" }]]) });
render(<SessionEditor input={input("A")} />);
const pane = await screen.findByRole("complementary", { name: "Changes" });
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
fireEvent.click(within(pane).getByRole("radio", { name: "Last Turn" }));
await waitFor(() => expect(within(pane).queryByText("a.ts")).toBeNull());
expect(within(pane).getByText("b.ts")).toBeInTheDocument();
expect(within(pane).getByText("Since the last turn started")).toBeInTheDocument();
expect(useChangesOptions.getState().scope).toBe("turn");
expect(screen.getByRole("button", { name: /2 changed files/ })).toBeInTheDocument();
fireEvent.click(within(pane).getByRole("button", { name: "Rollback All Changes…" }));
await waitFor(() => expect(backend.rolledBack).toEqual([["A", null, "lastTurn"]]));
backend.turnChanges = [];
fireEvent.click(within(pane).getByRole("button", { name: "Refresh" }));
expect(await within(pane).findByText("The last turn changed no files")).toBeInTheDocument();
fireEvent.click(within(pane).getByRole("radio", { name: "Whole Task" }));
expect(await within(pane).findByText("a.ts")).toBeInTheDocument();
});
});
describe("grouped changes", () => {
const commit = (overrides: Partial<AgentCommit> = {}): AgentCommit => ({
id: "a".repeat(40),
+43
Переглянути файл
@@ -0,0 +1,43 @@
import { lazyComponent } from "@/ui";
import { registerSettingsPages } from "@/workbench/contributions";
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE, WORKING_STATUS_PAGE } from "./model";
/** Settings › Agents › Coding Agents and Settings › Agents › External MCP Servers (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPages([
{
id: REGISTRY_PAGE,
title: "Coding Agents",
group: AGENTS_GROUP,
// First in Agents, which sits after Languages & Frameworks and before Tools.
order: 450,
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
},
{
id: WORKING_STATUS_PAGE,
title: "Working Status",
group: AGENTS_GROUP,
// After Chat.
order: 465,
keywords: ["agent", "status", "playful", "words", "working", "spinner", "fun", "delay", "seconds"],
component: lazyComponent(() => import("./WorkingStatusPage").then((m) => m.WorkingStatusPage)),
},
{
id: MCP_PAGE,
title: "External MCP Servers",
group: AGENTS_GROUP,
order: 475,
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
},
{
id: POLICY_PAGE,
title: "Command Permissions",
group: AGENTS_GROUP,
order: 490,
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "permission", "command", "exec"],
component: lazyComponent(() => import("./AgentPolicyPage").then((m) => m.AgentPolicyPage)),
},
]);
}
+29 -4
Переглянути файл
@@ -98,6 +98,8 @@ interface AgentsState {
changes: Map<string, AgentChange[]>;
/** The task's uncommitted changes and commits, when the Changes pane groups by commit. */
groupedChanges: Map<string, AgentChanges>;
/** What the task's last turn changed, when the Changes pane shows that. */
turnChanges: Map<string, AgentChange[]>;
/** Scroll position and follow-output preference by conversation, shared by both hosts. */
scrollPositions: Map<string, { top: number; stick: boolean }>;
providers: AgentProvider[];
@@ -186,6 +188,7 @@ export const useAgents = create<AgentsState>(() => ({
entryLoads: new Map(),
changes: new Map(),
groupedChanges: new Map(),
turnChanges: new Map(),
providers: [],
limits: new Map(),
modelCatalogs: new Map(),
@@ -496,6 +499,7 @@ export async function connect(): Promise<void> {
entryLoads: new Map(),
changes: new Map(),
groupedChanges: new Map(),
turnChanges: new Map(),
providers,
organizeRoot,
organize: pruneOrganize(loadOrganize(organizeRoot), tasks),
@@ -599,12 +603,18 @@ function withoutTaskCache(s: AgentsState, taskId: string): Partial<AgentsState>
groupedChanges = new Map(s.groupedChanges);
groupedChanges.delete(taskId);
}
if (!entries && !entryLoads && !changes && !groupedChanges) return null;
let turnChanges: Map<string, AgentChange[]> | undefined;
if (s.turnChanges.has(taskId)) {
turnChanges = new Map(s.turnChanges);
turnChanges.delete(taskId);
}
if (!entries && !entryLoads && !changes && !groupedChanges && !turnChanges) return null;
return {
...(entries ? { entries } : {}),
...(entryLoads ? { entryLoads } : {}),
...(changes ? { changes } : {}),
...(groupedChanges ? { groupedChanges } : {}),
...(turnChanges ? { turnChanges } : {}),
};
}
@@ -625,7 +635,7 @@ function isTaskOpenInUi(taskId: string): boolean {
/** Whether a background trigger should reload a task's changes: only while they are shown or still cached. */
function wantsChanges(taskId: string): boolean {
const s = useAgents.getState();
return s.changes.has(taskId) || s.groupedChanges.has(taskId) || isTaskOpenInUi(taskId);
return s.changes.has(taskId) || s.groupedChanges.has(taskId) || s.turnChanges.has(taskId) || isTaskOpenInUi(taskId);
}
/**
@@ -667,6 +677,7 @@ export function disconnect() {
entryLoads: new Map(),
changes: new Map(),
groupedChanges: new Map(),
turnChanges: new Map(),
modelCatalogs: new Map(),
modelRequests: new Set(),
modelRequestTargets: new Map(),
@@ -846,11 +857,25 @@ export async function loadEntries(task: string, subagent: string | null = null):
}
export async function refreshChanges(task: string): Promise<void> {
// Discard a result that arrives after a project switch, the task's deletion, or its cache being dropped.
const gen = generation;
const drops = cacheDrops.get(task);
// Discard a result that arrives after a project switch, the task's deletion, or its cache being dropped.
const stillWanted = () =>
gen === generation && useAgents.getState().tasks.has(task) && cacheDrops.get(task) === drops;
// The whole task's changes are read in either scope: the session's summary counts them.
await Promise.all([
refreshTaskChanges(task, stillWanted),
useChangesOptions.getState().scope === "turn" && refreshTurnChanges(task, stillWanted),
]);
}
async function refreshTurnChanges(task: string, stillWanted: () => boolean): Promise<void> {
const changes = await call(commands.agentChanges(task, "lastTurn")).catch(() => []);
if (!stillWanted()) return;
useAgents.setState((s) => ({ turnChanges: new Map(s.turnChanges).set(task, changes) }));
}
async function refreshTaskChanges(task: string, stillWanted: () => boolean): Promise<void> {
// Local tasks have no commits of their own to group: the flat list is their only view.
const grouped =
useChangesOptions.getState().groupByCommit && useAgents.getState().tasks.get(task)?.isolation === "worktree";
@@ -871,7 +896,7 @@ export async function refreshChanges(task: string): Promise<void> {
return;
}
try {
const changes = await call(commands.agentChanges(task));
const changes = await call(commands.agentChanges(task, null));
if (!stillWanted()) return;
useAgents.setState((s) => ({
changes: new Map(s.changes).set(task, changes),
+19 -1
Переглянути файл
@@ -56,7 +56,10 @@ vi.mock("@/platform/ipc", async (original) => ({
agentProviders: async () => ({ status: "ok", data: [] }),
agentChanges: async () => ({ status: "ok", data: [] }),
agentGroupedChanges: async () => ({ status: "ok", data: { uncommitted: [], commits: [] } }),
agentBaseText: async (_task: string, path: string) => ({ status: "ok", data: `base of ${path}` }),
agentBaseText: async (_task: string, path: string, view: string | null) => ({
status: "ok",
data: view === "lastTurn" ? `before the last turn: ${path}` : `base of ${path}`,
}),
agentEntries: async () => ({ status: "ok", data: await backend.entries }),
},
}));
@@ -522,6 +525,21 @@ describe("the diff of an agent change", () => {
expect(input.data.chain[0].left.text).toBe("base of /project/a.ts");
});
it("in the last turn, lists that turn's files against how they were as it started", async () => {
useAgents.setState({
changes: new Map([["one", [change("/project/a.ts"), change("/project/b.ts")]]]),
turnChanges: new Map([["one", [change("/project/b.ts")]]]),
});
await openChangeDiff(task("one"), "/project/b.ts", "turn");
const input = backend.openInput.mock.lastCall![0];
expect(input.data.left).toEqual({
type: "text",
text: "before the last turn: /project/b.ts",
label: "Before Last Turn",
});
expect(input.data.chain).toBeUndefined();
});
it("opens a file outside the change list on its own", async () => {
useAgents.setState({ changes: new Map([["one", [change("/project/a.ts")]]]) });
await openChangeDiff(task("one"), "/project/c.ts");
+32 -3
Переглянути файл
@@ -1,9 +1,23 @@
import { afterEach, expect, it, vi } from "vitest";
import type { Diagnostic, InspectEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { installInspectionProfileSync, resetInspection, runInspection, useInspection } from "./inspect";
import {
installInspectionProfileSync,
rerunInspection,
resetInspection,
runInspection,
useInspection,
} from "./inspect";
const mock = vi.hoisted(() => ({ channel: null as null | { onmessage: (event: InspectEvent) => void } }));
const mock = vi.hoisted(() => ({
channel: null as null | { onmessage: (event: InspectEvent) => void },
scopes: [] as unknown[],
active: "/p/a.ts",
}));
vi.mock("@/editor/api", async (original) => ({
...(await original<object>()),
activeEditor: () => ({ ctx: { path: mock.active, virtual: false } }),
}));
vi.mock("@tauri-apps/api/core", () => ({
Channel: class {
onmessage = () => {};
@@ -14,7 +28,8 @@ vi.mock("@/platform/ipc", async (original) => ({
isTauri: () => true,
call: (value: unknown) => value,
commands: {
inspectCode: (_id: unknown, _scope: unknown, channel: typeof mock.channel) => {
inspectCode: (_id: unknown, scope: unknown, channel: typeof mock.channel) => {
mock.scopes.push(scope);
mock.channel = channel;
return Promise.resolve();
},
@@ -97,3 +112,17 @@ it("retains initially disabled diagnostics and uses edits made during streaming"
dispose();
}
});
it("reruns the file the results are for, not the file now active", async () => {
mock.scopes = [];
mock.active = "/p/a.ts";
await runInspection({ kind: "file", directory: "" }, "default");
mock.active = "/p/b.ts";
rerunInspection();
await vi.waitFor(() => expect(mock.scopes).toHaveLength(2));
expect(mock.scopes).toEqual([
{ kind: "files", paths: ["/p/a.ts"] },
{ kind: "files", paths: ["/p/a.ts"] },
]);
expect(useInspection.getState().scopeLabel).toBe("File /p/a.ts");
});
+2 -1
Переглянути файл
@@ -200,7 +200,8 @@ export async function runInspection(choice: ScopeChoice, profileId: ProfileId =
summary: null,
error: null,
scopeLabel: describeScope(choice, scope),
last: choice,
// Rerun repeats this run's scope: "Current file" stays the file inspected now.
last: choice.kind === "file" && scope.kind === "files" ? { ...choice, file: scope.paths[0] } : choice,
profile: profileId,
excluded: new Set(),
});
+3 -1
Переглянути файл
@@ -15,6 +15,8 @@ export interface ScopeChoice {
directory: string;
/** Name of the custom scope for `custom` (`@/platform/search`). */
custom?: string;
/** The file `file` resolved to, so a rerun inspects it again rather than the file now active. */
file?: string;
}
export const SCOPE_LABELS: Record<ScopeKind, string> = {
@@ -58,7 +60,7 @@ export async function resolveScope(choice: ScopeChoice): Promise<SearchScope | s
case "directory":
return choice.directory.trim() ? { kind: "directory", path: choice.directory.trim() } : "Choose a directory";
case "file": {
const file = currentFile();
const file = choice.file ?? currentFile();
return file ? { kind: "files", paths: [file] } : "No file is open";
}
case "changed": {
+19 -2
Переглянути файл
@@ -192,6 +192,20 @@ describe("replacing a project in this window", () => {
expect(useProject.getState().project?.root).toBe("/local");
});
it("asks about trust before leaving, so Don't Open keeps the current project running", async () => {
useProject.setState({
...projectState("/a"),
settings: { general: { openProjectIn: "same" } },
} as never);
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
vi.mocked(confirmProjectTrust).mockRejectedValueOnce(new IpcError({ kind: "cancelled", message: "Cancelled" }));
await openProjectWithPolicy("/b");
expect(confirmProjectTrust).toHaveBeenCalledWith("/b", "local");
expect(confirmLeaveProject).not.toHaveBeenCalled();
expect(openProject).not.toHaveBeenCalled();
expect(notify).not.toHaveBeenCalled();
});
it("opens the local project when its path matches the remote root", async () => {
useProject.setState({
...projectState("/same"),
@@ -792,11 +806,14 @@ describe("trust is asked before a new project window opens", () => {
expect(windowOpenProject).toHaveBeenCalled();
});
it("asks only once, from openProject, when the project opens in this window", async () => {
it("asks once this window takes the project, before leaving its current one", async () => {
windowOpenProject.mockResolvedValue(ok({ kind: "current" }));
await openProjectInWindow("/p/b", false);
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", false, []);
expect(confirmProjectTrust).not.toHaveBeenCalled();
expect(confirmProjectTrust).toHaveBeenCalledOnce();
expect(vi.mocked(confirmProjectTrust).mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(confirmLeaveProject).mock.invocationCallOrder[0]!,
);
expect(openProject).toHaveBeenCalledWith("/p/b");
});
});
-6
Переглянути файл
@@ -22,12 +22,6 @@ import { installLaunchHandling, installLightEditAutoClose, windowActions } from
import { WorkspaceDialogHost } from "./WorkspaceDialog";
import { installWindowGroups } from "@/platform/windowGroups";
/** The UI locale of a secondary (Settings, comparison) window. */
export const activateLocale = installLocaleSync;
/** Native menu items of a secondary window that runs actions itself (comparison). */
export const activateMenuBridge = installMenuBridge;
export { confirmLeave } from "./closeGuard";
export function activate(): () => void {
const disposers = [
installLocaleSync(),
+10 -1
Переглянути файл
@@ -25,6 +25,7 @@ import { isDistractionFree, useDistractionFree } from "@/workbench/distractionFr
import { orderStatusItems } from "@/workbench/StatusBar";
import { statusWidgetRows } from "@/workbench/statusBarWidgets";
import { useToolWindowLayouts } from "@/workbench/toolwindows/layouts";
import { toolWindowsRestorable, useToolWindowLayout } from "@/workbench/toolwindows/store";
import { hostOs, type HostOs } from "./host";
export const MENU_EVENT = "openidea://menu";
@@ -100,7 +101,11 @@ export function menuAccelerator(binding: string): string | undefined {
export function buildMenuConfig(os: HostOs): MenuConfig {
const labels: Record<string, string> = {};
// Per-window state some labels follow (View › Appearance › Enter / Exit Distraction Free Mode).
const params = { os, distractionFree: isDistractionFree() ? "on" : "off" };
const params = {
os,
distractionFree: isDistractionFree() ? "on" : "off",
toolWindows: toolWindowsRestorable() ? "hidden" : "shown",
};
for (const key of keysWithPrefix("menu.")) labels[key] = t(key, params);
const accelerators: Record<string, string> = {};
const seen = new Set<string>();
@@ -265,6 +270,10 @@ export function installMenuBridge(): () => void {
useDistractionFree.subscribe((s, prev) => {
if (s.active !== prev.active) push();
}),
// Window › Hide All Tool Windows reads "Restore Tool Windows" while it would restore them.
useToolWindowLayout.subscribe((s, prev) => {
if (toolWindowsRestorable(s) !== toolWindowsRestorable(prev)) push();
}),
useContributions.subscribe((s, prev) => {
if (s.toolWindows !== prev.toolWindows || s.statusItems !== prev.statusItems) push();
}),
+7
Переглянути файл
@@ -57,6 +57,13 @@ async function openHere(path: string): Promise<boolean> {
if (!isRemoteWindow() && useProject.getState().project?.root === path) return true;
// A folder of a WSL distro runs there, not as a network folder; the window then drops untitled buffers.
const wsl = await commands.wslResolve(path).catch(() => null);
try {
// Asked before leaving, so Don't Open keeps the current project and its processes running.
if (!wsl) await confirmProjectTrust(path, "local");
} catch (e) {
openFailed(path, e);
return false;
}
if (!(await confirmLeaveProject(!wsl))) return false;
try {
if (wsl) await connectRemote(wsl.target, wsl.path);
+85
Переглянути файл
@@ -410,6 +410,91 @@ describe("build feature", () => {
expect(notes).toHaveLength(0);
});
it.each(["cancelled", "failed", "succeeded"])("ignores a previous project's build that %s", async (outcome) => {
const previous = startBuild("build", null, false);
await act(async () => {});
const oldRequest = useBuildRun.getState().request;
useProject.setState({ project: { root: "/other", name: "other" } as never });
expect(fake.cancelled).toEqual([oldRequest]);
const nextBackend = new FakeBackend();
setBuildBackend(nextBackend);
const next = startCompileFile("/other/Main.java", false);
await act(async () => {});
const current = useBuildRun.getState();
expect(current.request).not.toBe(oldRequest);
fake.emit!({ kind: "output", text: "old output\n", stderr: false });
if (outcome === "cancelled") fake.reject(new IpcError({ kind: "cancelled", message: "Cancelled" }));
else if (outcome === "failed") fake.reject(new Error("Old build failed"));
else fake.resolve(result([], true));
const previousResult = await previous;
expect(useBuildRun.getState()).toBe(current);
expect(previousResult).toBeNull();
expect(getContext()["build.lastStatus"]).toBeNull();
expect(getContext()["build.running"]).toBe(true);
expect(isActionEnabled(getAction("build.stop")!)).toBe(true);
expect(useTasks.getState().tasks.find((task) => task.id === BUILD_TASK_ID)).toMatchObject({
title: "Compile File",
done: false,
});
expect(notes).toEqual([]);
expect(show).not.toHaveBeenCalled();
expect(openFile).not.toHaveBeenCalled();
stopBuild();
expect(nextBackend.cancelled).toEqual([current.request]);
nextBackend.reject(new IpcError({ kind: "cancelled", message: "Cancelled" }));
await next;
expect(useBuildRun.getState().status).toBe("cancelled");
expect(isActionEnabled(getAction("build.stop")!)).toBe(false);
});
it("drops a previous project's build that was waiting for Save All", async () => {
let saved!: () => void;
const saving = new Promise<void>((resolve) => (saved = resolve));
provideEditorService({
openFile,
saveAll: vi.fn().mockReturnValueOnce(saving).mockResolvedValue(undefined),
activePath: () => null,
} as unknown as EditorService);
const previous = startBuild("build", null, false);
useProject.setState({ project: { root: "/other", name: "other" } as never });
const next = startCompileFile("/other/Main.java", false);
await act(async () => {});
saved();
await act(async () => {});
expect(fake.calls).toEqual([{ kind: "compileFile", file: "/other/Main.java", clear: [] }]);
expect(await previous).toBeNull();
fake.resolve(result([], true));
await next;
expect(useBuildRun.getState().status).toBe("success");
});
it("keeps the next build's progress when the finished task's linger expires", async () => {
vi.useFakeTimers();
try {
const previous = startBuild("build", null, false);
await act(async () => {});
fake.resolve(result([], true));
await previous;
useProject.setState({ project: { root: "/other", name: "other" } as never });
const next = startBuild("rebuild", null, false);
await act(async () => {});
await vi.advanceTimersByTimeAsync(600);
expect(useTasks.getState().tasks.find((task) => task.id === BUILD_TASK_ID)).toMatchObject({
title: "Rebuild",
done: false,
});
fake.resolve(result([], true));
await next;
} finally {
vi.useRealTimers();
}
});
it("compiles one file without its module and reruns it from the tool window", async () => {
const run = startCompileFile("/p/core/src/A.java");
await act(async () => {});
+17 -10
Переглянути файл
@@ -204,17 +204,20 @@ async function executeBuild(
invoke: (previous: string[], onEvent: (e: BuildEvent) => void) => Promise<BuildResult>,
cancel: () => void,
): Promise<BuildResult | null> {
const ownsBuild = () => useBuildRun.getState().request === request;
await maybeEditorService()
?.saveAll()
.catch(() => undefined);
if (!ownsBuild()) return null;
let queue: BuildEvent[] = [];
let timer: ReturnType<typeof setTimeout> | undefined;
const flush = () => {
clearTimeout(timer);
timer = undefined;
const events = queue;
queue = [];
if (useBuildRun.getState().request !== request || !events.length) return;
if (!ownsBuild() || !events.length) return;
let s = useBuildRun.getState();
for (const e of events) s = { ...s, ...applyBuildEvent(s, e) };
useBuildRun.setState(s);
@@ -222,6 +225,7 @@ async function executeBuild(
upsertTask({ id: BUILD_TASK_ID, title: taskTitle, message: s.message, fraction: null, done: false, cancel });
};
const onEvent = (e: BuildEvent) => {
if (!ownsBuild()) return;
queue.push(e);
timer ??= setTimeout(flush, 16);
};
@@ -229,7 +233,7 @@ async function executeBuild(
let result: BuildResult | null = null;
try {
result = await invoke(useBuildRun.getState().files, onEvent);
clearTimeout(timer);
if (!ownsBuild()) return null;
flush();
const status: BuildStatus = result.success ? "success" : "failed";
useBuildRun.setState({
@@ -255,7 +259,7 @@ async function executeBuild(
});
if (!result.success) showFailure();
} catch (e) {
clearTimeout(timer);
if (!ownsBuild()) return null;
flush();
if (isCancelled(e)) {
useBuildRun.setState({ status: "cancelled", files: [], message: null });
@@ -278,13 +282,16 @@ async function executeBuild(
showFailure();
}
} finally {
if (useBuildRun.getState().request === request) useBuildRun.setState({ request: null });
setContext(
BUILD_LAST_STATUS,
result?.success ? "success" : useBuildRun.getState().status === "cancelled" ? "cancelled" : "failed",
);
setContext(BUILD_RUNNING, false);
upsertTask({ id: BUILD_TASK_ID, title: taskTitle, message: null, fraction: 1, done: true });
clearTimeout(timer);
if (ownsBuild()) {
useBuildRun.setState({ request: null });
setContext(
BUILD_LAST_STATUS,
result?.success ? "success" : useBuildRun.getState().status === "cancelled" ? "cancelled" : "failed",
);
setContext(BUILD_RUNNING, false);
upsertTask({ id: BUILD_TASK_ID, title: taskTitle, message: null, fraction: 1, done: true });
}
}
return result;
}
+12
Переглянути файл
@@ -24,6 +24,18 @@ describe("Language server status popup", () => {
off();
});
it("opens a server's settings from its row", () => {
const run = vi.fn();
const off = registerAction({ id: "tools.languageServers", title: "Language Servers…", run: ({ arg }) => run(arg) });
useServers.setState({ servers: new Map([[1 as never, server("ready", null)]]) });
render(<ServerStatus />);
fireEvent.click(screen.getByRole("button", { name: /Language servers/ }));
fireEvent.click(screen.getByRole("button", { name: "Configure jdtls…" }));
expect(run).toHaveBeenCalledWith("jdtls");
expect(screen.queryByRole("button", { name: "Configure jdtls…" })).toBeNull();
off();
});
it("keeps Restart for other failures", () => {
useServers.setState({ servers: new Map([[1 as never, server("crashed", "exit code 1")]]) });
render(<ServerStatus />);
+13 -1
Переглянути файл
@@ -1,4 +1,4 @@
/** Status bar widget listing language servers, with a popup to restart them. */
/** Status bar widget listing language servers, with a popup to restart or configure them. */
import { useMemo, useRef, useState } from "react";
import clsx from "clsx";
import { getAction, executeAction } from "@/platform/actions";
@@ -18,6 +18,7 @@ export function ServerStatus() {
const summary = serversSummary(servers);
// features/tools owns installing; without it, fall back to the manual hint text.
const canInstall = !!getAction("tools.install");
const canConfigure = !!getAction("tools.languageServers");
if (!summary) return null;
return (
<>
@@ -92,6 +93,17 @@ export function ServerStatus() {
/>
</>
)}
{canConfigure && (
<IconButton
icon="settings"
size="small"
title={tx`Configure ${serverLabel(s)}…`}
onClick={() => {
setOpen(false);
void executeAction("tools.languageServers", s.name);
}}
/>
)}
</div>
{(s.languages.length > 0 || s.root) && (
<div className={styles.meta}>
+11 -3
Переглянути файл
@@ -11,7 +11,7 @@ import {
type RunExecutorContribution,
} from "@/workbench/contributions";
import { coverageSupports, formatPercent } from "./model";
import { addSuite } from "./store";
import { addSuite, captureCoverageProject } from "./store";
import { tx } from "@/platform/i18n";
const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
@@ -69,7 +69,13 @@ async function prepare(config: RunConfig): Promise<ExecutorLaunch | null> {
notifications().notify({ group: "run", level: "warning", title: "Coverage needs the desktop app" });
return null;
}
const plan = await call(commands.coveragePrepare(config));
const project = captureCoverageProject();
if (!project) return null;
const plan = await call(commands.coveragePrepare(config)).catch((e: unknown) => {
if (project.isCurrent()) throw e;
return null;
});
if (!plan || !project.isCurrent()) return null;
if (plan.status === "unsupported") {
notifications().notify({
group: "run",
@@ -88,10 +94,11 @@ async function prepare(config: RunConfig): Promise<ExecutorLaunch | null> {
return {
launch: plan.launch,
finished: ({ stopped }) => {
if (stopped) return;
if (stopped || !project.isCurrent()) return;
void (async () => {
try {
const data = await call(commands.coverageCollect(report));
if (!project.isCurrent()) return;
const suite = addSuite(config.name, data);
const totals = data.files.reduce((a, f) => [a[0]! + f.linesCovered, a[1]! + f.linesTotal], [0, 0]);
try {
@@ -106,6 +113,7 @@ async function prepare(config: RunConfig): Promise<ExecutorLaunch | null> {
title: `Coverage of '${suite.name}': ${formatPercent(totals[0]!, totals[1]!)} lines`,
});
} catch (e) {
if (!project.isCurrent()) return;
notifications().notify({
group: "run",
level: "error",
+6 -2
Переглянути файл
@@ -10,7 +10,7 @@ import { registerOverlay, registerRunExecutor, registerToolWindow, toolWindowSer
import { CoverageHeaderActions, CoverageTabs, CoverageView } from "./CoverageView";
import { coverageExecutor } from "./executor";
import { coverageGutter } from "./gutter";
import { ManageReportsOverlay, importReport, openManageReports } from "./reports";
import { ManageReportsOverlay, closeManageReports, importReport, openManageReports } from "./reports";
import { resetCoverage, setCoverageVisible, syncCoverageViews, useCoverage } from "./store";
export function activate(): () => void {
@@ -96,11 +96,15 @@ export function activate(): () => void {
},
]),
useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) resetCoverage();
if (s.project?.root !== prev.project?.root) {
resetCoverage();
closeManageReports();
}
}),
];
return () => {
disposers.reverse().forEach((d) => d());
closeManageReports();
if (useCoverage.getState().suites.length) resetCoverage();
};
}
+146
Переглянути файл
@@ -0,0 +1,146 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { CoveragePrepared, CoverageSuite, RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { coverageExecutor } from "./executor";
import { importReport } from "./reports";
import { importedReports, resetCoverage, useCoverage } from "./store";
const backend = vi.hoisted(() => ({
coverageImport: vi.fn(),
coveragePrepare: vi.fn(),
coverageCollect: vi.fn(),
open: vi.fn(),
show: vi.fn(),
notify: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/platform/ipc")>();
return {
...actual,
isTauri: () => true,
commands: {
...actual.commands,
coverageImport: backend.coverageImport,
coveragePrepare: backend.coveragePrepare,
coverageCollect: backend.coverageCollect,
},
};
});
vi.mock("@/platform/dialog", () => ({ open: backend.open }));
vi.mock("@/workbench/contributions", async (importOriginal) => ({
...(await importOriginal<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify: backend.notify }),
toolWindowService: () => ({ show: backend.show }),
}));
const origin = "/project-a";
const next = "/project-b";
const report = `${origin}/lcov.info`;
const data: CoverageSuite = {
runner: "lcov",
hasBranches: false,
files: [
{ path: `${origin}/src/a.ts`, lines: [], linesCovered: 1, linesTotal: 2, branchesCovered: 0, branchesTotal: 0 },
],
};
const config: RunConfig = {
id: "run-a",
kind: "shell",
name: "Run A",
command: "go",
args: ["test"],
cwd: null,
env: {},
detected: false,
isTest: true,
debugAdapter: null,
};
const plan: CoveragePrepared = {
status: "ready",
runner: "lcov",
launch: config,
report: { kind: "lcov", runner: "lcov", path: report, base: origin },
};
const ok = <T>(value: T) => ({ status: "ok" as const, data: value });
const switchTo = (root: string) => useProject.setState({ project: { root } as never });
function pending<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((done) => {
resolve = done;
});
return { promise, resolve };
}
beforeEach(() => {
vi.resetAllMocks();
localStorage.clear();
resetCoverage();
switchTo(origin);
});
afterEach(() => {
useProject.setState({ project: null, opening: false, openingPath: null });
resetCoverage();
});
it("remembers a late coverage import only in the requesting project", async () => {
const response = pending<ReturnType<typeof ok<CoverageSuite>>>();
backend.coverageImport.mockReturnValueOnce(response.promise).mockResolvedValueOnce(ok(data));
const importing = importReport(report);
expect(backend.coverageImport).toHaveBeenCalledWith(report);
switchTo(next);
response.resolve(ok(data));
await importing;
expect(useCoverage.getState().suites).toEqual([]);
expect(importedReports()).toEqual([]);
expect(importedReports(origin)).toEqual([{ path: report, name: "lcov.info", importedAt: expect.any(Number) }]);
expect(backend.show).not.toHaveBeenCalled();
expect(backend.notify).not.toHaveBeenCalled();
switchTo(origin);
const suite = await importReport(importedReports()[0]!.path);
expect(useCoverage.getState().suites).toEqual([suite]);
expect(suite?.data).toEqual(data);
expect(backend.show).toHaveBeenCalledWith("coverage");
});
it.each([
["while the next project opens", () => useProject.setState({ opening: true, openingPath: next })],
["after the next project opens", () => switchTo(next)],
])("abandons a report picked %s", async (_transition, changeProject) => {
const picker = pending<string>();
backend.open.mockReturnValue(picker.promise);
backend.coverageImport.mockResolvedValue(ok(data));
const importing = importReport();
await vi.waitFor(() => expect(backend.open).toHaveBeenCalledOnce());
changeProject();
picker.resolve(report);
await expect(importing).resolves.toBeNull();
expect(backend.coverageImport).not.toHaveBeenCalled();
});
it("does not launch coverage after leaving the project during preparation", async () => {
const response = pending<ReturnType<typeof ok<CoveragePrepared>>>();
backend.coveragePrepare.mockReturnValue(response.promise);
const preparing = coverageExecutor.prepare(config);
switchTo(next);
response.resolve(ok(plan));
await expect(preparing).resolves.toBeNull();
});
it("does not show a collected run after leaving its project", async () => {
const response = pending<ReturnType<typeof ok<CoverageSuite>>>();
backend.coveragePrepare.mockResolvedValue(ok(plan));
backend.coverageCollect.mockReturnValue(response.promise);
const run = await coverageExecutor.prepare(config);
expect(run).not.toBeNull();
run!.finished({ stopped: false, exitCode: 0 });
expect(backend.coverageCollect).toHaveBeenCalledWith(plan.report);
switchTo(next);
response.resolve(ok(data));
await new Promise((resolve) => setTimeout(resolve, 0));
expect(useCoverage.getState().suites).toEqual([]);
expect(backend.show).not.toHaveBeenCalled();
expect(backend.notify).not.toHaveBeenCalled();
});
+11 -4
Переглянути файл
@@ -12,6 +12,7 @@ import { notifications, toolWindowService } from "@/workbench/contributions";
import { formatPercent } from "./model";
import {
addSuite,
captureCoverageProject,
closeSuite,
forgetImport,
importedReports,
@@ -49,12 +50,16 @@ export async function importReport(path?: string): Promise<Suite | null> {
notifications().notify({ group: "run", level: "warning", title: "Importing coverage needs the desktop app" });
return null;
}
const project = captureCoverageProject();
if (!project) return null;
const file = path ?? (await pickReport());
if (!file) return null;
if (!file || !project.isCurrent()) return null;
try {
const data = await call(commands.coverageImport(file));
const suite = addSuite(basename(file), data, file);
rememberImport({ path: file, name: suite.name, importedAt: suite.createdAt });
const name = basename(file);
const suite = project.isCurrent() ? addSuite(name, data, file) : null;
rememberImport(project.root, { path: file, name, importedAt: suite?.createdAt ?? Date.now() });
if (!suite) return null;
try {
toolWindowService().show("coverage");
} catch {
@@ -70,6 +75,7 @@ export async function importReport(path?: string): Promise<Suite | null> {
});
return suite;
} catch (e) {
if (!project.isCurrent()) return null;
notifications().notify({
group: "run",
level: "error",
@@ -84,10 +90,11 @@ export async function importReport(path?: string): Promise<Suite | null> {
const useManageDialog = create<{ open: boolean }>(() => ({ open: false }));
export const openManageReports = () => useManageDialog.setState({ open: true });
export const closeManageReports = () => useManageDialog.setState({ open: false });
export function ManageReportsOverlay() {
const open = useManageDialog((s) => s.open);
return open ? <ManageReportsDialog onClose={() => useManageDialog.setState({ open: false })} /> : null;
return open ? <ManageReportsDialog onClose={closeManageReports} /> : null;
}
function ManageReportsDialog({ onClose }: { onClose: () => void }) {
+15 -3
Переглянути файл
@@ -33,6 +33,19 @@ interface CoverageState {
export const useCoverage = create<CoverageState>(() => ({ suites: [], activeId: null, visible: false }));
export function captureCoverageProject() {
const { project, opening } = useProject.getState();
if (!project || opening) return null;
const root = project.root;
return {
root,
isCurrent: () => {
const current = useProject.getState();
return !current.opening && current.project?.root === root;
},
};
}
let seq = 0;
export function activeSuite(s: CoverageState = useCoverage.getState()): Suite | null {
@@ -142,9 +155,8 @@ function saveImported(root: string, reports: ImportedReport[]) {
}
}
export function rememberImport(report: ImportedReport) {
const root = useProject.getState().project?.root;
if (root) saveImported(root, [report, ...importedReports(root).filter((r) => r.path !== report.path)]);
export function rememberImport(root: string, report: ImportedReport) {
saveImported(root, [report, ...importedReports(root).filter((r) => r.path !== report.path)]);
}
export function forgetImport(path: string) {
+3
Переглянути файл
@@ -370,6 +370,9 @@
font-size: var(--fs-small);
color: var(--fg-muted);
}
.formFull {
grid-column: 1 / -1;
}
.paramInput {
font-family: var(--openidea-editor-font, var(--font-mono));
font-weight: var(--fw-code);
+1 -1
Переглянути файл
@@ -454,7 +454,7 @@ export function DatabaseView() {
case "source":
return sourceIcon(n.source);
case "database":
return "database";
return "db-database";
case "schema":
return "db-schema";
case "folder":
+184 -6
Переглянути файл
@@ -1,34 +1,42 @@
/**
* Dialogs of the Database tree's object actions, after IDEA's: Rename, Confirm
* Drop, Truncate, Modify Table / New Table (with a Preview of the SQL they
* run), Remove Data Source, Data Source from URL, and the Quick Documentation popup.
* Drop, Truncate, Modify Table / New Table, New Database / New Schema (with a
* Preview of the SQL they run), Remove Data Source, Data Source from URL, and the Quick Documentation popup.
*/
import { useEffect, useMemo, useRef, useState } from "react";
import { call, commands, type DbColumnInfo, type DbDriver } from "@/platform/ipc";
import { highlightInto } from "@/editor/lsp/markdown";
import { Button, Checkbox, Dialog, IconButton, Input, Popup, Icon, T } from "@/ui";
import { Button, Checkbox, Dialog, IconButton, Input, Popup, Icon, Select, T, type SelectOption } from "@/ui";
import { parseSourceUrl, sourceLabel, splitTarget } from "./model";
import { nodeTarget, schemaObjectOf, tableOf, type DbNode } from "./nodes";
import {
alterTableSql,
canAlterColumn,
createDatabaseSql,
createSchemaSql,
createTableSql,
draftOf,
dropDatabaseSql,
dropSql,
ident,
reference,
renameSql,
truncateSql,
type ColumnDraft,
templateOf,
type CreateOptions,
type DbObjectRef,
} from "./objects";
import {
closeDialog,
detailsKey,
connectedTargets,
createDatabase,
dropDatabase,
loadDetails,
openSourceDialog,
readableDdl,
refresh,
renameSource,
runSql,
sourceById,
@@ -80,14 +88,15 @@ function objectName(o: DbObjectRef): string {
function useRunner() {
const [busy, setBusy] = useState(false);
const running = useRef(false);
const runAndClose = async (id: string, statements: string[]) => {
if (running.current) return;
const runAndClose = async (id: string, statements: string[]): Promise<boolean> => {
if (running.current) return false;
running.current = true;
setBusy(true);
const ok = await runSql(id, statements);
running.current = false;
setBusy(false);
if (ok) closeDialog();
return ok;
};
return { busy, runAndClose };
}
@@ -116,7 +125,7 @@ function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }
width={480}
buttons={[
{ label: "Cancel", role: "cancel" },
{ label: "Refactor", role: "default", disabled: busy || !name.trim(), onClick: submit },
{ label: "Refactor", role: "default", disabled: busy || !name.trim(), onClick: () => void submit() },
]}
>
<div className={styles.dialogBody}>
@@ -213,6 +222,169 @@ function TruncateDialog({ id, schema, table }: { id: string; schema: string; tab
);
}
// ---- New Database / New Schema / Drop database ---------------------------------
const TEMPLATES: SelectOption[] = [
{ value: "", label: "Server default" },
...["template0", "template1"].map((name) => ({ value: name, label: name, verbatim: true })),
];
/** An optional text field of the create dialogs: empty leaves it to the server. */
function OptionField({
id,
label,
value,
onChange,
}: {
id: string;
label: string;
value: string;
onChange: (value: string) => void;
}) {
return (
<>
<label className={styles.formLabel} htmlFor={id}>
{tx(label)}
</label>
<Input id={id} placeholder="Server default" value={value} onChange={(e) => onChange(e.target.value)} />
</>
);
}
/** New › Database (`database`) or New › Schema (`schema`) in target `id`. */
function CreateDialog({ id, what }: { id: string; what: "database" | "schema" }) {
const driver = driverOf(id);
const [name, setName] = useState("");
const [opts, setOpts] = useState<CreateOptions>({});
const { busy: running, runAndClose } = useRunner();
const [creating, setCreating] = useState(false);
const busy = running || creating;
const sql = (what === "database" ? createDatabaseSql : createSchemaSql)(driver, name.trim() || "<name>", opts);
const submit = async () => {
if (what === "schema") {
if (await runAndClose(id, [sql])) void refresh(id);
return;
}
setCreating(true);
if (await createDatabase(id, templateOf(driver, opts), sql)) closeDialog();
else setCreating(false);
};
const field = (key: keyof CreateOptions, label: string) => (
<OptionField
id={`db-new-${key}`}
label={label}
value={opts[key] ?? ""}
onChange={(value) => setOpts((o) => ({ ...o, [key]: value }))}
/>
);
return (
<Dialog
open
onClose={closeDialog}
title={what === "database" ? "New Database" : "New Schema"}
width={560}
buttons={[
{ label: "Cancel", role: "cancel" },
{ label: "OK", role: "default", disabled: busy || !name.trim(), onClick: submit },
]}
>
<div className={styles.form}>
<label className={styles.formLabel} htmlFor="db-new-name">
<T>Name:</T>
</label>
<Input id="db-new-name" autoFocus value={name} onChange={(e) => setName(e.target.value)} />
{what === "database" && driver === "postgres" && (
<>
{field("owner", "Owner:")}
<label className={styles.formLabel} htmlFor="db-new-template">
<T>Template:</T>
</label>
<Select
id="db-new-template"
value={opts.template ?? ""}
options={TEMPLATES}
onChange={(template) => setOpts((o) => ({ ...o, template }))}
/>
<span />
<span className={styles.formHint}>
<T>Restoring a dump needs template0: template1 can already hold extensions and schemas.</T>
</span>
{field("encoding", "Encoding:")}
{field("tablespace", "Tablespace:")}
</>
)}
{what === "database" && driver === "sqlServer" && field("collation", "Collation:")}
{what === "schema" && driver === "mysql" && (
<>
{field("charset", "Character set:")}
{field("collation", "Collation:")}
</>
)}
{what === "schema" && driver !== "mysql" && field("owner", "Owner:")}
<div className={styles.formFull}>
<SqlPreview sql={sql} />
</div>
</div>
</Dialog>
);
}
/** PostgreSQL 13 added `drop database … with (force)`. */
const PG_FORCE_DROP = 130000;
function DropDatabaseDialog({ id, database }: { id: string; database: string }) {
const driver = driverOf(id);
const [force, setForce] = useState(false);
const [version, setVersion] = useState<number | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
if (driver !== "postgres") return;
let live = true;
void withConnection(id, () => call(commands.dbServerVersion(id)))
.then((v) => live && setVersion(v))
.catch(() => {});
return () => {
live = false;
};
}, [id, driver]);
const canForce = driver === "sqlServer" || (version ?? 0) >= PG_FORCE_DROP;
const sql = dropDatabaseSql(driver, database, force && canForce);
const submit = async () => {
setBusy(true);
if (await dropDatabase(id, database, sql)) closeDialog();
else setBusy(false);
};
return (
<Dialog
open
onClose={closeDialog}
title="Confirm Drop"
width={520}
buttons={[
{ label: "Cancel", role: "cancel" },
{ label: "OK", role: "default", disabled: busy, onClick: () => void submit() },
]}
>
<div className={styles.dialogBody}>
<div className={styles.dialogLead}>
{tx`Drop database`} <strong>{database}</strong>
{tx`? This cannot be undone.`}
</div>
<span className={styles.formHint}>
<T>The IDE closes its own connections to the database first.</T>
</span>
<Checkbox
checked={force && canForce}
onChange={setForce}
disabled={!canForce}
label="Close the sessions of other clients"
/>
<SqlPreview sql={sql} />
</div>
</Dialog>
);
}
// ---- Modify Table / New Table -----------------------------------------------
const TYPES: Record<DbDriver, string[]> = {
@@ -726,6 +898,12 @@ export function ObjectDialogs() {
return <DropDialog id={dialog.id} object={dialog.object} />;
case "truncate":
return <TruncateDialog id={dialog.id} schema={dialog.schema} table={dialog.table} />;
case "createDatabase":
return <CreateDialog id={dialog.id} what="database" />;
case "createSchema":
return <CreateDialog id={dialog.id} what="schema" />;
case "dropDatabase":
return <DropDatabaseDialog id={dialog.id} database={dialog.database} />;
case "modifyTable":
return (
<ModifyTableDialog
-2
Переглянути файл
@@ -81,8 +81,6 @@ function tableTarget(arg: unknown): TableCommandTarget {
return { rows: activeCellGrid()?.selectedRows() ?? [], editor: null };
}
export { activateSettingsPages } from "./settingsPages";
export function activate(): () => void {
const disposers = [
onIdeEvent("dbSourcesChanged", () => {
+50
Переглянути файл
@@ -4,8 +4,12 @@ import {
alterTableSql,
canDrop,
canModifyTable,
createDatabaseSql,
createSchemaSql,
createTableSql,
draftOf,
dropDatabaseSql,
templateOf,
dropSql,
ident,
reference,
@@ -341,3 +345,49 @@ describe("snowflake object SQL", () => {
expect(alterTableSql("snowflake", "HR", "EMP", "EMP", dropped)).toEqual(["alter table HR.EMP drop column NAME;"]);
});
});
describe("database and schema SQL", () => {
it("creates a PostgreSQL database with only the options given", () => {
expect(createDatabaseSql("postgres", "shop", {})).toBe("create database shop;");
expect(
createDatabaseSql("postgres", "Shop Copy", {
owner: "app",
template: "template0",
encoding: "UTF8",
tablespace: " ",
}),
).toBe(`create database "Shop Copy" owner app template template0 encoding 'UTF8';`);
expect(createDatabaseSql("postgres", "shop", { encoding: "it's" })).toBe("create database shop encoding 'it''s';");
});
it("names the database the server copies for a new one", () => {
expect(templateOf("postgres", {})).toBe("template1");
expect(templateOf("postgres", { template: "template0" })).toBe("template0");
expect(templateOf("sqlServer", { template: "ignored" })).toBe("model");
});
it("creates a SQL Server database with a collation", () => {
expect(createDatabaseSql("sqlServer", "shop", { collation: "Latin1_General_CI_AS", owner: "ignored" })).toBe(
"create database shop collate Latin1_General_CI_AS;",
);
});
it("creates a schema with an owner, and a MySQL schema as a database", () => {
expect(createSchemaSql("postgres", "sales", {})).toBe("create schema sales;");
expect(createSchemaSql("postgres", "sales", { owner: "app" })).toBe("create schema sales authorization app;");
expect(createSchemaSql("sqlServer", "sales", { owner: "dbo" })).toBe("create schema sales authorization dbo;");
expect(createSchemaSql("mysql", "shop", { charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci" })).toBe(
"create database shop character set utf8mb4 collate utf8mb4_0900_ai_ci;",
);
expect(createSchemaSql("mysql", "shop", {})).toBe("create database shop;");
});
it("drops a database, forcing out other sessions when asked", () => {
expect(dropDatabaseSql("postgres", "shop", false)).toBe("drop database shop;");
expect(dropDatabaseSql("postgres", "shop", true)).toBe("drop database shop with (force);");
expect(dropDatabaseSql("sqlServer", "shop", false)).toBe("drop database shop;");
expect(dropDatabaseSql("sqlServer", "shop", true)).toBe(
"alter database shop set single_user with rollback immediate;\ndrop database shop;",
);
});
});
+57
Переглянути файл
@@ -180,6 +180,63 @@ export function truncateSql(
return `truncate table ${q}${opts.restartIdentity ? " restart identity" : ""}${opts.cascade ? " cascade" : ""};`;
}
const literal = (value: string) => `'${value.replace(/'/g, "''")}'`;
/** Options of New › Database / New › Schema; an empty or absent one is left to the server. */
export interface CreateOptions {
owner?: string;
template?: string;
encoding?: string;
tablespace?: string;
charset?: string;
collation?: string;
}
/** New › Database (PostgreSQL, SQL Server). */
export function createDatabaseSql(driver: DbDriver, name: string, opts: CreateOptions): string {
const clauses: string[] = [];
const add = (keyword: string, value: string | undefined, quote = (v: string) => ident(driver, v)) => {
if (value?.trim()) clauses.push(`${keyword} ${quote(value.trim())}`);
};
if (driver === "postgres") {
add("owner", opts.owner);
add("template", opts.template);
add("encoding", opts.encoding, literal);
add("tablespace", opts.tablespace);
} else if (driver === "sqlServer") {
add("collate", opts.collation, (v) => v);
}
return `create database ${ident(driver, name)}${clauses.map((c) => ` ${c}`).join("")};`;
}
/** The database the server copies for New › Database: the chosen template on PostgreSQL, `model` on SQL Server. */
export function templateOf(driver: DbDriver, opts: CreateOptions): string {
return driver === "sqlServer" ? "model" : opts.template?.trim() || "template1";
}
/** New › Schema; on MySQL a schema is a database, with a character set and collation instead of an owner. */
export function createSchemaSql(driver: DbDriver, name: string, opts: CreateOptions): string {
if (driver === "mysql") {
const charset = opts.charset?.trim() ? ` character set ${opts.charset.trim()}` : "";
const collation = opts.collation?.trim() ? ` collate ${opts.collation.trim()}` : "";
return `create database ${ident(driver, name)}${charset}${collation};`;
}
const owner = opts.owner?.trim() ? ` authorization ${ident(driver, opts.owner.trim())}` : "";
return `create schema ${ident(driver, name)}${owner};`;
}
/**
* Drop on a database node. `force` ends the sessions of other clients first:
* `with (force)` on PostgreSQL 13+, single-user mode on SQL Server.
*/
export function dropDatabaseSql(driver: DbDriver, name: string, force: boolean): string {
const db = ident(driver, name);
// One batch: the session that sets single-user mode is the single user, so it must drop too.
if (driver === "sqlServer" && force)
return `alter database ${db} set single_user with rollback immediate;\ndrop database ${db};`;
return `drop database ${db}${force && driver === "postgres" ? " with (force)" : ""};`;
}
export type ScriptKind = "selectAll" | "selectFirst" | "insert" | "update" | "delete";
export const SCRIPT_LABELS: Record<ScriptKind, string> = {
+10
Переглянути файл
@@ -417,6 +417,16 @@ describe("connection and metadata continuations", () => {
});
}
it("does not list sources after the project is closed", async () => {
// Closing the project resets `loaded`; a still-mounted SQL console then asks for sources again.
useProject.setState({ project: null });
backend.sources.mockRejectedValue(new Error("no project is open in this window"));
backend.connected.mockRejectedValue(new Error("no project is open in this window"));
await loadSources();
expect(ui.notify).not.toHaveBeenCalled();
expect(backend.sources).not.toHaveBeenCalled();
});
it("can load metadata again after a disconnect fails", async () => {
backend.disconnect.mockRejectedValueOnce(new Error("disconnect failed"));
await expect(disconnect("pg")).rejects.toThrow("disconnect failed");
+53
Переглянути файл
@@ -130,6 +130,11 @@ export type DialogState =
/** Confirm Drop / Truncate, with a preview of the statement. */
| { kind: "drop"; id: string; object: DbObjectRef }
| { kind: "truncate"; id: string; schema: string; table: string }
/** New › Database of data source `id`; New › Schema in target `id`. */
| { kind: "createDatabase"; id: string }
| { kind: "createSchema"; id: string }
/** Drop on database `database` of data source `id`. */
| { kind: "dropDatabase"; id: string; database: string }
/** Modify Table (`table` null: New › Table); `focusColumn` selects a column, `addColumn` starts a new one. */
| { kind: "modifyTable"; id: string; schema: string; table: string | null; focusColumn?: string; addColumn?: boolean }
/** Quick Documentation of a tree node, shown at `anchor` (client coordinates). */
@@ -325,6 +330,8 @@ function sourceMutation(id: string): () => boolean {
}
export async function loadSources(): Promise<void> {
// Closing the project resets `loaded` while its SQL consoles are still mounted.
if (!useProject.getState().project) return;
const request = ++sourcesRequest;
const current = projectRequest();
const intents = new Map(connectionIntents);
@@ -614,6 +621,20 @@ export function listsDatabases(source: DataSource | undefined): boolean {
);
}
/** New › Database and Drop on database nodes: PostgreSQL and SQL Server data sources that show their databases. */
export function createsDatabases(source: DataSource | undefined): boolean {
return listsDatabases(source) && source?.driver !== "snowflake";
}
/** The target New › Schema creates a schema in: a database node, or a data source that shows schemas directly. */
export function newSchemaTarget(n: DbNode): string | null {
if (n.kind === "database") return createsDatabases(sourceById(n.id)) ? n.id : null;
if (n.kind !== "source" || !n.source.id) return null;
const driver = n.source.driver;
if (driver !== "postgres" && driver !== "sqlServer" && driver !== "mysql") return null;
return listsDatabases(n.source) ? null : n.source.id;
}
interface LoadedLevels {
schemas: string[];
tables: [string, string][];
@@ -1091,6 +1112,38 @@ export async function runSql(id: string, texts: string[]): Promise<boolean> {
}
}
/**
* Creates a database on data source `id` with `sql` after disconnecting `template`, then refreshes
* the data source, reloading what the tree had shown of `template` too.
*/
export async function createDatabase(id: string, template: string, sql: string): Promise<boolean> {
const levels = loadedLevels(id);
await disconnect(`${id}:${template}`);
try {
// Asks for a password the data source does not save, like any statement it runs.
await withConnection(id, () => call(commands.dbCreateDatabase(id, template, sql)));
} catch (e) {
notifications().notify({ level: "error", title: tx`Cannot create database`, body: message(e) });
void refresh(id, levels);
return false;
}
void refresh(id, levels);
return true;
}
/** Drops `database` of data source `id` with `sql` after disconnecting it, then refreshes the data source. */
export async function dropDatabase(id: string, database: string, sql: string): Promise<boolean> {
await disconnect(`${id}:${database}`);
try {
await withConnection(id, () => call(commands.dbDropDatabase(id, database, sql)));
} catch (e) {
notifications().notify({ level: "error", title: tx`Cannot drop database ${database}`, body: message(e) });
return false;
}
void refresh(id);
return true;
}
/** Opens the query console of `id` with `text` appended and selected (SQL Scripts › …). */
export async function openConsoleWith(id: string, text: string): Promise<void> {
let path: string;
+27
Переглянути файл
@@ -15,6 +15,7 @@ import {
DB_TOOL_WINDOW,
OUTPUT_TAB,
connect,
createsDatabases,
RESULTS_VIEW,
detailsKey,
disconnect,
@@ -24,6 +25,7 @@ import {
loadSources,
loadTables,
consoleFiles,
newSchemaTarget,
newConsole,
openConsole,
openConsoleFile,
@@ -358,6 +360,9 @@ export function registerDatabaseTreeActions(): () => void {
if (!n) return;
const id = nodeTarget(n);
if (n.kind === "source") return void removeSource(n.source);
const source = sourceById(id);
if (n.kind === "database" && !n.current && !source?.readOnly && createsDatabases(source))
return openDialog({ kind: "dropDatabase", id: splitTarget(n.id).id, database: n.name });
const o = objectOf(n);
if (id && o && canDrop(driverOf(id), o)) openDialog({ kind: "drop", id, object: o });
},
@@ -390,6 +395,28 @@ export function registerDatabaseTreeActions(): () => void {
});
},
}),
tree({
id: "db.newDatabase",
title: "Database…",
icon: "db-database",
keywords: ["create database", "new database"],
run: ({ arg }) => {
const source = sourceOf(nodeFrom(arg));
if (source?.id && !source.readOnly && createsDatabases(source))
openDialog({ kind: "createDatabase", id: source.id });
},
}),
tree({
id: "db.newSchema",
title: "Schema…",
icon: "db-schema",
keywords: ["create schema", "new schema"],
run: ({ arg }) => {
const n = nodeFrom(arg);
const id = n && newSchemaTarget(n);
if (id && !sourceById(id)?.readOnly) openDialog({ kind: "createSchema", id });
},
}),
tree({
id: "db.newTable",
title: "Table",
+25 -3
Переглянути файл
@@ -5,7 +5,15 @@ import { fileSourceName, parseSourceUrl } from "./model";
import { VENDORS, vendorPreset } from "./vendors";
import { nodeTarget, objectOf, tableOf, type DbNode } from "./nodes";
import { SCRIPT_LABELS, canDrop, canModifyTable, canRename, type ScriptKind } from "./objects";
import { connectedTargets, openDialog, openSourceDialog, sourceById, useDatabase } from "./store";
import {
connectedTargets,
createsDatabases,
newSchemaTarget,
openDialog,
openSourceDialog,
sourceById,
useDatabase,
} from "./store";
import { readClipboardPlainText } from "@/platform/clipboard";
import { useRemote } from "@/platform/remote";
import { dumpScope, mysqlDumpScope } from "./dumpTools";
@@ -113,6 +121,8 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
const rename = act("db.rename", n, { disabled: !(n.kind === "source" || (o && canRename(driver, o))) });
const drop = act("db.drop", n, { disabled: !o || !canDrop(driver, o) });
const copyRef = act("db.copyReference", n);
const readOnly = !!sourceById(id)?.readOnly;
const newSchema = newSchemaTarget(n) ? [act("db.newSchema", n, { disabled: readOnly })] : [];
const navigation = (extra: MenuItem[] = []): MenuItem => ({
label: "Navigation",
submenu: [...extra, act("db.jumpToConsole", n)],
@@ -124,7 +134,18 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
return [
act("db.properties", n, { label: "Properties" }),
sep,
{ label: "New", icon: "plus", submenu: [newConsole, sep, ...dataSourceItems()] },
{
label: "New",
icon: "plus",
submenu: [
newConsole,
sep,
...(createsDatabases(n.source) ? [act("db.newDatabase", n, { disabled: readOnly })] : []),
...newSchema,
...(createsDatabases(n.source) || newSchema.length ? [sep] : []),
...dataSourceItems(),
],
},
{ label: "Copy/Paste", submenu: [copyRef, act("db.duplicateSource", n)] },
refresh,
...(n.source.driver === "snowflake" ? [act("db.introspect", n)] : []),
@@ -144,7 +165,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
}
case "database":
return [
{ label: "New", icon: "plus", submenu: [newConsole] },
{ label: "New", icon: "plus", submenu: [newConsole, ...(newSchema.length ? [sep, ...newSchema] : [])] },
{ label: "Copy/Paste", submenu: [copyRef] },
refresh,
act("db.disconnect", n, { disabled: !useDatabase.getState().connected.has(id) || n.current }),
@@ -152,6 +173,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
navigation(),
sqlScripts(n, false),
...importExport(dumpItems(n, true)),
...(createsDatabases(sourceById(id)) ? [sep, act("db.drop", n, { disabled: n.current || readOnly })] : []),
];
case "schema":
case "folder":
+57
Переглянути файл
@@ -0,0 +1,57 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { provideEditorService } from "@/workbench/contributions";
import { addBreakpoint, useBreakpoints } from "../breakpoints/store";
import { DebuggerOverlays } from "../ui/Overlays";
import { useOverlays } from "../ui/popoverStore";
const openFile = vi.fn(async () => undefined);
provideEditorService({ openFile } as never);
const path = "/p/main.py";
describe("the Breakpoints dialog", () => {
beforeEach(() => {
openFile.mockClear();
useBreakpoints.setState({ byFile: {}, status: {}, muted: false });
const first = addBreakpoint(path, 2, { condition: "value == 2" });
addBreakpoint(path, 6);
useOverlays.setState({ breakpoints: { id: first.id } } as never);
});
afterEach(() => {
cleanup();
act(() => useOverlays.setState({ breakpoints: null } as never));
});
const dialog = () => screen.getByRole("dialog", { name: "Breakpoints" });
const row = (name: string) => within(within(dialog()).getByLabelText("All breakpoints")).getByText(name);
const condition = () => within(dialog()).getByLabelText("Condition") as HTMLInputElement;
/** A row's mouse click as the list sees it: mousedown selects, click (with its count) activates. */
const clickRow = (name: string, detail: number) => {
fireEvent.mouseDown(row(name), { button: 0 });
fireEvent.click(row(name), { detail });
};
const breakpointAt = (line: number) => useBreakpoints.getState().byFile[path]!.find((b) => b.line === line)!;
it("selects a breakpoint on click and goes to its source on double-click", () => {
render(<DebuggerOverlays />);
clickRow("main.py:7", 1);
expect(openFile).not.toHaveBeenCalled();
// Its details show beside the list.
expect(within(dialog()).getAllByText("main.py:7")).toHaveLength(2);
clickRow("main.py:3", 2);
expect(openFile).toHaveBeenCalledWith(path, { selection: { line: 2, col: 0 } });
});
it("saves the condition being typed when the dialog closes or another breakpoint is shown", () => {
render(<DebuggerOverlays />);
fireEvent.change(condition(), { target: { value: "value == 1" } });
fireEvent.click(within(dialog()).getByRole("button", { name: "Done" }));
expect(breakpointAt(2).condition).toBe("value == 1");
act(() => useOverlays.setState({ breakpoints: { id: breakpointAt(2).id } } as never));
fireEvent.change(condition(), { target: { value: "value == 3" } });
clickRow("main.py:7", 1);
expect(breakpointAt(2).condition).toBe("value == 3");
});
});
Loaded 100 of 221 files, more files were not shown because too many files have changed in this diff. Show more