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

..
Автор SHA1 Повідомлення Дата
l0ng-ai aa1fd84a1d fix(keymap): list the data editor actions in the VS Code preset
The VS Code preset must name every IntelliJ action id; #3551 added the
db.* data editor actions to the IntelliJ presets only.
2026-11-15 23:16:15 +08:00
Sameh Elhawaryтаsamehelhawary acea7e6235 feat(php): Phoxite as a selectable PHP language server (#3541)
languages/php.toml gains a phoxite entry (phoxite-lsp over stdio), a fallback listed after phpactor; Intelephense stays the default and users pick Phoxite under Language Servers. ide-tools installs it from the samehelhawary/phoxite GitHub releases (a binary per platform with a .sha256 beside it). A server entry can now name the servers it replaces: those stay away while it serves the file (Phoxite replaces laravel-lsp, which it covers), including when the replacing fallback takes over after a server gives up.

Co-authored-by: samehelhawary <[email protected]>
2026-11-15 23:14:32 +08:00
l0ng-ai 25197b3215 fix(vcs): show a committed directory symlink's target in revision diffs (#3554)
Revision content was decoded with the working file's encoding, read whenever the path existed. For a symlink to a folder that path is a directory, so loading failed and the Git Log diff showed '<path> is a directory'. The working file is now consulted only when it is a regular file; otherwise the encoding is detected from the revision's blob.

Closes #3528
2026-11-15 23:11:50 +08:00
Vadim LazukтаInf1mum 55786a7030 fix(vcs): the Git Log rename label names the original directory (#3546)
The changed-file label trimmed a rename's old path to its base name, so a move between directories looked like a rename in place. A shared renameFrom() now says 'renamed from <name>' within one directory and 'moved from <old path relative to the new directory>' otherwise, as IDEA does; Git Log and the GitHub create / pull request change trees use it.

Closes #3529

Co-authored-by: Inf1mum <[email protected]>
2026-11-15 23:09:13 +08:00
Vadim LazukтаInf1mum b7adbbb17c fix(project): mark symlinks with a link arrow in the tree (#3547)
Directory and file symlinks used the same icons as real folders and files. The Project view now overlays IDEA's link arrow (expui nodes/symlink) on every entry the listing reports as a symlink; the model already carried the flag, so no extra stat calls.

Closes #3527

Co-authored-by: Inf1mum <[email protected]>
2026-11-15 23:06:39 +08:00
l0ng-ai d1290c76ea feat(database): data editor row and toolbar commands as actions (#3551)
Reload Page, First / Previous / Next / Last Page, Add Row, Export Data, Delete Rows, Restore Rows, Edit Cell and the cell copy commands were menu items or toolbar buttons only. They are now db.* actions supplied by the table editor and the console result grid through their focus handle, so they appear in Find Action and take Keymap shortcuts; menus and buttons run the same actions. DataGrip's defaults bind Reload Page, Previous / Next Page and Add Row, and Delete Rows on Windows and Linux.

Closes #3506
2026-11-15 23:03:35 +08:00
l0ng-ai 0febd3e170 fix(editor): Sort Lines orders by character code (#3548)
Sort Lines used a locale-aware collator, which interleaves upper- and lowercase letters. It now compares UTF-16 code units, the order IDEA's Sort Lines uses (String.compareTo) and LC_ALL=C sort gives.

Closes #3516
2026-11-15 22:47:11 +08:00
Akbar Husain acee0d5edb feat(libraries): show the Zig standard library and build.zig.zon packages in External Libraries (#3526)
A zig detector joins the External Libraries pipeline: the standard library from zig env (struct-literal and JSON output), and the fetched build.zig.zon dependencies from the global package cache, as p/<hash> folders (Zig <= 0.14) or p/<hash>.tar.gz blobs (Zig >= 0.15) browsed read-only through the archive VFS, which now reads gzip'd tars. Nothing is downloaded; path dependencies stay in the project tree. New setting languages.zig.zig (directory of zig, empty = PATH).

Co-authored-by: akbar1214 <[email protected]>
2026-11-15 22:45:18 +08:00
Akbar Husain a02a594010 perf(text): byte-parallel scans in ide-text, ide-syntax and ide-language (#3539)
Document open/diff and UTF-16 position mapping decoded whole files char by char. common_ends compares bytes and backs off to char boundaries, utf16_len classifies bytes with an ASCII fast path, LF-only text skips line-ending normalisation, and memchr_newlines uses memchr. Outputs are unchanged; text/open_1mb -60%, diff_two_edits_1mb -38%.

Co-authored-by: akbar1214 <[email protected]>
2026-11-15 22:38:51 +08:00
PONK 6bb4a6375a docs: add Turkish README translation (#3519)
Adds README.tr.md and a Türkçe link in the README language switcher.

Co-authored-by: lprvy <[email protected]>
2026-11-15 22:37:30 +08:00
Mr0Bread f15c2c2b5e perf(startup): load DiffEditor, the Run console and the file-revision chooser on demand (#3544)
DiffWindow, the Services detail pane and Compare with Revision imported these statically, which kept their chunks in the startup set despite lazy imports elsewhere. They now load on demand; initial JS drops by about 34 KB gzip.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 22:35:26 +08:00
Mr0Bread a83a1a54e5 fix(agents): refresh stale agent versions after CLI updates (#3538)
The New Task page reused a probe cached for the whole session, so an updated CLI kept showing its old version. The selected agent is probed again (initialize only, no session) when the page is shown or the window regains focus, without overlapping probes.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 22:35:21 +08:00
Mr0Bread 0d499f3af6 fix(agents): render Nerd Font icons in agent task titles (#3523)
No font in the UI stack had private-use icons, so OMP task titles showed a missing-glyph box. The UI stack now ends with --font-icons, the first installed Nerd Font (proportional faces first), resolved once when the window is idle. The terminal's Nerd Font list moved to platform/fonts unchanged.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 22:35:17 +08:00
zhzhsxтаzhzhsx e06c890ca4 fix(editor): show completion documentation beside the list (#3522)
The completion documentation was drawn inside the lookup popup, which clipped it or let it cover the options. positionInfo now places it beside the list on the side with more room, top edges aligned, with capped width and height.

Co-authored-by: zhzhsx <[email protected]>
2026-11-15 22:35:12 +08:00
Muuтаmuutot 6295cc2237 fix(vcs): keep inline blame on its line when soft wraps are on (#3518)
The line-end blame was an in-flow nowrap inline-block, so with soft wrap a label that did not fit was folded onto a new visual row and stretched the line. It is now a zero-width anchor with an absolutely positioned label, like code-vision hints and plugin line-end messages; the inner box is the hover and click target.

Co-authored-by: muutot <[email protected]>
2026-11-15 22:35:07 +08:00
Mamaev Igor 8349938481 fix(vim): enable Vim in notebook cells (#3515)
Notebook cell editors did not include the embedded editor contributions, so Vim (an embedded contribution) never attached to them. CellEditor now adds embeddedEditorExtensions like the other embedded editors.

Co-authored-by: pxc1984 <[email protected]>
2026-11-15 22:35:03 +08:00
Alexanderтаformiat cb2c4345d1 fix(vcs): a branch whose remote branch is gone tracks nothing (#3533)
upstream_of returned the configured upstream name even when its tracking ref had been deleted and pruned, so Git Branches still showed origin/<name>, Update stayed enabled and incoming commits were polled against a missing ref. It now reports an upstream only while the tracking ref exists; branches() and branch_info() share it.

Closes #3530

Co-authored-by: formiat <[email protected]>
2026-11-15 22:25:02 +08:00
l0ng-ai 22f409ae76 feat(diff): external diff tool and Show Diff for Lines (#3543)
- Settings › Tools › External Diff Tools: a program and its parameters
  (%1 the left file, %2 the right file, %3 the title). Diff viewers then
  offer Show Diff in External Tool (toolbar button and action). Saved
  files are passed as they are (saved first); revisions and texts go to
  temporary files named after the file. The program is always read from
  the global settings, never a project's, and runs on this machine.
- Show Diff for Lines (vcs.showDiffForLines): with the caret on changed
  lines in the editor, opens the file's diff at that line.
2026-11-15 22:18:58 +08:00
l0ng-ai b2dc59eb0f feat(diff): blank diff window, Swap Sides, and Search In Changes (#3540)
- Open Blank Diff Window: a new diff tab with two empty, editable sides;
  the editor's selection fills the left one. Text typed into either side
  survives viewer changes (mode, highlighting, Swap Sides).
- Swap Sides: a toolbar button and action for diffs whose sides the user
  picked (Compare With…, Compare Files, Compare with Clipboard, the
  command-line diff and blank diffs). Diffs of revisions keep their order.
- Search In Changes: a find bar filter in diffs that limits matches to the
  changed ranges of the searched side. It is per diff and applies to
  finding only; the replace bar searches the whole side.
2026-11-15 21:59:59 +08:00
Mr0Bread f5641f9c6f feat(agents): say what the agent is doing in the working status, with opt-in playful words (#3459)
The row under a working conversation showed a constant Working…. It now follows the turn's latest entry: Thinking…, Writing…, Reading…, Editing…, Running a command…, Running a subagent… and so on, with Working… for the rest.

Settings › Agents › Working Status adds playful words per activity, off by default. When on, they rotate from the start or after a configurable quiet time (0–600 s). Each word stays 8 s, or at least 3 s once the activity changes. Screen readers keep hearing the plain status. Users can replace or clear each activity's words.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 21:55:09 +08:00
l0ng-ai dcd4f150bd fix(kotlin): stop notifying about every Kotlin compiler error in Maven projects (#3521)
The Kotlin-to-Java bridge popped an error notification for each new failure message, so mid-edit Kotlin with autosave produced a balloon per save for errors its editor already shows. Compiler errors in project sources now only update the Problems entry on pom.xml; a build that fails without one (Maven, a goal that didn't run, the bridge bundle or JDT snapshot) still notifies once per message.
2026-11-15 19:26:00 +08:00
l0ng-ai 8caeb1305f fix(editor): indent Kotlin, Scala, Dart and Groovy brackets opened after a string (#3520)
The string-interpolation wrapper let the stock clike tokenizer consume an empty string on a new stream at column 0 whenever a literal opened; clike read that as a new line and reset the line's indentation to 0, so a bracket opened later on the same line indented its contents from column 0. Enter and paste with Reformat on Paste put the following lines at the wrong column. The empty string is now tokenized at the literal's own column, which fixes all dialects served by the wrapper (Kotlin, Scala, Dart, Groovy; C# shares the code path).
2026-11-15 19:21:48 +08:00
l0ng-ai 7ec0a4fed2 feat(diff): Esc closes a diff tab; switch panes with ⌃⇧⇥; move a diff window back to a tab (#3517)
Close Diff Editor: Esc in a diff editor tab closes it once the find bar, a selection, completion or a popup don't take it; panels, dialogs and diff windows keep their own Esc. Select Opposite Diff Pane (⌃⇧⇥ in the IntelliJ keymaps) moves focus to the other side of a side-by-side diff and wins over the Switcher while a diff is focused. A diff window's Show Diff in Editor Tab saves its edits, opens the diff as a tab in its project window and closes the window.
2026-11-15 18:42:16 +08:00
l0ng-ai 733b6cff1d feat(run): pin Run and Debug tabs; a new run replaces one finished, unpinned tab (#3514)
Run and Debug tabs can be pinned (context menu, Pin Active Tab, or the pin in place of the close button). A new run or debug session takes the place of one finished, unpinned tab: the same configuration's, else the selected one, else the first; Run used to add a tab per configuration, so finished tabs piled up. Rerun on a pinned tab restarts it in place and keeps it pinned. Settings > Run/Debug gets "Make configurations pinned by default".

Siblings: Run, Debug, Find and Usages tabs share one context menu (Close Tab, Close All Tabs, Close Other Tabs, Pin/Unpin Tab); Find and Usages show a pinned tab with the pin in place of its close button.
2026-11-15 18:29:15 +08:00
l0ng-ai b0860ed1e2 fix(debugger): a new debug session replaces one finished tab, not all of them (#3512)
Starting a session dropped every finished Debug tab, so ended sessions of other configurations disappeared with it. The new session now takes the place of a single finished tab: the same-named one, else the selected one, else the first; other finished tabs stay. A prepared start replaces it when its build begins and doesn't replace another when the adapter starts.
2026-11-15 18:01:31 +08:00
l0ng-ai 48a13cb8fa fix(terminal): paste paths of files dragged from the Project view (#3511)
The terminal took file paths only from OS drops (Finder / Explorer). A
file or folder dragged from the Project view onto the terminal did nothing.
The terminal is now a drop target for Project view drags too and pastes the
paths at the prompt, shell-quoted, without executing; it also works in a
remote window, where the paths are the remote project's.

Fixes #3503
2026-11-15 17:28:05 +08:00
l0ng-ai c9488df786 fix(appearance): red-green vision setting also adjusts editor colours (#3510)
Adjust colors for red-green vision deficiency only recoloured VCS file
status, change markers and success, so in a file without changes it had no
visible effect. With the bundled dark and light schemes it now also uses the
schemes' red-green variants for syntax (keywords, strings, numbers, fields,
functions, annotations, TODO), errors (orange instead of red), warnings,
identifier-under-caret and search highlights, breakpoint lines and coverage.
Other colour themes and plugin themes keep their own editor colours.

Fixes #3500
2026-11-15 17:28:01 +08:00
l0ng-ai 4427ec2c07 fix(ui): restore hover backgrounds on the main menu and Review Mode buttons (#3509)
The main menu button (Windows and Linux title bar) and the Review Mode comment navigation buttons are plain buttons, so #2990's IconButton hover did not reach them. They paint --bg-toolbar-hover again; the main menu button keeps it while its menu is open. Gutter run markers, diff arrows and the database banner close button keep their icon-only hover.
2026-11-15 17:26:02 +08:00
Mr0Bread cf71a61cdf fix(ui): restore toolbar icon hover feedback (#2990)
Toolbar and tool window icon buttons (IconButton) paint --bg-toolbar-hover across their hit target again, so hovering shows the clickable area. Disabled buttons stay transparent; pressed, selected, focus ring and icon colours are unchanged. The hover colours match the toolbar tokens already used for the pressed state in Islands Light and Dark.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-15 17:23:13 +08:00
156 змінених файлів з 4792 додано та 467 видалено

No files matched your search

Створено
+5
Переглянути файл
@@ -4578,6 +4578,7 @@ dependencies = [
"ide-core",
"ide-extension",
"ide-text",
"memchr",
"parking_lot",
"regex-lite",
"serde",
@@ -4798,6 +4799,7 @@ name = "ide-sdk"
version = "0.1.45"
dependencies = [
"dunce",
"flate2",
"ide-core",
"ide-language",
"ide-run",
@@ -4807,6 +4809,7 @@ dependencies = [
"serde",
"serde_json",
"specta",
"tar",
"tempfile",
"toml 0.9.12+spec-1.1.0",
"tracing",
@@ -4963,6 +4966,7 @@ dependencies = [
"chardetng",
"dunce",
"encoding_rs",
"flate2",
"gix",
"globset",
"ide-core",
@@ -4973,6 +4977,7 @@ dependencies = [
"serde",
"serde_json",
"specta",
"tar",
"tempfile",
"tracing",
"trash",
+2
Переглянути файл
@@ -90,6 +90,8 @@ dunce = "1"
dirs = "6"
memmap2 = "0.9"
zip = { version = "9.2.3", default-features = false, features = ["deflate"] }
flate2 = "1"
tar = "0.4"
# search, index, language
grep-searcher = "0.1"
+1 -1
Переглянути файл
@@ -10,7 +10,7 @@
</p>
<p align="center">
English · <a href="README.zh-CN.md">简体中文</a>
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a>
</p>
<p align="center">
+79
Переглянути файл
@@ -0,0 +1,79 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="src-tauri/icons/source/openidea-wordmark-dark.svg">
<img src="src-tauri/icons/source/openidea-wordmark.svg" alt="OpenIDEA" height="56">
</picture>
</p>
<p align="center">
Bildiğin IDE, Rust ile yeniden yazıldı.
</p>
<p align="center">
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe
</p>
<p align="center">
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>İndir</b></a>
&nbsp;·&nbsp;
<a href="https://openidea.sh">Belgeler</a>
&nbsp;·&nbsp;
<a href="#performans-karşılaştırması">Performans</a>
&nbsp;·&nbsp;
<a href="#eklentiler">Eklentiler</a>
&nbsp;·&nbsp;
<a href="#topluluk">Topluluk</a>
</p>
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
OpenIDEA, IntelliJ IDEA'nın çalışma biçimini (kısayol tuşlarını, araç pencerelerini,
her şeyi arama alışkanlığını) çekirdeği Rust ile yazılmış yerel bir uygulamaya taşır.
Editör, kod analizi, hata ayıklayıcı (debugger), Git, terminal, veritabanı ve HTTP istemcileri;
60'tan fazla dil için. macOS, Windows ve Linux sürümleri var.
## Performans karşılaştırması
[freqtrade](https://github.com/freqtrade/freqtrade) projesini (Python, ~770 dosya)
önbellekler hazırken açma, 5 çalıştırmanın ortancası:
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
| ---------------------------------- | --------------------- | ---------------------- |
| Projeyle pencerenin açılması | **0,9 sn** | 3,1 sn |
| Hazır (CPU sakinleşti) | **1,1 sn** | 13,2 sn |
| Bellek (USS, tüm işlemler) | **169 MB** | 2011 MB |
| Hazır olana kadar CPU süresi | **2,4 sn** | 47,9 sn |
| Boştayken CPU | Bir çekirdeğin **%4**'ü | Bir çekirdeğin %7'si |
| Kapanma | **0,3 sn** | 5,9 sn |
`main` dalından derlenmiş bir OpenIDEA sürümü ve varsayılan ayar ve eklentilerle IDEA;
Windows 11, 32 çekirdekli AMD, 62 GB RAM.
IDEA, Python'u daha derinlemesine analiz eder; yani "hazır" iki tarafta aynı işi ifade etmez.
İkisi de dışarıdan, aynı yöntemle ölçüldü: kendi makinende ve projelerinde denemek için
[`perf/compare`](perf/compare) klasörüne bak.
## Eklentiler
Eklentiler; eylemler, kod tamamlama, hızlı düzeltmeler, araç pencereleri, özel editörler,
temalar, dosya simgeleri ve diller ekler. Korumalı (sandbox) WebAssembly bileşenleri olarak çalışırlar;
temalar, simge temaları ve diller için hiç kod yazmak gerekmez.
Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya da
`openidea-plugin new` ile kendininkini başlat. Ayrıntılar için [OpenIDEA eklentisi yazmak](https://openidea.sh/en/plugins) sayfasına ve
[resmi eklentilere](plugins/official) bak. Eklenti API'si hâlâ önizleme aşamasında.
## Topluluk
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
- WeChat grubu, katılmak için kodu okut:
<img src=".github/assets/wechat-group.png" alt="WeChat grubu QR kodu" width="200">
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
## Lisans
[Apache 2.0](LICENSE). Pakete dahil üçüncü taraf varlıklar [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md) dosyasında listelenir.
<sub>JetBrains ile bağlantılı değildir. IntelliJ IDEA, JetBrains s.r.o.'nun ticari markasıdır.</sub>
+25
Переглянути файл
@@ -42,6 +42,8 @@ pub struct Settings {
pub terminal: TerminalSettings,
pub actions_on_save: ActionsOnSaveSettings,
pub external_tools: Vec<ExternalTool>,
/// Tools › Diff & Merge › External Diff Tools.
pub external_diff: ExternalDiffSettings,
/// Language servers / debug adapters at a user-chosen location, by the
/// command the language definition launches (`elixir-ls`, `codelldb`).
pub tools: BTreeMap<String, ToolSettings>,
@@ -88,6 +90,16 @@ pub struct AgentSettings {
pub smooth_text: bool,
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
pub fit_window_width: bool,
/// While the agent works, playful words fill the pauses in what it reports.
pub playful_status: bool,
/// Seconds the agent reports nothing new before the playful words take over; 0 shows them
/// from the start.
pub playful_after_seconds: u32,
/// The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
/// the built-in ones of that activity; an empty list keeps its status factual.
#[serde(deserialize_with = "or_default")]
#[specta(type = BTreeMap<String, Vec<String>>)]
pub playful_words: BTreeMap<String, Vec<String>>,
#[serde(deserialize_with = "or_default")]
#[specta(type = ThinkingDisplay)]
pub thinking: ThinkingDisplay,
@@ -130,6 +142,9 @@ impl Default for AgentSettings {
fold_turns: true,
smooth_text: true,
fit_window_width: false,
playful_status: false,
playful_after_seconds: 0,
playful_words: BTreeMap::new(),
thinking: ThinkingDisplay::Auto,
tool_calls: ToolCallDisplay::Grouped,
expand_tool_output: false,
@@ -469,6 +484,7 @@ impl Default for Settings {
debugger: DebuggerSettings::default(),
run: RunSettings::default(),
terminal: TerminalSettings::default(),
external_diff: ExternalDiffSettings::default(),
actions_on_save: ActionsOnSaveSettings::default(),
external_tools: Vec::new(),
tools: BTreeMap::new(),
@@ -973,6 +989,7 @@ pub struct LanguagesSettings {
pub ruby: RubySettings,
pub markdown: MarkdownSettings,
pub arduino: ArduinoSettings,
pub zig: ZigSettings,
}
impl Default for LanguagesSettings {
@@ -995,6 +1012,7 @@ impl Default for LanguagesSettings {
ruby: RubySettings::default(),
markdown: MarkdownSettings::default(),
arduino: ArduinoSettings::default(),
zig: ZigSettings::default(),
}
}
}
@@ -1206,6 +1224,13 @@ impl Default for RustSettings {
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ZigSettings {
/// Directory holding the `zig` executable; empty = the one on `PATH`.
pub zig: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GoSettings {
+21
Переглянути файл
@@ -175,6 +175,24 @@ impl Default for VcsConfirmationSettings {
}
}
/// Tools › Diff & Merge › External Diff Tools: a program that shows two files' differences.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ExternalDiffSettings {
/// Offer Show Diff in External Tool in diff viewers.
pub enabled: bool,
/// The program to start.
pub path: String,
/// Its arguments: `%1` the left file, `%2` the right file, `%3` the diff's title.
pub parameters: String,
}
impl Default for ExternalDiffSettings {
fn default() -> Self {
Self { enabled: false, path: String::new(), parameters: "%1 %2 %3".into() }
}
}
/// Version Control › Shelf.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -327,6 +345,8 @@ pub struct RunSettings {
/// Ask before closing a Run tab whose process is still running.
pub confirm_terminate: bool,
pub show_on_start: bool,
/// New Run/Debug tabs start pinned: a later run doesn't take their place once finished.
pub pin_tabs: bool,
/// Grace period between interrupt and kill when stopping a process.
pub termination_timeout_ms: u32,
}
@@ -338,6 +358,7 @@ impl Default for RunSettings {
confirm_rerun: true,
confirm_terminate: true,
show_on_start: true,
pin_tabs: false,
termination_timeout_ms: 3000,
}
}
+38 -12
Переглянути файл
@@ -251,18 +251,12 @@ impl KotlinBridge {
}
}
other => {
let text = match other {
Ok(Ok(outcome)) => outcome
.messages
.iter()
.filter(|m| m.severity == Severity::Error)
.map(|m| m.text.as_str())
.collect::<Vec<_>>()
.join("\n"),
Ok(Err(error)) => error.message,
Err(error) => error.to_string(),
let (text, notify) = match other {
Ok(Ok(outcome)) => failed_build(&outcome),
Ok(Err(error)) => (error.message, true),
Err(error) => (error.to_string(), true),
};
self.failure(text, &mut diagnostics, &mut last_failure);
self.report(text, notify, &mut diagnostics, &mut last_failure);
remove_directory(directory).await;
}
}
@@ -276,6 +270,12 @@ impl KotlinBridge {
}
fn failure(&self, text: String, paths: &mut BTreeSet<PathBuf>, previous: &mut String) {
self.report(text, true, paths, previous);
}
/// Publishes a failed build in Problems (on `pom.xml`) and, when `notify`, as a
/// notification once per distinct message.
fn report(&self, text: String, notify: bool, paths: &mut BTreeSet<PathBuf>, previous: &mut String) {
let text = if text.is_empty() { "Kotlin compilation failed".to_owned() } else { text };
let text = format!("{text}\nJava temporarily uses the last successfully compiled Kotlin API.");
self.clear_diagnostics(paths);
@@ -295,7 +295,7 @@ impl KotlinBridge {
deprecated: false,
}],
});
if previous != &text {
if notify && previous != &text {
self.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Error,
title: "Kotlin editor compilation failed".into(),
@@ -306,6 +306,15 @@ impl KotlinBridge {
}
}
/// The error text of a failed bridge build, and whether to notify about it. Compiler errors
/// in the user's own Kotlin already show in its editor and stay in Problems; only a build
/// that failed without one (Maven itself, a missing plugin) is worth a notification.
fn failed_build(outcome: &Outcome) -> (String, bool) {
let errors: Vec<_> = outcome.messages.iter().filter(|m| m.severity == Severity::Error).collect();
let text = errors.iter().map(|m| m.text.as_str()).collect::<Vec<_>>().join("\n");
(text, !errors.iter().any(|m| m.path.is_some()))
}
fn relevant_change(root: &Path, path: &Path, settings: &ide_core::settings::Settings) -> bool {
let input = path.extension().is_some_and(|e| e == "kt")
|| path.file_name().is_some_and(|n| n == "pom.xml" || n == "mvnw" || n == "mvnw.cmd")
@@ -383,6 +392,23 @@ mod tests {
assert!(!relevant_change(dir.path(), &dir.path().join("module/src/build/pkg"), &Default::default()));
}
#[test]
fn source_errors_stay_out_of_notifications() {
let message = |text: &str, path: Option<&str>| ide_build::compile::BuildMessage {
severity: Severity::Error,
text: text.into(),
path: path.map(|p| PathBuf::from(p).into()),
range: None,
code: None,
};
let outcome = |messages| Outcome { projects: Vec::new(), messages, success: false };
let (text, notify) = failed_build(&outcome(vec![message("No value passed", Some("/p/src/A.kt"))]));
assert_eq!((text.as_str(), notify), ("No value passed", false));
let (text, notify) = failed_build(&outcome(vec![message("Plugin not found", None)]));
assert_eq!((text.as_str(), notify), ("Plugin not found", true));
assert!(failed_build(&outcome(Vec::new())).1);
}
#[test]
fn extensionless_root_file_does_not_trigger() {
let dir = tempfile::tempdir().unwrap();
+3 -1
Переглянути файл
@@ -1275,7 +1275,9 @@ impl Project {
}
let defaults = self.documents.file_defaults();
let fallback = defaults.fallback_for(path);
if path.exists() {
// The working file only when it is a regular file: a path that is a directory there
// (a committed symlink to a folder, a file replaced by a folder) has only its blob.
if path.is_file() {
let loaded = ide_vfs::load_text_with_fallback(path, fallback)?;
return encoding_rs::Encoding::for_label(loaded.encoding.as_bytes())
.ok_or_else(|| ide_core::IdeError::invalid("unknown file encoding"));
+2
Переглянути файл
@@ -310,6 +310,8 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
| "fs_delete"
| "fs_entry_kind"
| "fs_open_with_system"
// The user's own diff program (global settings) on the diff's two sides.
| "diff_external_tool"
| "fs_probe"
| "fs_read_dir"
| "fs_read_image"
+46
Переглянути файл
@@ -111,3 +111,49 @@ async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
assert_eq!(vcs::vcs_file_at(&host, "main", utf8, None).await.unwrap().as_deref(), Some(old));
host.close_project("main");
}
/// A committed symlink to a folder (#3528): its revision is the link target, even though the
/// working path is a directory.
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_directory_symlink_revision_is_its_target() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(root.join("target")).unwrap();
git(&root, &["init", "-b", "main"]);
git(&root, &["config", "user.name", "Test"]);
git(&root, &["config", "user.email", "[email protected]"]);
git(&root, &["config", "commit.gpgsign", "false"]);
std::fs::write(root.join("target/file.txt"), "example\n").unwrap();
std::os::unix::fs::symlink("target", root.join("dir-link")).unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-m", "Add a directory symlink"]);
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();
let project = host.open_project("main", &root).unwrap();
for _ in 0..500 {
if !project.repos().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let link = root.join("dir-link");
assert!(link.is_dir());
assert_eq!(
vcs::vcs_file_at(&host, "main", link.clone(), Some("HEAD".into())).await.unwrap().as_deref(),
Some("target")
);
assert_eq!(vcs::vcs_file_mode(&host, "main", link, Some("HEAD".into())).await.unwrap().as_deref(), Some("120000"));
host.close_project("main");
}
+1
Переглянути файл
@@ -16,6 +16,7 @@ toml.workspace = true
tree-sitter.workspace = true
parking_lot.workspace = true
tracing.workspace = true
memchr = "2"
regex-lite = "0.1"
blake3.workspace = true
tree-sitter-language = "0.1"
+5
Переглянути файл
@@ -170,6 +170,11 @@ pub struct LanguageServerConfig {
/// basedpyright): only used while none of those is installed.
#[serde(default)]
pub fallback: bool,
/// Names of servers listed after this one that it makes redundant (a PHP server
/// with its own Laravel support replaces `laravel-lsp`): they aren't used while
/// this one serves the file.
#[serde(default)]
pub replaces: Vec<String>,
/// What the server is used for (`completion`, `code-action`, `diagnostics`,
/// … `FEATURES` in `ide-lsp/src/caps.rs`); empty means everything. The other
/// capabilities it announces are ignored, so a refactoring-only server next
+4 -1
Переглянути файл
@@ -758,7 +758,10 @@ mod tests {
let cfg = reg.get(&LanguageId::new("php")).unwrap();
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
// After the fallback: hover, rename and symbols stay with Intelephense.
assert_eq!(names, ["intelephense", "phpactor", "laravel-lsp"]);
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "laravel-lsp"]);
// Phoxite answers the Laravel strings itself.
let phoxite = cfg.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
assert!(phoxite.fallback && phoxite.replaces == ["laravel-lsp"]);
let lsp = cfg.language_servers.iter().find(|s| s.name == "laravel-lsp").unwrap();
assert_eq!(lsp.command.as_str(), "laravel-lsp");
// Its `lsp` command takes no options and speaks over stdio; `--stdio` stops it at startup.
+7 -2
Переглянути файл
@@ -79,11 +79,16 @@ impl<'a> LineIndex<'a> {
}
fn memchr_newlines(bytes: &[u8]) -> impl Iterator<Item = usize> + '_ {
bytes.iter().enumerate().filter(|&(_, &b)| b == b'\n').map(|(i, _)| i + 1)
memchr::memchr_iter(b'\n', bytes).map(|i| i + 1)
}
pub(crate) fn utf16_len(s: &str) -> u32 {
if s.is_ascii() { s.len() as u32 } else { s.chars().map(|c| c.len_utf16() as u32).sum() }
if s.is_ascii() {
return s.len() as u32;
}
// One unit per char (each starts with a non-continuation byte), two for
// 4-byte chars; byte classification vectorizes, unlike decoding `chars()`.
s.as_bytes().iter().map(|&b| u32::from((b & 0xC0) != 0x80) + u32::from(b >= 0xF0)).sum()
}
/// Byte offset of `pos` (line, UTF-16 column) in `text`; None past the last line.
+22 -8
Переглянути файл
@@ -660,15 +660,17 @@ impl LspManager {
/// The servers serving `path`: every regular one, and each `fallback` one
/// only while all servers listed before it have given up (missing, not
/// launchable, or crashed for good). One that requires a root marker serves
/// only files below one, and stands in for no other.
/// only files below one, and stands in for no other. One that a server before
/// it `replaces` is left out while that server serves the file.
fn servers_for(&self, language: &LanguageId, path: &Path) -> Vec<Arc<Server>> {
if let Some(servers) = self.arduino_servers(language, path) {
return servers;
}
let mut out = Vec::new();
let mut available_before = false;
let mut replaced: Vec<String> = Vec::new();
for sc in &self.language_servers(language) {
if sc.fallback && available_before {
if (sc.fallback && available_before) || replaced.contains(&sc.name) {
continue;
}
if sc.require_root_marker
@@ -678,6 +680,9 @@ impl LspManager {
}
let server = self.server_for(sc, language, path);
available_before |= !sc.require_root_marker && !server.gave_up();
if !server.gave_up() {
replaced.extend(sc.replaces.iter().cloned());
}
out.push(server);
}
out
@@ -865,7 +870,7 @@ impl LspManager {
ide_core::event::ServerStatus::Missing,
Some(message),
) {
self.attach_fallbacks();
self.fallbacks_take_over().await;
}
return;
}
@@ -878,7 +883,7 @@ impl LspManager {
ide_core::event::ServerStatus::Misconfigured,
Some(message),
) {
self.attach_fallbacks();
self.fallbacks_take_over().await;
}
return;
}
@@ -891,7 +896,7 @@ impl LspManager {
ide_core::event::ServerStatus::Crashed,
Some(message),
) {
self.attach_fallbacks();
self.fallbacks_take_over().await;
}
return;
}
@@ -1039,7 +1044,7 @@ impl LspManager {
}
}
// Gave up (crashed repeatedly, or its build expired): the fallbacks it hid take over.
None => self.attach_fallbacks(),
None => self.fallbacks_take_over().await,
}
}
@@ -3828,8 +3833,16 @@ impl LspManager {
}
}
/// A server enabled again shadows the fallbacks attached in its place: they
/// leave the open documents, and stop once no document uses them.
/// A server gave up: its fallbacks take over the open documents, and the servers
/// they replace leave.
async fn fallbacks_take_over(&self) {
self.attach_fallbacks();
self.detach_shadowed_fallbacks().await;
}
/// A server enabled again shadows the fallbacks attached in its place, and a
/// fallback that took over may replace a server attached earlier: they leave the
/// open documents, and stop once no document uses them.
async fn detach_shadowed_fallbacks(&self) {
let open: Vec<(DocId, LanguageId, PathBuf)> =
self.docs.lock().iter().map(|(id, d)| (*id, d.language.clone(), d.path.clone())).collect();
@@ -3845,6 +3858,7 @@ impl LspManager {
.filter(|a| {
!wanted.iter().any(|w| w.id == a.server.id)
&& (configs.iter().any(|c| c.fallback && c.name == a.server.name)
|| configs.iter().any(|c| c.replaces.contains(&a.server.name))
|| (a.server.name == "clangd" && wanted.iter().any(|s| s.name == arduino::SERVER)))
})
.map(|a| a.server.id)
+62
Переглянути файл
@@ -264,6 +264,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
install_hint: Some(format!("install {name}")),
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
@@ -3286,6 +3287,67 @@ async fn a_server_requiring_a_root_marker_serves_only_files_below_one() {
h.wait_status("alt", ServerStatus::Ready).await;
}
/// A server that `replaces` another (a PHP server with its own Laravel support and
/// `laravel-lsp`) keeps it away while it serves, and only then.
#[tokio::test(flavor = "multi_thread")]
async fn a_replaced_server_stays_away_while_its_replacement_serves() {
let servers = [("main", incremental_caps()), ("alt", incremental_caps()), ("framework", incremental_caps())];
let configure = |cfg: &mut LanguageServerConfig| match cfg.name.as_str() {
"alt" => {
cfg.fallback = true;
cfg.replaces = vec!["framework".into()];
}
"framework" => cfg.require_root_marker = true,
_ => {}
};
let h = harness_configured("mock", "mk", &servers, configure);
let disabled: Arc<Mutex<Vec<String>>> = Default::default();
{
let disabled = disabled.clone();
h.mgr.set_servers_hook(Box::new(move |_, defined| {
defined.iter().filter(|c| !disabled.lock().contains(&c.name)).cloned().collect()
}));
}
std::fs::write(h.root.join("mock.toml"), "").unwrap();
let (_, path) = h.open("a.mk", "x");
let uri = uri_of(&path);
// The preferred server serves: the framework's server joins it, the alternative stays away.
h.wait_status("main", ServerStatus::Ready).await;
h.wait_status("framework", ServerStatus::Ready).await;
eventually(|| h.launcher.state("framework").docs.lock().contains_key(&uri)).await;
assert!(h.statuses("alt").is_empty());
// The alternative takes over: the server it replaces closes the document and stops.
disabled.lock().push("main".into());
h.mgr.reconfigure().await;
h.wait_status("alt", ServerStatus::Ready).await;
eventually(|| h.launcher.state("alt").docs.lock().contains_key(&uri)).await;
assert!(!h.launcher.state("framework").notified("textDocument/didClose").is_empty());
assert_eq!(h.statuses("framework").last(), Some(&ServerStatus::Stopped));
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["alt"]);
// The preferred server again: the framework's server comes back with it.
disabled.lock().clear();
h.mgr.reconfigure().await;
h.wait_status("main", ServerStatus::Ready).await;
eventually(|| h.statuses("framework").last() == Some(&ServerStatus::Ready)).await;
assert_eq!(h.statuses("alt").last(), Some(&ServerStatus::Stopped));
// A preferred server that is not installed: the alternative replaces the framework's
// server although that one attached first.
let servers = [("ghost", json!({})), ("alt", incremental_caps()), ("framework", incremental_caps())];
let h = harness_configured("mock", "mk", &servers, configure);
h.launcher.state("ghost").missing.store(true, Ordering::SeqCst);
std::fs::write(h.root.join("mock.toml"), "").unwrap();
let (_, path) = h.open("a.mk", "x");
let uri = uri_of(&path);
h.wait_status("ghost", ServerStatus::Missing).await;
h.wait_status("alt", ServerStatus::Ready).await;
eventually(|| h.launcher.state("alt").docs.lock().contains_key(&uri)).await;
eventually(|| !h.mgr.servers().iter().any(|s| s.name == "framework")).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_fallback_leaves_when_the_preferred_server_is_enabled_again() {
let h = harness_with_fallbacks(&[("main", incremental_caps()), ("alt", incremental_caps())], &["alt"]);
+3
Переглянути файл
@@ -419,6 +419,7 @@ async fn missing_binary_is_reported_with_install_hint() {
install_hint: Some("npm i -g nope-ls".into()),
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
@@ -692,6 +693,7 @@ async fn typescript_language_server_end_to_end() {
install_hint: None,
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
@@ -745,6 +747,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
install_hint: None,
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
+4
Переглянути файл
@@ -21,3 +21,7 @@ toml.workspace = true
tracing.workspace = true
url = "2"
zip.workspace = true
[dev-dependencies]
flate2.workspace = true
tar.workspace = true
+7
Переглянути файл
@@ -141,6 +141,12 @@ pub(crate) fn goroot(root: &Path, s: &Settings) -> Option<PathBuf> {
.or_else(|| pinned::pinned_install(root, Tool::Go).and_then(|(dir, _)| pinned::goroot_in_install(&dir)))
}
/// The directory of the configured Zig install (holding `zig`), else `None` for `PATH`.
pub(crate) fn zig_bin(root: &Path, s: &Settings) -> Option<PathBuf> {
setting_path(root, &s.languages.zig.zig)
.map(|p| if p.is_file() { p.parent().map(Path::to_path_buf).unwrap_or(p) } else { p })
}
/// Runtime choices for package-manager based IDE tool installs.
#[derive(Default)]
pub struct ToolInstallEnvironment {
@@ -1300,6 +1306,7 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
}),
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
+1
Переглянути файл
@@ -26,6 +26,7 @@ pub mod pinned;
pub mod python;
pub mod ruby;
mod vue;
mod zig;
use serde::{Deserialize, Serialize};
use specta::Type;
+206 -3
Переглянути файл
@@ -2,7 +2,8 @@
//! Project view): the folders holding the sources of the project's SDKs and
//! dependencies — the Python interpreter's standard library and site-packages,
//! the JDK, `node_modules` packages, Cargo crates and the Rust standard
//! library, GOROOT and the Go module cache.
//! library, GOROOT and the Go module cache, the Zig standard library and the
//! fetched packages of `build.zig.zon`.
//!
//! Ecosystems are detected in the project and its modules. SDK and graph probes
//! are cached until manifests or settings change; Node packages are read on refresh.
@@ -28,7 +29,7 @@ use std::time::{Duration, SystemTime};
pub struct LibraryGroup {
/// Display name, e.g. `Python 3.12 (.venv)`.
pub name: String,
/// `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath`.
/// `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath` | `zig` | `zigPackages`.
pub kind: String,
pub roots: Vec<LibraryRoot>,
}
@@ -56,6 +57,7 @@ const JAVA_MANIFESTS: &[&str] =
const CARGO_MANIFESTS: &[&str] = &["Cargo.toml", "Cargo.lock", "rust-toolchain", "rust-toolchain.toml"];
const GO_MANIFESTS: &[&str] = &["go.mod", "go.sum", "go.work"];
const RUBY_MANIFESTS: &[&str] = &["Gemfile", "Gemfile.lock", ".ruby-version", ".tool-versions", "mise.toml"];
const ZIG_MANIFESTS: &[&str] = &["build.zig.zon", "build.zig"];
/// A Maven / Gradle dependency of the project, from the build model.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -83,7 +85,7 @@ pub fn project_libraries_stream(
on_groups: &(dyn Fn(Vec<LibraryGroup>) + Sync),
) -> Vec<LibraryGroup> {
type Detect = fn(&Path, &Settings, &CancellationToken) -> Vec<LibraryGroup>;
let detectors: [Detect; 5] = [python_groups, jdk_groups, node_groups, go_groups, ruby_groups];
let detectors: [Detect; 6] = [python_groups, jdk_groups, node_groups, go_groups, ruby_groups, zig_groups];
let roots = library_project_roots(root, cancel);
let settings = module_settings(root, settings);
std::thread::scope(|s| {
@@ -193,6 +195,8 @@ fn library_project_roots(root: &Path, cancel: &CancellationToken) -> Vec<PathBuf
"setup.py",
"requirements.txt",
".python-version",
"build.zig",
"build.zig.zon",
".tool-versions",
"mise.toml",
]
@@ -252,6 +256,7 @@ fn module_settings(root: &Path, settings: &Settings) -> Settings {
&mut l.rust.stdlib,
&mut l.go.goroot,
&mut l.go.gopath,
&mut l.zig.zig,
&mut l.java.jdk,
] {
// `target:<id>` names a run target, not a path.
@@ -998,6 +1003,80 @@ pub(crate) fn parse_go_modules(text: &str) -> Vec<(String, PathBuf)> {
.collect()
}
// ------------------------------------------------------------------ zig
fn zig_groups(root: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
let Some(files) = manifests(root, ZIG_MANIFESTS) else { return Vec::new() };
let Some(zig) = tool(crate::apply::zig_bin(root, s), "zig") else { return Vec::new() };
cached_cancellable(root, "zig", zig.display().to_string(), &files, cancel, || {
let Some(env) = query_in_cancellable(&zig, &["env"], root, &[], QUERY_TIMEOUT, cancel)
.as_deref()
.and_then(crate::zig::parse_zig_env)
else {
return Vec::new();
};
let mut out = Vec::new();
let version =
env.version.clone().or_else(|| query_in_cancellable(&zig, &["version"], root, &[], QUERY_TIMEOUT, cancel));
let name = match version.as_deref().map(str::trim) {
Some(v) if !v.is_empty() => format!("Zig {v}"),
_ => "Zig".into(),
};
out.extend(env.std_sources().and_then(|std| group(name, "zig", library_roots(vec![std]))));
if let Some(cache) = env.global_cache_dir.as_deref() {
let zon = std::fs::read_to_string(root.join("build.zig.zon")).unwrap_or_default();
let deps = crate::zig::zon_dependencies(&zon);
out.extend(group("Zig packages", "zigPackages", zig_package_roots(cache, &deps)));
}
out
})
}
/// The fetched sources of a `build.zig.zon`'s dependencies: `p/<hash>` folders
/// (Zig ≤ 0.14 unpacks them) or the package root inside `p/<hash>.tar.gz` (Zig
/// ≥ 0.15 keeps packages as blobs, browsed through the archive VFS). Path
/// dependencies stay in the project tree; unfetched packages are simply absent —
/// listing libraries never downloads.
fn zig_package_roots(cache: &Path, deps: &[crate::zig::ZonDependency]) -> Vec<LibraryRoot> {
let mut seen = std::collections::HashSet::new();
deps.iter()
.filter_map(|d| {
let hash = d.hash.as_deref()?;
let dir = cache.join("p").join(hash);
if dir.is_dir() {
let zon = std::fs::read_to_string(dir.join("build.zig.zon")).unwrap_or_default();
let name =
match (crate::zig::zon_string_field(&zon, "name"), crate::zig::zon_string_field(&zon, "version")) {
(Some(name), Some(version)) => format!("{name} {version}"),
(Some(name), None) => name,
_ => hash.to_owned(),
};
return Some((name, dir));
}
let blob = cache.join("p").join(format!("{hash}.tar.gz"));
blob.is_file().then_some(hash).map(|hash| {
// The blob's only top-level folder is the package (`<hash>/`); fall back to
// the archive root should that layout ever change.
let entry = if ide_vfs::read_archive_dir(&blob, hash).is_ok() { hash } else { "" };
(package_label(d, hash), ide_vfs::archive_entry_path(&blob, entry))
})
})
.filter(|(_, path)| seen.insert(path.to_string_lossy().into_owned()))
.map(|(name, path)| LibraryRoot { name, path: path.into() })
.collect()
}
/// `probe_pkg 0.1.0` from a Zig ≥ 0.15 package hash (`name-version-<hash>`).
fn package_label(dep: &crate::zig::ZonDependency, hash: &str) -> String {
let Some((rest, _)) = hash.rsplit_once('-') else { return dep.name.clone() };
let mut parts: Vec<&str> = rest.split('-').collect();
let version = parts.pop().unwrap_or_default();
match parts.is_empty() || !version.starts_with(|c: char| c.is_ascii_digit()) || !version.contains('.') {
true => dep.name.clone(),
false => format!("{} {version}", parts.join("-")),
}
}
#[cfg(test)]
mod go_cache_tests {
use super::*;
@@ -1387,3 +1466,127 @@ mod idea_project_tests {
assert!(idea_java_project(root));
}
}
#[cfg(test)]
mod zig_tests {
use super::*;
use crate::zig::ZonDependency;
/// Writes a Zig package blob (`p/<hash>.tar.gz`) with a `<hash>/` root folder.
fn write_package_blob(cache: &Path, hash: &str, files: &[(&str, &str)]) {
use flate2::write::GzEncoder;
let blob = cache.join("p").join(format!("{hash}.tar.gz"));
std::fs::create_dir_all(blob.parent().unwrap()).unwrap();
let enc = GzEncoder::new(std::fs::File::create(blob).unwrap(), flate2::Compression::default());
let mut tar = tar::Builder::new(enc);
for (name, text) in files {
let mut header = tar::Header::new_gnu();
header.set_size(text.len() as u64);
header.set_mode(0o644);
header.set_cksum();
tar.append_data(&mut header, name, text.as_bytes()).unwrap();
}
tar.into_inner().unwrap().finish().unwrap();
}
#[test]
fn zig_packages_come_from_the_global_cache_without_fetching() {
let tmp = tempfile::tempdir().unwrap();
let cache = tmp.path();
let (hash, old) = ("zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8", "1220b7c0");
write_package_blob(cache, hash, &[(&format!("{hash}/src/lib.zig"), "pub fn hello() {}\n")]);
let unpacked = cache.join("p").join(old);
std::fs::create_dir_all(&unpacked).unwrap();
std::fs::write(unpacked.join("build.zig.zon"), r#".{ .name = .old_pkg, .version = "0.2.0" }"#).unwrap();
let deps = [
ZonDependency { name: "zap".into(), hash: Some(hash.into()), path: None, lazy: false },
ZonDependency { name: "shared".into(), hash: None, path: Some("../shared".into()), lazy: false },
ZonDependency { name: "gone".into(), hash: Some("gone-1.0.0-BBBBBBBBBB".into()), path: None, lazy: true },
ZonDependency { name: "old".into(), hash: Some(old.into()), path: None, lazy: false },
];
let roots = zig_package_roots(cache, &deps);
let summary: Vec<(String, String)> =
roots.iter().map(|r| (r.name.clone(), r.path.to_string_lossy().into_owned())).collect();
let blob = cache.join("p").join(format!("{hash}.tar.gz"));
assert_eq!(
summary,
[
("zap 0.1.0".into(), format!("{}!/{hash}", blob.display())),
("old_pkg 0.2.0".into(), unpacked.to_string_lossy().into_owned())
]
);
}
#[test]
fn zig_package_labels_parse_from_the_hash() {
let dep = |name: &str| ZonDependency { name: name.into(), hash: None, path: None, lazy: false };
assert_eq!(package_label(&dep("zap"), "zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8"), "zap 0.1.0");
assert_eq!(
package_label(&dep("diffz"), "diffz-0.0.1-G2tlISvOAQDORzPTSxDgiKwlHuADKeJMdJrw4kRfLufj"),
"diffz 0.0.1"
);
assert_eq!(
package_label(&dep("zig-anytype"), "zig-anytype-0.1.0-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
"zig-anytype 0.1.0"
);
assert_eq!(package_label(&dep("old"), "1220b7c0"), "old");
}
#[cfg(unix)]
#[test]
fn zig_libraries_list_the_stdlib_and_fetched_packages() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let stdlib = root.join("stdlib");
std::fs::create_dir_all(&stdlib).unwrap();
std::fs::write(root.join("build.zig"), "").unwrap();
let hash = "zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8";
let cache = root.join("zig-cache");
write_package_blob(&cache, hash, &[(&format!("{hash}/src/lib.zig"), "pub fn hello() {}\n")]);
std::fs::write(
root.join("build.zig.zon"),
r#".{
.name = .app,
.dependencies = .{
// the package cache holds this one
.zap = .{ .url = "https://example.com/zap.tar.gz", .hash = "zap-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8" },
.local = .{ .path = "../shared" },
.gone = .{ .url = "https://example.com/gone.tar.gz", .hash = "gone-1.0.0-BBBBBBBBBB" },
},
}
"#,
)
.unwrap();
let bin = root.join("tools");
std::fs::create_dir(&bin).unwrap();
let zig = bin.join("zig");
std::fs::write(
&zig,
format!(
"#!/bin/sh\ncase \"$1\" in\n env) printf '%s\\n' '.{{\n .zig_exe = \"{}\",\n .std_dir = \"{}\",\n .global_cache_dir = \"{}\",\n .version = \"0.16.0\",\n}}' ;;\n version) echo 0.16.0 ;;\nesac\n",
zig.display(),
stdlib.display(),
cache.display(),
),
)
.unwrap();
std::fs::set_permissions(&zig, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut settings = Settings::default();
settings.languages.zig.zig = "tools".into();
let groups = zig_groups(root, &settings, &CancellationToken::new());
let summary: Vec<(&str, &str, Vec<&str>)> = groups
.iter()
.map(|g| (g.name.as_str(), g.kind.as_str(), g.roots.iter().map(|r| r.name.as_str()).collect()))
.collect();
assert_eq!(
summary,
[("Zig 0.16.0", "zig", vec!["stdlib"]), ("Zig packages", "zigPackages", vec!["zap 0.1.0"])]
);
let packages = groups.iter().find(|g| g.kind == "zigPackages").unwrap();
assert_eq!(
packages.roots[0].path.to_string_lossy(),
format!("{}!/{hash}", cache.join("p").join(format!("{hash}.tar.gz")).display())
);
}
}
+80
Переглянути файл
@@ -35,6 +35,7 @@ pub(crate) fn server(name: &str) -> LanguageServerConfig {
install_hint: None,
connect: None,
fallback: false,
replaces: Vec::new(),
features: Vec::new(),
code_action_kinds: Vec::new(),
max_java: None,
@@ -1589,6 +1590,85 @@ fn go_modules_skip_the_main_module_and_missing_downloads() {
);
}
#[test]
fn build_zig_zon_dependencies_are_parsed() {
let zon = r#"// the manifest is a Zig struct literal
.{
.name = .app,
.version = "0.1.0",
.fingerprint = 0x348e9ddfb4b9e03c,
.dependencies = .{
.zap = .{ .url = "https://example.com/zap.tar.gz", .hash = "zap-0.1.0-AAA" },
.@"weird name" = .{
.url = "https://example.com/w.tar.gz",
.hash = "weird-2.0.0-BBB",
.lazy = true,
},
.shared = .{ .path = "../shared" },
},
.paths = .{ "build.zig", "src" },
}
"#;
assert_eq!(
crate::zig::zon_dependencies(zon),
[
crate::zig::ZonDependency {
name: "zap".into(),
hash: Some("zap-0.1.0-AAA".into()),
path: None,
lazy: false
},
crate::zig::ZonDependency {
name: "weird name".into(),
hash: Some("weird-2.0.0-BBB".into()),
path: None,
lazy: true
},
crate::zig::ZonDependency {
name: "shared".into(),
hash: None,
path: Some("../shared".into()),
lazy: false
},
]
);
assert!(crate::zig::zon_dependencies(".{ .name = .app, .dependencies = .{} }").is_empty());
assert!(crate::zig::zon_dependencies(".{ .name = .app }").is_empty());
assert!(crate::zig::zon_dependencies("{ broken").is_empty());
assert_eq!(
crate::zig::zon_string_field(".{ .name = .probe_pkg, .version = \"0.1.0\" }", "name").as_deref(),
Some("probe_pkg")
);
}
#[test]
fn zig_env_is_parsed_from_json_and_struct_literals() {
let env = crate::zig::parse_zig_env(
r#"{"zig_exe":"/opt/zig/zig","lib_dir":"/opt/zig/lib","std_dir":"/opt/zig/lib/std","global_cache_dir":"/home/u/.cache/zig","version":"0.14.1"}"#,
)
.unwrap();
assert_eq!(env.std_sources().as_deref(), Some(std::path::Path::new("/opt/zig/lib/std")));
assert_eq!(env.global_cache_dir.as_deref(), Some(std::path::Path::new("/home/u/.cache/zig")));
// Zig ≥ 0.15 prints a struct literal; a relative std_dir resolves against the install dir.
let env = crate::zig::parse_zig_env(
r#".{
.zig_exe = "/opt/zig/zig",
.lib_dir = "/opt/zig/lib",
.std_dir = "lib/std",
.global_cache_dir = "/home/u/.cache/zig",
.version = "0.16.0",
.target = "aarch64-macos",
.env = .{ .ZIG_GLOBAL_CACHE_DIR = null, .HOME = "/home/u" },
}"#,
)
.unwrap();
assert_eq!(env.std_sources().as_deref(), Some(std::path::Path::new("/opt/zig/lib/std")));
assert_eq!(env.version.as_deref(), Some("0.16.0"));
assert_eq!(env.global_cache_dir.as_deref(), Some(std::path::Path::new("/home/u/.cache/zig")));
assert!(crate::zig::parse_zig_env("error: nothing").is_none());
}
#[test]
fn jdk_library_is_the_jdk_home() {
let tmp = tempfile::tempdir().unwrap();
+261
Переглянути файл
@@ -0,0 +1,261 @@
//! Reading Zig's own text formats for External Libraries, without running Zig:
//! the package manifest (`build.zig.zon`) and the `zig env` output. Both are
//! Zig struct literals; `zig env` printed JSON before Zig 0.15.
use serde::Deserialize;
use std::path::{Path, PathBuf};
/// One `.dependencies` entry of a `build.zig.zon`.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ZonDependency {
pub name: String,
/// Package hash: its sources are fetched into the global cache as `p/<hash>`
/// (Zig ≤ 0.14 unpacks them, Zig ≥ 0.15 keeps `p/<hash>.tar.gz` blobs).
pub hash: Option<String>,
/// A path dependency, part of the project tree rather than the package cache.
pub path: Option<String>,
/// Fetched only when the build actually references it.
pub lazy: bool,
}
/// The `.dependencies` entries of a `build.zig.zon`, in order. Tolerant of
/// partially edited files: whatever does not parse is skipped.
pub(crate) fn zon_dependencies(zon: &str) -> Vec<ZonDependency> {
let src = code_only(zon);
let Some(top) = struct_body(&src) else { return Vec::new() };
let Some((_, value)) = fields(top).into_iter().find(|(name, _)| *name == "dependencies") else {
return Vec::new();
};
let Some(deps) = struct_body(value) else { return Vec::new() };
fields(deps)
.into_iter()
.map(|(name, value)| {
let entry = struct_body(value).map(|body| fields(body)).unwrap_or_default();
ZonDependency {
name: name.to_owned(),
hash: field(&entry, "hash"),
path: field(&entry, "path"),
lazy: entry.iter().any(|(n, v)| *n == "lazy" && v.trim() == "true"),
}
})
.collect()
}
/// A top-level string (or enum-literal, `.name`) field of a Zig struct literal.
pub(crate) fn zon_string_field(text: &str, name: &str) -> Option<String> {
let src = code_only(text);
let top = struct_body(&src)?;
field(&fields(top), name)
}
/// What `zig env` reports that External Libraries needs.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct ZigEnv {
pub zig_exe: Option<PathBuf>,
pub lib_dir: Option<PathBuf>,
pub std_dir: Option<PathBuf>,
pub global_cache_dir: Option<PathBuf>,
pub version: Option<String>,
}
impl ZigEnv {
/// The standard library sources: `std_dir`, else `lib_dir/std`. A relative
/// path resolves against the zig install dir (stage builds print relative paths).
pub(crate) fn std_sources(&self) -> Option<PathBuf> {
let resolve = |p: &Path| match (p.is_relative(), self.zig_exe.as_ref().and_then(|e| e.parent())) {
(true, Some(install)) => install.join(p),
_ => p.to_path_buf(),
};
self.std_dir
.as_deref()
.map(Path::new)
.map(resolve)
.or_else(|| self.lib_dir.as_deref().map(Path::new).map(|dir| resolve(dir).join("std")))
}
}
/// The `zig env` output: JSON (older Zig) or a struct literal (Zig ≥ 0.15).
pub(crate) fn parse_zig_env(out: &str) -> Option<ZigEnv> {
#[derive(Deserialize)]
struct Json {
zig_exe: Option<PathBuf>,
lib_dir: Option<PathBuf>,
std_dir: Option<PathBuf>,
global_cache_dir: Option<PathBuf>,
version: Option<String>,
}
if let Ok(json) = serde_json::from_str::<Json>(out.trim()) {
return Some(ZigEnv {
zig_exe: json.zig_exe,
lib_dir: json.lib_dir,
std_dir: json.std_dir,
global_cache_dir: json.global_cache_dir,
version: json.version,
});
}
let src = code_only(out);
let top = struct_body(&src)?;
let f = fields(top);
Some(ZigEnv {
zig_exe: field(&f, "zig_exe").map(PathBuf::from),
lib_dir: field(&f, "lib_dir").map(PathBuf::from),
std_dir: field(&f, "std_dir").map(PathBuf::from),
global_cache_dir: field(&f, "global_cache_dir").map(PathBuf::from),
version: field(&f, "version"),
})
}
/// The string (or enum-literal, `.foo`) value of a field of a struct body.
fn field<'a>(entry: &[(&'a str, &'a str)], name: &str) -> Option<String> {
let value = entry.iter().find(|(n, _)| *n == name)?.1;
if let Some(string) = string_value(value) {
return Some(string);
}
value
.strip_prefix('.')
.filter(|v| v.chars().next().is_some_and(|c| c.is_ascii_alphanumeric() || c == '_'))
.map(str::to_owned)
}
/// The contents of the string literal starting at `value`, `\"` unescaped.
fn string_value(value: &str) -> Option<String> {
let rest = value.trim_start().strip_prefix('"')?;
let mut out = String::new();
let mut chars = rest.chars();
while let Some(c) = chars.next() {
match c {
'"' => return Some(out),
'\\' => out.push(chars.next()?),
c => out.push(c),
}
}
None
}
/// `src` with comments blanked out and string contents kept.
fn code_only(src: &str) -> String {
let mut out = String::with_capacity(src.len());
for line in src.lines() {
let bytes = line.as_bytes();
let mut in_string = false;
let mut escaped = false;
let mut end = line.len();
for (i, &b) in bytes.iter().enumerate() {
if in_string {
match b {
_ if escaped => escaped = false,
b'\\' => escaped = true,
b'"' => in_string = false,
_ => {}
}
} else if b == b'"' {
in_string = true;
} else if b == b'/' && bytes.get(i + 1) == Some(&b'/') {
end = i;
break;
}
}
out.push_str(&line[..end]);
out.push('\n');
}
out
}
/// The inside of the first `{ … }` of `text`, strings respected.
fn struct_body(text: &str) -> Option<&str> {
let bytes = text.as_bytes();
let mut start = 0;
while start < bytes.len() {
match bytes[start] {
b'"' => start = skip_string(text, start),
b'{' => break,
_ => start += 1,
}
}
let mut depth = 0;
let mut i = start;
while i < bytes.len() {
match bytes[i] {
b'"' => i = skip_string(text, i),
b'{' => {
depth += 1;
i += 1;
}
b'}' => {
if depth == 1 {
return Some(&text[start + 1..i]);
}
depth -= 1;
i += 1;
}
_ => i += 1,
}
}
None
}
/// The index just past the string literal starting at `i` (an opening `"`).
fn skip_string(text: &str, i: usize) -> usize {
let bytes = text.as_bytes();
let mut i = i + 1;
while i < bytes.len() {
match bytes[i] {
b'\\' => i += 2,
b'"' => return i + 1,
_ => i += 1,
}
}
i
}
/// The `.name = value` fields of a struct literal body, in order: `name` is the
/// identifier (or `@"…"` unquoted), `value` trimmed and may itself be `.{ … }`.
fn fields(body: &str) -> Vec<(&str, &str)> {
let bytes = body.as_bytes();
let mut out = Vec::new();
let mut depth = 0;
let mut field: Option<usize> = None;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'"' => i = skip_string(body, i),
b'{' | b'[' | b'(' => {
depth += 1;
i += 1;
}
b'}' | b']' | b')' => {
if depth == 0 {
break;
}
depth -= 1;
i += 1;
}
b',' if depth == 0 => {
if let Some(start) = field.take() {
push_field(&mut out, body, start, i);
}
i += 1;
}
b'.' if depth == 0 && field.is_none() => {
if bytes.get(i + 1).is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b'@') {
field = Some(i + 1);
}
i += 1;
}
_ => i += 1,
}
}
if let Some(start) = field {
push_field(&mut out, body, start, bytes.len());
}
out
}
fn push_field<'a>(out: &mut Vec<(&'a str, &'a str)>, body: &'a str, start: usize, end: usize) {
let text = &body[start..end];
let Some(eq) = text.find('=') else { return };
let name = text[..eq].trim().trim_start_matches('@').trim_matches('"');
if !name.is_empty() {
out.push((name, text[eq + 1..].trim()));
}
}
+6 -1
Переглянути файл
@@ -56,7 +56,12 @@ impl<'a> Lines<'a> {
}
pub(crate) fn utf16_len(s: &str) -> u32 {
if s.is_ascii() { s.len() as u32 } else { s.chars().map(|c| c.len_utf16() as u32).sum() }
if s.is_ascii() {
return s.len() as u32;
}
// One unit per char (each starts with a non-continuation byte), two for
// 4-byte chars; byte classification vectorizes, unlike decoding `chars()`.
s.as_bytes().iter().map(|&b| u32::from((b & 0xC0) != 0x80) + u32::from(b >= 0xF0)).sum()
}
fn utf16_to_byte(s: &str, offset: usize) -> usize {
+30 -9
Переглянути файл
@@ -39,6 +39,10 @@ impl LineEnding {
/// The dominant line ending of `text`; ties and text without any line
/// break resolve to [`LineEnding::Lf`].
pub fn detect(text: &str) -> Self {
// Without `\r` both other counts are zero and `Lf` wins outright.
if !text.contains('\r') {
return Self::Lf;
}
let (mut lf, mut crlf, mut cr) = (0usize, 0usize, 0usize);
let bytes = text.as_bytes();
let mut i = 0;
@@ -72,13 +76,20 @@ const DIFF_BUDGET: Duration = Duration::from_millis(50);
type LineRange = std::ops::Range<usize>;
/// Byte lengths of the common prefix and suffix; they never overlap.
/// Byte lengths of the common prefix and suffix; they never overlap. Compared
/// byte-wise (equal bytes imply equal chars) so the scan vectorizes, with the
/// ends backed off to char boundaries.
fn common_ends(a: &str, b: &str) -> (usize, usize) {
let shared = |a: &mut dyn Iterator<Item = char>, b: &mut dyn Iterator<Item = char>| -> usize {
a.zip(b).take_while(|(x, y)| x == y).map(|(x, _)| x.len_utf8()).sum()
};
let prefix = shared(&mut a.chars(), &mut b.chars());
let suffix = shared(&mut a[prefix..].chars().rev(), &mut b[prefix..].chars().rev());
let (ab, bb) = (a.as_bytes(), b.as_bytes());
let mut prefix = ab.iter().zip(bb).take_while(|(x, y)| x == y).count();
while !a.is_char_boundary(prefix) {
prefix -= 1;
}
let limit = ab.len().min(bb.len()) - prefix;
let mut suffix = ab.iter().rev().zip(bb.iter().rev()).take(limit).take_while(|(x, y)| x == y).count();
while suffix > 0 && !a.is_char_boundary(a.len() - suffix) {
suffix -= 1;
}
(prefix, suffix)
}
@@ -94,7 +105,13 @@ fn line_starts(lines: &[&str]) -> Vec<usize> {
}
fn utf16_len(text: &str) -> u32 {
text.chars().map(|c| c.len_utf16() as u32).sum()
let bytes = text.as_bytes();
if bytes.is_ascii() {
return bytes.len() as u32;
}
// One unit per char (each starts with a non-continuation byte), two for
// 4-byte chars; byte classification vectorizes, unlike decoding `chars()`.
bytes.iter().map(|&b| u32::from((b & 0xC0) != 0x80) + u32::from(b >= 0xF0)).sum()
}
/// Converts `\r\n` and lone `\r` to `\n`. Borrows when there is nothing to do.
@@ -158,8 +175,12 @@ pub struct Document {
impl Document {
/// Builds a document from text with any line endings; detects and normalizes them.
pub fn new(text: &str) -> Self {
let line_ending = LineEnding::detect(text);
let rope = ropey::Rope::from_str(&normalize_line_endings(text));
// One `\r` scan decides both: LF text needs no normalization pass.
let (line_ending, rope) = if text.contains('\r') {
(LineEnding::detect(text), ropey::Rope::from_str(&normalize_line_endings(text)))
} else {
(LineEnding::Lf, ropey::Rope::from_str(text))
};
Self { rope, version: 0, line_ending }
}
+22
Переглянути файл
@@ -170,6 +170,28 @@ mod tests {
assert_eq!(select_asset(&["laravel-lsp"], rules, LINUX_X64), None);
}
#[test]
fn phoxite_assets() {
let names = [
"phoxite-lsp-aarch64-apple-darwin",
"phoxite-lsp-x86_64-apple-darwin",
"phoxite-lsp-aarch64-unknown-linux-gnu",
"phoxite-lsp-x86_64-unknown-linux-gnu",
"phoxite-lsp-x86_64-pc-windows-msvc.exe",
// Not for any platform here: the musl build, the checksums, the VS Code packages.
"phoxite-lsp-x86_64-unknown-linux-musl",
"phoxite-lsp-x86_64-unknown-linux-gnu.sha256",
"phoxite-lsp-x86_64-pc-windows-msvc.exe.sha256",
"phoxite-linux-x64-0.2.1.vsix",
];
let rules = crate::registry::find("phoxite").unwrap().asset_rules();
assert_eq!(select_asset(&names, rules, MAC_ARM), Some(names[0]));
assert_eq!(select_asset(&names, rules, MAC_X64), Some(names[1]));
assert_eq!(select_asset(&names, rules, LINUX_ARM), Some(names[2]));
assert_eq!(select_asset(&names, rules, LINUX_X64), Some(names[3]));
assert_eq!(select_asset(&names, rules, WIN), Some(names[4]));
}
#[test]
fn kmp_lsp_assets_include_the_native_jar_indexer() {
let names = [
+32
Переглянути файл
@@ -458,6 +458,38 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/laravel/lsp",
needs: &[],
},
ToolSpec {
name: "phoxite",
display: "Phoxite",
kind: LanguageServer,
commands: &["phoxite-lsp"],
// Plain binaries per platform (`phoxite-lsp-<target triple>[.exe]`), each with a
// `.sha256` beside it.
method: Method::Release {
source: ReleaseSource::GitHub { repo: "samehelhawary/phoxite" },
assets: &[
rule(Mac, Arm64, "phoxite-lsp-aarch64-apple-darwin"),
rule(Mac, X64, "phoxite-lsp-x86_64-apple-darwin"),
rule(Linux, Arm64, "phoxite-lsp-aarch64-unknown-linux-gnu"),
rule(Linux, X64, "phoxite-lsp-x86_64-unknown-linux-gnu"),
rule(Windows, Arm64, "phoxite-lsp-aarch64-pc-windows-msvc.exe"),
rule(Windows, X64, "phoxite-lsp-x86_64-pc-windows-msvc.exe"),
],
locate: &[
"phoxite-lsp",
"phoxite-lsp-aarch64-apple-darwin",
"phoxite-lsp-x86_64-apple-darwin",
"phoxite-lsp-aarch64-unknown-linux-gnu",
"phoxite-lsp-x86_64-unknown-linux-gnu",
"phoxite-lsp-aarch64-pc-windows-msvc",
"phoxite-lsp-x86_64-pc-windows-msvc",
],
},
fallback: None,
version: ver("phoxite-lsp"),
homepage: "https://github.com/samehelhawary/phoxite",
needs: &[],
},
ToolSpec {
name: "gopls",
display: "gopls",
+145
Переглянути файл
@@ -0,0 +1,145 @@
//! Show Diff in External Tool: starts the user's diff program on the two sides of a diff.
use ide_core::{IdeError, IdeResult, settings::ExternalDiffSettings};
use serde::Deserialize;
use specta::Type;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
/// One side of the diff: a file on disk, or text written to a temporary file.
#[derive(Clone, Debug, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExternalDiffSide {
/// A saved file, passed to the tool as it is.
pub path: Option<PathBuf>,
/// Content without a file of its own (a revision, a text), written to a temporary file.
pub text: Option<String>,
/// The temporary file's name; its extension lets the tool pick a syntax.
pub name: String,
}
/// Splits a parameter line like a shell does for plain words: whitespace separates
/// arguments, double or single quotes keep one together, a backslash escapes the next
/// character inside double quotes and outside quotes.
pub fn split_parameters(line: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
let mut in_arg = false;
let mut quote: Option<char> = None;
let mut chars = line.chars();
while let Some(c) = chars.next() {
match (quote, c) {
(Some('\''), '\'') | (Some('"'), '"') => quote = None,
(Some('"') | None, '\\') => {
if let Some(next) = chars.next() {
cur.push(next);
}
in_arg = true;
}
(None, '"' | '\'') => {
quote = Some(c);
in_arg = true;
}
(None, c) if c.is_whitespace() => {
if in_arg {
out.push(std::mem::take(&mut cur));
in_arg = false;
}
}
(_, c) => {
cur.push(c);
in_arg = true;
}
}
}
if in_arg {
out.push(cur);
}
out
}
/// The tool's arguments: `%1` the left file, `%2` the right file, `%3` the title.
pub fn expand_parameters(parameters: &str, left: &str, right: &str, title: &str) -> Vec<String> {
split_parameters(parameters)
.into_iter()
.map(|arg| arg.replace("%1", left).replace("%2", right).replace("%3", title))
.collect()
}
fn side_file(side: &ExternalDiffSide, dir: &Path, sub: &str) -> IdeResult<PathBuf> {
if let Some(path) = &side.path {
return Ok(path.clone());
}
let name = Path::new(&side.name).file_name().map(|n| n.to_owned()).unwrap_or_else(|| "content".into());
let folder = dir.join(sub);
std::fs::create_dir_all(&folder)?;
let file = folder.join(name);
std::fs::write(&file, side.text.as_deref().unwrap_or_default())?;
Ok(file)
}
/// Starts the configured tool on `left` ↔ `right` and returns once it runs; the tool
/// lives on after the diff closes, as it would started from a shell.
pub fn launch_external_diff(
settings: &ExternalDiffSettings,
left: &ExternalDiffSide,
right: &ExternalDiffSide,
title: &str,
) -> IdeResult<()> {
let program = settings.path.trim();
if program.is_empty() {
return Err(IdeError::invalid("no external diff tool is set (Settings › Tools › External Diff Tools)"));
}
let needs_temp = left.path.is_none() || right.path.is_none();
// Kept after the call: the tool reads the files after it starts.
let dir = if needs_temp { Some(tempfile::Builder::new().prefix("openidea-diff-").tempdir()?.keep()) } else { None };
let temp = dir.as_deref().unwrap_or_else(|| Path::new(""));
let a = side_file(left, temp, "left")?;
let b = side_file(right, temp, "right")?;
let args = expand_parameters(&settings.parameters, &a.to_string_lossy(), &b.to_string_lossy(), title);
let mut cmd = Command::new(program);
ide_core::process::prepare(&mut cmd);
cmd.args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
let mut child = cmd
.spawn()
.map_err(|e| IdeError::unavailable(format!("cannot start the external diff tool {program}: {e}")))?;
std::thread::spawn(move || {
let _ = child.wait();
});
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn splits_quoted_parameters() {
assert_eq!(split_parameters("%1 %2 %3"), ["%1", "%2", "%3"]);
assert_eq!(split_parameters(r#"--title "%3" -L 'a b' x\ y"#), ["--title", "%3", "-L", "a b", "x y"]);
assert_eq!(split_parameters(r#"--empty "" end"#), ["--empty", "", "end"]);
}
#[test]
fn expands_placeholders_inside_arguments() {
let args = expand_parameters("--left=%1 %2 --title %3", "/t/a b.rs", "/t/b.rs", "a.rs (HEAD ↔ Your version)");
assert_eq!(args, ["--left=/t/a b.rs", "/t/b.rs", "--title", "a.rs (HEAD ↔ Your version)"]);
}
#[test]
fn writes_text_sides_to_named_temporary_files() {
let dir = tempfile::tempdir().unwrap();
let side = ExternalDiffSide { path: None, text: Some("x\n".into()), name: "../Main.java".into() };
let file = side_file(&side, dir.path(), "left").unwrap();
assert_eq!(file, dir.path().join("left/Main.java"));
assert_eq!(std::fs::read_to_string(file).unwrap(), "x\n");
let saved = ExternalDiffSide { path: Some("/p/a.rs".into()), text: None, name: "a.rs".into() };
assert_eq!(side_file(&saved, dir.path(), "right").unwrap(), PathBuf::from("/p/a.rs"));
}
#[test]
fn needs_a_program() {
let side = ExternalDiffSide { path: Some("/p/a".into()), text: None, name: "a".into() };
assert!(launch_external_diff(&ExternalDiffSettings::default(), &side, &side, "t").is_err());
}
}
+2
Переглянути файл
@@ -627,6 +627,7 @@ pub mod changelists;
mod cli;
mod compare;
mod diff;
mod external_diff;
mod history;
mod ignore;
mod index_writes;
@@ -653,6 +654,7 @@ pub use cli::{
set_git_command_observer, set_git_executable,
};
pub use diff::build_partial_patch;
pub use external_diff::{ExternalDiffSide, launch_external_diff};
pub use ignore::{IgnoreDestination, add_to_ignore};
pub use manage::{MergeOptions, RebaseOptions, RemoteEdit, Worktree};
pub use remotes::Remote;
+10 -16
Переглянути файл
@@ -24,8 +24,8 @@ pub(crate) fn branch_info(r: &Repo) -> IdeResult<BranchInfo> {
&& let Some((upstream_name, upstream_id)) = upstream_of(&repo, name.as_ref())
{
info.upstream = Some(upstream_name);
if let (Some(local), Some(up)) = (head_commit, upstream_id) {
let (a, b) = ahead_behind(&repo, local, up)?;
if let Some(local) = head_commit {
let (a, b) = ahead_behind(&repo, local, upstream_id)?;
info.ahead = a;
info.behind = b;
}
@@ -51,16 +51,12 @@ pub(crate) fn operation(repo: &gix::Repository) -> Option<String> {
Some(op.to_string())
}
/// Short upstream name (`origin/main`) and, if the tracking ref exists, its commit.
fn upstream_of(repo: &gix::Repository, branch: &gix::refs::FullNameRef) -> Option<(String, Option<gix::ObjectId>)> {
/// Short upstream name (`origin/main`) and its commit. A branch whose tracking ref is gone (the
/// remote branch was deleted and pruned) tracks nothing, as in IDEA.
fn upstream_of(repo: &gix::Repository, branch: &gix::refs::FullNameRef) -> Option<(String, gix::ObjectId)> {
let tracking = repo.branch_remote_tracking_ref_name(branch, gix::remote::Direction::Fetch)?.ok()?;
let short = to_string(tracking.as_ref().shorten());
let id = repo
.try_find_reference(tracking.as_ref())
.ok()
.flatten()
.and_then(|mut r| r.peel_to_id().ok().map(|id| id.detach()));
Some((short, id))
let id = repo.try_find_reference(tracking.as_ref()).ok()??.peel_to_id().ok()?.detach();
Some((to_string(tracking.as_ref().shorten()), id))
}
/// Commits in `local` not in `upstream`, and vice versa.
@@ -114,11 +110,9 @@ pub(crate) fn branches(r: &Repo) -> IdeResult<Vec<Branch>> {
};
if let Some((up, up_id)) = upstream_of(&repo, full.as_ref()) {
branch.upstream = Some(up);
if let Some(up_id) = up_id {
let (a, b) = ahead_behind(&repo, id, up_id)?;
branch.ahead = a;
branch.behind = b;
}
let (a, b) = ahead_behind(&repo, id, up_id)?;
branch.ahead = a;
branch.behind = b;
}
out.push(branch);
}
+6
Переглянути файл
@@ -777,12 +777,18 @@ fn fetch_prunes_deleted_remote_branches() {
let (fx, bare) = Fixture::with_origin();
fx.git(&["push", "-q", "origin", "main:gone"]);
fx.git(&["fetch", "-q"]);
fx.git(&["checkout", "-q", "-b", "feature", "--track", "origin/gone"]);
let repo = fx.repo();
let upstream = || repo.branches().unwrap().into_iter().find(|b| b.name == "feature").and_then(|b| b.upstream);
assert!(repo.branches().unwrap().iter().any(|b| b.name == "origin/gone"));
assert_eq!(upstream().as_deref(), Some("origin/gone"));
git_in(&bare, &["branch", "-D", "gone"]);
let (cancel, out) = quiet();
repo.fetch(&cancel, &out).unwrap();
assert!(!repo.branches().unwrap().iter().any(|b| b.name == "origin/gone"));
// The branch that tracked it no longer counts as tracking, as in IDEA.
assert_eq!(upstream(), None);
assert_eq!(repo.branch_info().unwrap().upstream, None);
}
#[test]
+2
Переглянути файл
@@ -20,6 +20,8 @@ trash.workspace = true
tracing.workspace = true
parking_lot.workspace = true
zip.workspace = true
flate2.workspace = true
tar.workspace = true
[dev-dependencies]
tempfile.workspace = true
+163 -44
Переглянути файл
@@ -1,6 +1,7 @@
//! Read-only browsing of zip archives (jar, zip, war…), IDEA's `jar://` file
//! system: `<archive>!` is the archive's root and `<archive>!/<entry>` an entry
//! inside it. Listing and reading go through a small cache of parsed central
//! Read-only browsing of zip archives (jar, zip, war…) and gzip'd tars (Zig
//! keeps its fetched packages as `.tar.gz` blobs), IDEA's `jar://` file system:
//! `<archive>!` is the archive's root and `<archive>!/<entry>` an entry inside
//! it. Listing and reading go through a small cache of parsed central
//! directories, refreshed when the archive changes on disk.
use crate::{EntryKind, FileEntry, mtime_ms, natural_cmp};
@@ -8,7 +9,7 @@ use ide_core::{IdeError, IdeResult};
use parking_lot::Mutex;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::io::{Read, Seek};
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock};
use std::time::SystemTime;
@@ -22,13 +23,21 @@ pub const ARCHIVE_SEPARATOR: char = '!';
/// Parsed archives kept open.
const CACHE_SIZE: usize = 8;
/// Whether `path` names a file browsed as an archive (by extension).
/// Whether `path` names a file browsed as an archive: a zip extension, or a
/// gzip'd tar (`x.tar.gz`).
pub fn is_archive_file(path: &Path) -> bool {
if is_tar_gz(path) {
return true;
}
path.extension()
.and_then(|e| e.to_str())
.is_some_and(|e| ARCHIVE_EXTENSIONS.iter().any(|a| a.eq_ignore_ascii_case(e)))
}
fn is_tar_gz(path: &Path) -> bool {
path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.to_ascii_lowercase().ends_with(".tar.gz"))
}
/// `(archive, entry)` for `<archive>!` (entry `""`) or `<archive>!/<entry>`;
/// `None` for ordinary paths. The entry is `/`-separated without leading or trailing `/`.
pub fn split_archive_path(path: &Path) -> Option<(PathBuf, String)> {
@@ -84,7 +93,14 @@ struct Archive {
mtime_ms: f64,
/// Entry path (`""` = root) → node.
nodes: HashMap<String, Node>,
zip: Mutex<zip::ZipArchive<File>>,
contents: Contents,
}
/// Where entry contents come from: a random-access zip, or a gzip'd tar that
/// is re-scanned per read (package tarballs are small).
enum Contents {
Zip(Mutex<zip::ZipArchive<File>>),
Tar(Mutex<File>),
}
/// Most recently used first.
@@ -115,43 +131,83 @@ fn parent_of(name: &str) -> (&str, &str) {
impl Archive {
fn open(path: &Path, stamp: (Option<SystemTime>, u64), mtime_ms: f64) -> IdeResult<Self> {
let mut zip = zip::ZipArchive::new(File::open(path)?).map_err(|e| zip_error(path, e))?;
let mut nodes: HashMap<String, Node> = HashMap::new();
nodes.insert(String::new(), Node { dir: true, size: 0, index: None, children: Vec::new() });
for i in 0..zip.len() {
let Ok(file) = zip.by_index_raw(i) else { continue };
let Ok(name) = file.name() else { continue };
let Some(name) = clean_name(&name) else { continue };
let (dir, size) = (file.is_dir(), file.size());
drop(file);
let mut parent = parent_of(&name).0;
while !nodes.contains_key(parent) {
nodes.insert(parent.to_owned(), Node { dir: true, size: 0, index: None, children: Vec::new() });
parent = parent_of(parent).0;
}
let node = nodes.entry(name).or_insert(Node { dir, size: 0, index: None, children: Vec::new() });
node.dir |= dir;
node.index = Some(i);
node.size = if node.dir { 0 } else { size };
}
let links: Vec<(String, String)> = nodes
.keys()
.filter(|k| !k.is_empty())
.map(|k| {
let (parent, base) = parent_of(k);
(parent.to_owned(), base.to_owned())
})
.collect();
for (parent, base) in links {
if let Some(p) = nodes.get_mut(&parent) {
p.dir = true;
p.children.push(base);
}
}
Ok(Self { stamp, mtime_ms, nodes, zip: Mutex::new(zip) })
let file = File::open(path)?;
let (nodes, contents) = if is_tar_gz(path) {
(tar_nodes(&file)?, Contents::Tar(Mutex::new(file)))
} else {
let mut zip = zip::ZipArchive::new(file).map_err(|e| zip_error(path, e))?;
let nodes = zip_nodes(&mut zip)?;
(nodes, Contents::Zip(Mutex::new(zip)))
};
Ok(Self { stamp, mtime_ms, nodes, contents })
}
}
/// The directory tree of a zip, with each entry's central-directory index.
fn zip_nodes(zip: &mut zip::ZipArchive<File>) -> IdeResult<HashMap<String, Node>> {
let mut nodes: HashMap<String, Node> = HashMap::new();
nodes.insert(String::new(), Node { dir: true, size: 0, index: None, children: Vec::new() });
for i in 0..zip.len() {
let Ok(file) = zip.by_index_raw(i) else { continue };
let Ok(name) = file.name() else { continue };
let Some(name) = clean_name(&name) else { continue };
let (dir, size) = (file.is_dir(), file.size());
drop(file);
add_entry(&mut nodes, name, i, dir, size);
}
Ok(link_children(nodes))
}
/// The directory tree of a gzip'd tar, with each entry's ordinal position.
/// Entries are re-read by streaming the (decompressed) tar again.
fn tar_nodes(file: &File) -> IdeResult<HashMap<String, Node>> {
let mut nodes: HashMap<String, Node> = HashMap::new();
nodes.insert(String::new(), Node { dir: true, size: 0, index: None, children: Vec::new() });
let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file));
for (i, entry) in tar.entries()?.enumerate() {
let Ok(entry) = entry else { break };
let Ok(name) = entry.path().map(|p| p.to_string_lossy().into_owned()) else { continue };
let Some(name) = clean_name(&name) else { continue };
let (dir, size) = match entry.header().entry_type().is_dir() {
true => (true, 0),
false => (false, entry.header().size().unwrap_or_default()),
};
add_entry(&mut nodes, name, i, dir, size);
}
Ok(link_children(nodes))
}
fn add_entry(nodes: &mut HashMap<String, Node>, name: String, index: usize, dir: bool, size: u64) {
let mut parent = parent_of(&name).0;
while !nodes.contains_key(parent) {
nodes.insert(parent.to_owned(), Node { dir: true, size: 0, index: None, children: Vec::new() });
parent = parent_of(parent).0;
}
let node = nodes.entry(name).or_insert(Node { dir, size: 0, index: None, children: Vec::new() });
node.dir |= dir;
node.index = Some(index);
node.size = if node.dir { 0 } else { size };
}
/// Makes every named entry a child of its parent folder node.
fn link_children(mut nodes: HashMap<String, Node>) -> HashMap<String, Node> {
let links: Vec<(String, String)> = nodes
.keys()
.filter(|k| !k.is_empty())
.map(|k| {
let (parent, base) = parent_of(k);
(parent.to_owned(), base.to_owned())
})
.collect();
for (parent, base) in links {
if let Some(p) = nodes.get_mut(&parent) {
p.dir = true;
p.children.push(base);
}
}
nodes
}
/// The parsed archive at `path`, from the cache unless it changed on disk.
fn archive(path: &Path) -> IdeResult<Arc<Archive>> {
let meta = std::fs::metadata(path)?;
@@ -235,10 +291,31 @@ pub fn read_archive_entry(archive_path: &Path, entry: &str) -> IdeResult<(Vec<u8
Some(_) => return Err(IdeError::invalid(format!("{entry} is a directory"))),
None => return Err(IdeError::not_found(format!("{entry} not found in {}", archive_path.display()))),
};
let mut zip = a.zip.lock();
let mut file = zip.by_index(index).map_err(|e| zip_error(archive_path, e))?;
let mut bytes = Vec::with_capacity(file.size().min(crate::MAX_OPEN_SIZE) as usize);
file.read_to_end(&mut bytes)?;
let bytes = match &a.contents {
Contents::Zip(zip) => {
let mut zip = zip.lock();
let mut file = zip.by_index(index).map_err(|e| zip_error(archive_path, e))?;
let mut bytes = Vec::with_capacity(file.size().min(crate::MAX_OPEN_SIZE) as usize);
file.read_to_end(&mut bytes)?;
bytes
}
Contents::Tar(file) => {
let mut file = file.lock();
file.seek(std::io::SeekFrom::Start(0))?;
let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(&mut *file));
for (i, entry) in tar.entries()?.enumerate() {
if i != index {
continue;
}
let mut entry = entry.map_err(|e| IdeError::invalid(format!("{}: {e}", archive_path.display())))?;
let mut bytes =
Vec::with_capacity(entry.header().size().unwrap_or_default().min(crate::MAX_OPEN_SIZE) as usize);
entry.read_to_end(&mut bytes)?;
return Ok((bytes, a.mtime_ms));
}
return Err(IdeError::not_found(format!("{entry} not found in {}", archive_path.display())));
}
};
Ok((bytes, a.mtime_ms))
}
@@ -262,6 +339,20 @@ pub(crate) mod tests {
w.finish().unwrap();
}
/// Writes a gzip'd tar with `files`, the layout of the Zig package cache blobs.
pub(crate) fn write_tar_gz(path: &Path, files: &[(&str, &str)]) {
let enc = flate2::write::GzEncoder::new(File::create(path).unwrap(), flate2::Compression::default());
let mut b = tar::Builder::new(enc);
for (name, text) in files {
let mut header = tar::Header::new_gnu();
header.set_size(text.len() as u64);
header.set_mode(0o644);
header.set_cksum();
b.append_data(&mut header, name, text.as_bytes()).unwrap();
}
b.into_inner().unwrap().finish().unwrap();
}
#[test]
fn splits_archive_paths() {
assert_eq!(split_archive_path(Path::new("/a/b.txt")), None);
@@ -317,6 +408,34 @@ pub(crate) mod tests {
assert_eq!(names(""), vec![("only.txt".into(), EntryKind::File)]);
}
#[test]
fn lists_and_reads_gzipped_tars() {
let tmp = tempfile::tempdir().unwrap();
let hash = "probe_pkg-0.1.0-ISc0DC0BAAD0X6wRO4jcg4yLywsgmBYSlOsNhFDSnwV8";
let blob = tmp.path().join(format!("{hash}.tar.gz"));
let (zon, lib) = (format!("{hash}/build.zig.zon"), format!("{hash}/src/lib.zig"));
write_tar_gz(&blob, &[(zon.as_str(), ".{ .name = .probe_pkg }"), (lib.as_str(), "pub fn hello() {}\n")]);
let root = |entry: &str| PathBuf::from(format!("{}!/{entry}", blob.display()));
let names = |dir: &str| -> Vec<String> {
crate::read_dir(&root(&format!("{hash}/{dir}")), &[]).unwrap().into_iter().map(|e| e.name).collect()
};
assert_eq!(names(""), vec!["src", "build.zig.zon"]);
assert_eq!(names("src"), vec!["lib.zig"]);
let lib = crate::load_text(&root(&format!("{hash}/src/lib.zig"))).unwrap();
assert_eq!((lib.text.as_str(), lib.binary), ("pub fn hello() {}\n", false));
// A rewritten tar is re-read, and a plain `.gz` stays an ordinary file.
write_tar_gz(&blob, &[("only.zig", "1")]);
let f = File::options().write(true).open(&blob).unwrap();
f.set_modified(SystemTime::now() + std::time::Duration::from_secs(5)).unwrap();
assert_eq!(
crate::read_dir(&root(""), &[]).unwrap().iter().map(|e| e.name.as_str()).collect::<Vec<_>>(),
["only.zig"]
);
assert!(!is_archive_file(Path::new("/a/data.gz")));
assert!(is_archive_file(Path::new("/a/pack.TAR.GZ")));
}
#[test]
fn read_dir_and_load_text_go_through_archives() {
let tmp = tempfile::tempdir().unwrap();
+2
Переглянути файл
@@ -28,6 +28,8 @@ Style components with CSS Modules: `Thing.module.css` next to `Thing.tsx`, impor
Build from the primitives in `src/ui/` before writing your own: `Button`, `BarButton`, `Input`, `Checkbox`, `Select`, `Dialog`, `Popup`, `Menu`, `Tooltip`, `List`, `Tree`, `Tabs`, `Splitter`, `Scrollbar`, `Spinner`, `Kbd`, and `T` for translated text. They already handle focus, keyboard navigation, theming and translation of their labels. Workbench-level pieces (tool windows, status items, overlays) come from [contributions](/en/contribute/architecture/frontend#contributions), not from custom layout.
Toolbar icon actions use `IconButton`: its full hit target uses `--bg-toolbar-hover` on hover, while pressed and selected states use their corresponding toolbar tokens. Keep semantic icon colours and the keyboard focus ring intact.
## Accessibility
- Use real `<button>` and `<input>` elements (or the primitives that render them), never clickable `<div>`s.
+4
Переглянути файл
@@ -56,6 +56,8 @@ Agents are unavailable in a project you have not marked as trusted.
Available models depend on the installed agent and account. If a selected model is removed, choose another before starting. Refreshing does not change running tasks.
The version below the prompt is reported by a fresh agent initialization when this page is shown or the window regains focus. After updating a CLI, return to this page to refresh it. This does not restart running tasks; an already running agent process keeps its original version until it exits.
</Step>
<Step title="Send">
The task opens as an editor tab and starts.
@@ -119,6 +121,8 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
**Settings › Tools › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
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.
## Add a custom agent
Any agent that speaks ACP over stdio can be added with an agent file, `agents/<id>.toml` in OpenIDEA's configuration directory:
+2 -1
Переглянути файл
@@ -146,7 +146,8 @@ Closing a selected result activates its left neighbor, or its right neighbor if
**Edit Data** (`F4`) opens a table in an editor tab with server-side paging (100 to 5,000 rows), a `WHERE` filter and an `ORDER BY` field (both with completion). Click a column header to sort; `Shift`-click to add more sort columns.
- Double-click, `Enter` or `F2` edits a cell; `Shift+Enter` opens a larger editor. Pasting tab-separated text fills several cells.
- **Add Row**, **Delete Rows**, **Set NULL** (`⌘⌫` / `Ctrl+Backspace`), **Set DEFAULT** (`⌘⇧⌫` / `Ctrl+Shift+Backspace`). `Space` toggles booleans.
- **Add Row** (`⌘N` / `Alt+Insert`), **Delete Rows** (`Ctrl+Y` on Windows and Linux), **Set NULL** (`⌘⌫` / `Ctrl+Backspace`), **Set DEFAULT** (`⌘⇧⌫` / `Ctrl+Shift+Backspace`). `Space` toggles booleans.
- **Reload Page** (`⌘R` / `Ctrl+F5`), **Previous Page** and **Next Page** (`⌘⌥↑` / `⌘⌥↓`, `Ctrl+Alt+Up` / `Ctrl+Alt+Down`). These, the copy commands and **Export Data** are actions: find them with **Find Action** and assign shortcuts in **Settings › Keymap**.
- **Submit** (`⌘Enter` / `Ctrl+Enter`) sends all pending changes in one transaction; **Revert** (`⌘⌥Z` / `Ctrl+Alt+Z`) discards them.
Console results are editable the same way when the query is a plain select from one table that includes the primary key. Tables without a primary key, joins, aggregates, `UNION` queries, read-only data sources and ClickHouse results are read-only.
+1 -1
Переглянути файл
@@ -47,7 +47,7 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
| **Move Caret to Code Block Start** / **End** | `⌥⌘[` / `⌥⌘]` | `Ctrl+[` / `Ctrl+]` |
| **Toggle Insert/Overwrite** | `Insert` | `Insert` |
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines; they have no default shortcut.
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines (the whole file without a selection); they have no default shortcut. Sort Lines orders by character code, so uppercase letters come before lowercase ones.
Brackets and quotes are paired as you type, and typing a quote or bracket over a selection surrounds it. These and other typing aids (smart Home, Tab out of a closing bracket, smart indent on Enter, documentation comment stubs, what Backspace does with indentation, reformat on paste) are under **Settings › Editor › General › Smart Keys**.
+1
Переглянути файл
@@ -101,6 +101,7 @@ Each entry starts one LSP server. Servers are listed in order; all regular serve
| `settings` | table | Answers the server's `workspace/configuration` requests. Without it, the requested sections are looked up in `initialization-options`. |
| `install-hint` | string | Shown when the server is missing and the IDE cannot install it. |
| `fallback` | bool | An alternative to the servers listed before it; used only while none of them is installed. |
| `replaces` | string array | Names of servers listed after this one that it makes redundant. They are not used while this server serves the file. Use it for an alternative that covers what an added server does. |
| `features` | string array | Use the server only for these features; empty means everything. Values: `completion`, `inline-completion`, `hover`, `signature-help`, `definition`, `declaration`, `type-definition`, `implementation`, `references`, `document-highlight`, `document-symbol`, `workspace-symbol`, `code-action`, `code-lens`, `rename`, `formatting`, `inlay-hint`, `semantic-tokens`, `document-link`, `call-hierarchy`, `type-hierarchy`, `folding-range`, `selection-range`, `diagnostics`. |
| `code-action-kinds` | string array | Keep only these code action kinds, matched by prefix (`refactor` keeps `refactor.extract`); empty keeps all. |
| `connect` | string | `host:port` of a server that speaks LSP over TCP. See [TCP servers](#tcp-servers). |
+1 -1
Переглянути файл
@@ -148,7 +148,7 @@ The table lists every built-in language definition. Server and debugger names in
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | Yes | Yes | ocamllsp | ocamlearlybird |
| OCaml Interface | `ocaml.interface` | `.mli` | Yes | Yes | ocamllsp | — |
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | Yes | — | **perlnavigator** | — |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → phpactor + **laravel-lsp** | **php-debug** |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | Yes | Yes | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** |
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | Yes | — | powershell-editor-services | — |
| Prisma | `prisma` | `.prisma` | Yes | Yes | **prisma-language-server** | — |
+11 -7
Переглянути файл
@@ -7,11 +7,14 @@ OpenIDEA highlights PHP files (`.php`, `.phtml`, `.phpt` and older `.php3`–`.p
## Language servers
| Server | When it runs |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | Default. Workspace root: `composer.json`, `.phpactor.json` or `index.php`. |
| `phpactor` | Fallback: used only while Intelephense is not installed. |
| `laravel-lsp` | Laravel projects only (below an `artisan` file): hover, definition and completion inside `config('…')`, `route('…')` and `view('…')`. |
| Server | When it runs |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | Default. Workspace root: `composer.json`, `.phpactor.json` or `index.php`. |
| `phpactor` | Fallback: used only while Intelephense is not installed. |
| `phoxite` | Alternative with its own Laravel and Blade support: used while neither server above is installed, or when you pick it in **Settings › Languages & Frameworks › Language Servers**. |
| `laravel-lsp` | Laravel projects only (below an `artisan` file): hover, definition and completion inside `config('…')`, `route('…')` and `view('…')`. |
While Phoxite serves a project, `laravel-lsp` is not started: Phoxite answers the Laravel strings itself.
Intelephense checks code against the project's PHP version (see [Language level](#language-level)) and indexes the stubs and include paths you configure.
@@ -25,6 +28,7 @@ When a `.php` file opens and Intelephense is missing, a notification offers **In
| ------------------ | ---------------------------------------------------------------------- |
| Intelephense | npm (`intelephense`) |
| Laravel LSP | GitHub release (`laravel/lsp`) |
| Phoxite | GitHub release (`samehelhawary/phoxite`) |
| PHP Debug (Xdebug) | Open VSX (`xdebug.php-debug`); needs Node.js to run |
| phpactor | Not installable from the IDE; install it yourself and put it on `PATH` |
@@ -77,12 +81,12 @@ See [Debugging](/en/guide/debugging).
## Framework support
- **Laravel**: Laravel LSP for `config()`, `route()` and `view()` strings, and an `artisan serve` configuration.
- **Laravel**: Laravel LSP for `config()`, `route()` and `view()` strings, and an `artisan serve` configuration. With Phoxite as the PHP server, routes, views, config, translations and Eloquent models get completion, navigation and rename from it instead.
- **WordPress** and similar platforms: add their stubs under **Additional stubs** and the platform folder under **Include paths**.
## Limitations
- No Blade or Twig template support; only `.php` files get PHP code insight.
- No Blade or Twig template support with Intelephense; only `.php` files get PHP code insight. Phoxite adds code insight in `.blade.php` files, without Blade highlighting.
- phpactor is not installed by the IDE.
- Run with Coverage is not available for PHPUnit.
- Debugging needs the Xdebug extension in your PHP; the IDE does not install it.
+2
Переглянути файл
@@ -28,6 +28,8 @@ description: "前端 UI 代码的规则:设计 token、CSS Modules、图标、
先用 `src/ui/` 里的基础组件,再考虑自己写:`Button`、`BarButton`、`Input`、`Checkbox`、`Select`、`Dialog`、`Popup`、`Menu`、`Tooltip`、`List`、`Tree`、`Tabs`、`Splitter`、`Scrollbar`、`Spinner`、`Kbd`,以及用于翻译文本的 `T`。它们已经处理好焦点、键盘导航、主题和标签翻译。工作台级别的部件(工具窗口、状态栏项、浮层)来自 [contribution](/zh/contribute/architecture/frontend),不要自己写布局。
工具栏图标操作使用 `IconButton`:悬停时整个点击区域使用 `--bg-toolbar-hover`,按下和选中状态使用对应的工具栏 token。保留图标的语义颜色和键盘焦点环。
## 无障碍
- 使用真正的 `<button>` 和 `<input>` 元素(或渲染它们的基础组件),不要用可点击的 `<div>`。
+4
Переглянути файл
@@ -56,6 +56,8 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
可用模型取决于已安装的 agent 和账号。如果已选模型被移除,需要先选择其他模型才能开始任务。刷新不会更改正在运行的任务。
提示词下方的版本来自 agent 的初始化响应;显示此页面或窗口重新获得焦点时会重新查询。更新 CLI 后,返回此页面即可刷新版本。这不会重启正在运行的任务;已运行的 agent 进程在退出前仍使用原来的版本。
</Step>
<Step title="发送">
任务会在编辑器标签页中打开并开始运行。
@@ -119,6 +121,8 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
**设置 › 工具 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。在 **设置 › 智能体 › 工作状态** 中可以让这里改为显示与当前工作相关的趣味文字,默认关闭。开启后,工作一变化就轮换显示,也可以设置在 agent 无新进展多少秒后才显示(0 到 600,默认 0);屏幕阅读器读出的仍是 agent 实际在做的事。agent 持续做同一类工作时,每条文字停留八秒;转向其他工作时也至少停留三秒,状态行不会频繁跳动。同一页面还可以替换这些文字:选择状态(**正在读取…**、**正在运行命令…**…),再添加或移除对应的文字。**恢复内置文字** 会换回 OpenIDEA 自带的文字;没有任何文字的状态只显示实际进展。
## 添加自定义 agent
任何通过 stdio 使用 ACP 的 agent,都可以用一个 agent 文件添加:OpenIDEA 配置目录下的 `agents/<id>.toml`。
+2 -1
Переглянути файл
@@ -145,7 +145,8 @@ SQL 补全基于已连接的架构:`FROM`/`JOIN` 后补全表(并根据外
**编辑数据**(`F4`)在编辑器标签页中打开表,服务器端分页(每页 100 到 5,000 行),并提供 `WHERE` 过滤和 `ORDER BY` 字段(都支持补全)。点击列标题排序,按住 `Shift` 点击可以追加排序列。
- 双击、`Enter` 或 `F2` 编辑单元格;`Shift+Enter` 打开更大的编辑框。粘贴制表符分隔的文本可以一次填写多个单元格。
- **添加行**、**删除行**、**设为 NULL**(`⌘⌫` / `Ctrl+Backspace`)、**设为默认值**(`⌘⇧⌫` / `Ctrl+Shift+Backspace`)。`Space` 切换布尔值。
- **添加行**(`⌘N` / `Alt+Insert`)、**删除行**(Windows 和 Linux 上为 `Ctrl+Y`)、**设为 NULL**(`⌘⌫` / `Ctrl+Backspace`)、**设为默认值**(`⌘⇧⌫` / `Ctrl+Shift+Backspace`)。`Space` 切换布尔值。
- **重新加载页面**(`⌘R` / `Ctrl+F5`)、**上一页** 和 **下一页**(`⌘⌥↑` / `⌘⌥↓`,`Ctrl+Alt+Up` / `Ctrl+Alt+Down`)。这些命令、各种复制命令和 **导出数据** 都是操作:可以在 **查找操作** 中找到,并在 **设置 › 按键映射** 中设置快捷键。
- **提交**(`⌘Enter` / `Ctrl+Enter`)在一个事务中提交所有待定更改;**还原**(`⌘⌥Z` / `Ctrl+Alt+Z`)放弃更改。
如果控制台查询是对单表的简单 select 且包含主键,结果同样可以编辑。没有主键的表、连接查询、聚合、`UNION` 查询、只读数据源和 ClickHouse 的结果都是只读的。
+1 -1
Переглянути файл
@@ -47,7 +47,7 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
| **将光标移至代码块开头** / **末尾** | `⌥⌘[` / `⌥⌘]` | `Ctrl+[` / `Ctrl+]` |
| **切换插入/改写** | `Insert` | `Insert` |
**编辑 › 对行排序** 和 **编辑 › 反转行** 对选中的行重新排序,默认没有快捷键。
**编辑 › 对行排序** 和 **编辑 › 反转行** 对选中的行(没有选区时为整个文件)重新排序,默认没有快捷键。对行排序按字符编码排序,大写字母排在小写字母之前。
输入时括号和引号会自动成对,选中文本后输入引号或括号会把选区包起来。这些以及其他输入辅助(智能 Home、用 Tab 跳出右括号、回车智能缩进、文档注释骨架、退格键如何处理缩进、粘贴时重新格式化)都在 **设置 › 编辑器 › 常规 › 智能键** 中。
+1
Переглянути файл
@@ -101,6 +101,7 @@ root-markers = ["angular.json", "node_modules/@angular/core"]
| `settings` | 表 | 用于响应服务器的 `workspace/configuration` 请求。不写时,从 `initialization-options` 中查找请求的配置节。 |
| `install-hint` | 字符串 | 服务器缺失且 IDE 无法安装时显示的提示。 |
| `fallback` | 布尔 | 作为前面服务器的备选,只在它们都未安装时使用。 |
| `replaces` | 字符串数组 | 排在它后面、因它而变得多余的服务器名称。它为文件提供服务时,这些服务器不会被使用。用于能覆盖附加服务器功能的备选服务器。 |
| `features` | 字符串数组 | 只把服务器用于这些功能;为空表示全部。可选值:`completion`、`inline-completion`、`hover`、`signature-help`、`definition`、`declaration`、`type-definition`、`implementation`、`references`、`document-highlight`、`document-symbol`、`workspace-symbol`、`code-action`、`code-lens`、`rename`、`formatting`、`inlay-hint`、`semantic-tokens`、`document-link`、`call-hierarchy`、`type-hierarchy`、`folding-range`、`selection-range`、`diagnostics`。 |
| `code-action-kinds` | 字符串数组 | 只保留这些种类的代码操作,按前缀匹配(`refactor` 包含 `refactor.extract`);为空则全部保留。 |
| `connect` | 字符串 | 通过 TCP 提供 LSP 的服务器地址 `host:port`,见 [TCP 服务器](#tcp-服务器)。 |
+1 -1
Переглянути файл
@@ -143,7 +143,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| OCaml | `ocaml` | `.ml`, `.mll`, `.mly` | 是 | 是 | ocamllsp | ocamlearlybird |
| OCaml Interface | `ocaml.interface` | `.mli` | 是 | 是 | ocamllsp | — |
| Perl | `perl` | `.pl`, `.pm`, `.pod`, `.psgi`, `.cgi` | 是 | — | **perlnavigator** | — |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → phpactor + **laravel-lsp** | **php-debug** |
| PHP | `php` | `.php`, `.phtml`, `.php3`, `.php4`, `.php5`, … | 是 | 是 | **intelephense** → phpactor → **phoxite** + **laravel-lsp** | **php-debug** |
| Plain Text | `plaintext` | `.txt`, `.text` | — | — | — | — |
| PowerShell | `powershell` | `.ps1`, `.psm1`, `.psd1`, `.pssc`, `.psrc` | 是 | — | powershell-editor-services | — |
| Prisma | `prisma` | `.prisma` | 是 | 是 | **prisma-language-server** | — |
+11 -7
Переглянути файл
@@ -7,11 +7,14 @@ OpenIDEA 开箱即可高亮 PHP 文件(`.php`、`.phtml`、`.phpt` 以及老
## 语言服务器
| 服务器 | 启用条件 |
| -------------- | --------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | 默认。工作区根:`composer.json`、`.phpactor.json` 或 `index.php`。 |
| `phpactor` | 备选:仅在未安装 Intelephense 时使用。 |
| `laravel-lsp` | 仅限 Laravel 项目(`artisan` 文件所在目录之下):在 `config('…')`、`route('…')`、`view('…')` 中提供悬停、跳转和补全。 |
| 服务器 | 启用条件 |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `intelephense` | 默认。工作区根:`composer.json`、`.phpactor.json` 或 `index.php`。 |
| `phpactor` | 备选:仅在未安装 Intelephense 时使用。 |
| `phoxite` | 备选,自带 Laravel 和 Blade 支持:仅在以上两个服务器都未安装时使用,或在 **设置 › 语言和框架 › 语言服务器** 中选中它时使用。 |
| `laravel-lsp` | 仅限 Laravel 项目(`artisan` 文件所在目录之下):在 `config('…')`、`route('…')`、`view('…')` 中提供悬停、跳转和补全。 |
Phoxite 为项目提供服务时不会启动 `laravel-lsp`:Laravel 相关的字符串由 Phoxite 自己处理。
Intelephense 会按项目的 PHP 版本检查代码(见下文“语言级别”),并索引你配置的 stub 和包含路径。
@@ -25,6 +28,7 @@ Intelephense 会按项目的 PHP 版本检查代码(见下文“语言级别
| ------------------ | -------------------------------------------------- |
| Intelephense | npm(`intelephense`) |
| Laravel LSP | GitHub release(`laravel/lsp`) |
| Phoxite | GitHub release(`samehelhawary/phoxite`) |
| PHP Debug (Xdebug) | Open VSX(`xdebug.php-debug`),运行时需要 Node.js |
| phpactor | IDE 不负责安装,请自行安装并放到 `PATH` 上 |
@@ -77,12 +81,12 @@ PHPUnit 运行配置类型包含 **目标**、**配置文件**、**测试过滤
## 框架支持
- **Laravel**:Laravel LSP 支持 `config()`、`route()`、`view()` 中的字符串,并提供 `artisan serve` 运行配置。
- **Laravel**:Laravel LSP 支持 `config()`、`route()`、`view()` 中的字符串,并提供 `artisan serve` 运行配置。以 Phoxite 作为 PHP 服务器时,路由、视图、配置、翻译和 Eloquent 模型的补全、跳转和重命名改由它提供。
- **WordPress** 等平台:在 **附加存根** 中加入对应 stub,在 **包含路径** 中加入平台代码目录。
## 已知限制
- 不支持 Blade 或 Twig 模板,只有 `.php` 文件有 PHP 代码智能。
- 使用 Intelephense 时不支持 Blade 或 Twig 模板,只有 `.php` 文件有 PHP 代码智能。Phoxite 为 `.blade.php` 文件提供代码智能,但没有 Blade 语法高亮。
- IDE 不会安装 phpactor。
- PHPUnit 不支持使用覆盖率运行。
- 调试需要 PHP 已安装 Xdebug 扩展,IDE 不负责安装。
+2 -2
Переглянути файл
@@ -83,8 +83,8 @@ for (const placement of ["editor", "toolWindow"] as const) {
},
{ id: task.id, placement },
);
// The working indicator ends the conversation, after its rows.
await expect(stream.getByRole("status").getByText("Working…", { exact: true })).toBeVisible();
// The working indicator ends the conversation, after its rows; the turn ends with a reply.
await expect(stream.getByRole("status").getByText("Writing…", { exact: true })).toBeVisible();
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3 + 1);
await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(2);
const timer = await page.evaluate(async (id) => {
+75
Переглянути файл
@@ -0,0 +1,75 @@
import { expect, test } from "./fixtures";
test.beforeEach(async ({ workbench: page }) => {
await page.evaluate(async () => {
// Load the IPC module in Vite's browser realm, not Playwright's Node process.
const ipcPath = "/src/platform/ipc.ts";
const { commands } = await import(ipcPath);
const provider = {
id: "omp",
name: "OMP",
command: "omp acp",
program: "omp",
args: ["acp"],
defaultProgram: null,
defaultArgs: [],
loginHint: null,
commandOverridden: false,
commandEditable: true,
commandReadOnlyReason: null,
installed: true,
env: {},
commands: [],
source: { kind: "custom" },
config: [],
thoughtLevels: {},
};
let installed = "18.20.0";
let cached = installed;
window.addEventListener("test:agent-upgraded", () => {
installed = "18.20.2";
});
commands.agentProviders = async () => ({ status: "ok", data: [provider] });
commands.agentProbe = async (id: string, refresh: boolean) => {
if (refresh) cached = installed;
return {
status: "ok",
data: { provider: id, name: "omp", version: cached, protocol: "ACP v1", error: null },
};
};
commands.agentRefreshModels = async () => ({
status: "ok",
data: {
provider: "omp",
config: [],
thoughtLevels: {},
refreshing: false,
refreshedAtMs: Date.now(),
retryAtMs: null,
error: null,
},
});
});
await page.getByRole("button", { name: "Agents", exact: true }).click();
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
await expect(page.getByText("omp · 18.20.0 · ACP v1", { exact: true })).toBeVisible();
});
test("refreshes an upgraded agent's version on window focus without losing the draft", async ({ workbench: page }) => {
const message = page.getByRole("textbox", { name: "Message", exact: true });
await message.focus();
await page.keyboard.insertText("Keep this unsent draft");
await page.evaluate(() => {
window.dispatchEvent(new Event("test:agent-upgraded"));
window.dispatchEvent(new Event("focus"));
});
await expect(page.getByText("omp · 18.20.2 · ACP v1", { exact: true })).toBeVisible();
await expect(message).toHaveText("Keep this unsent draft");
});
test("refreshes an upgraded agent's version when New Task is reopened", async ({ workbench: page }) => {
await page.getByRole("button", { name: "Close Tab", exact: true }).click();
await page.evaluate(() => window.dispatchEvent(new Event("test:agent-upgraded")));
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
await expect(page.getByText("omp · 18.20.2 · ACP v1", { exact: true })).toBeVisible();
});
+95
Переглянути файл
@@ -98,6 +98,101 @@ test("completion lists the server's items and inserts the chosen one", async ({
expect((await ipcCalls(page, "lsp_completion")).length).toBeGreaterThan(0);
});
test("documentation shows beside the lookup instead of being clipped by it", async ({ workbench: page }, info) => {
const editor = await openSample(page);
await page.evaluate(async () => {
// Long enough for the pane to reach its max-width: a short doc leaves it at
// `width: max-content`, so the placement assertions would never exercise the room calculation.
const longDocs =
"Computes the order total including tax, discounts and shipping, rounded to the currency's scale. " +
"The result is cached until the order changes, so callers should not hold on to it across edits; " +
"ask for a fresh value after every update.";
const item = (label: string, detail: string) => ({
label,
labelDetail: "()",
detail,
kind: "method",
documentation: { kind: "markdown", value: `Docs for **${label}**. ${longDocs}` },
sortText: null,
filterText: null,
preselect: false,
deprecated: false,
insertText: `${label}()`,
isSnippet: false,
replaceRange: null,
replaceRangeTab: null,
additionalEdits: [],
commitCharacters: [],
command: null,
data: null,
server: 1,
});
window.__ipc.handlers.lsp_completion = () => ({
isIncomplete: false,
items: [item("total", "BigDecimal"), item("toDto", "OrderDto")],
});
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const settings = structuredClone(useProject.getState().settings ?? {});
const editor = settings.editor ?? {};
settings.editor = {
...editor,
completion: { ...editor.completion, showDocumentation: true, documentationDelay: 0 },
};
useProject.setState({ settings });
});
const popup = page.locator(".cm-tooltip-autocomplete");
const openLookup = async () => {
await editor.locator(".cm-line", { hasText: "return order.toDto()" }).click();
await page.keyboard.press("End");
await page.keyboard.press("Enter");
await page.keyboard.type("order.");
await page.keyboard.press("Control+Space");
await expect(popup.getByText("total", { exact: true })).toBeVisible();
await expect(page.locator(".cm-completionInfo")).toContainText("Docs for");
};
const geometry = () =>
page.evaluate(() => {
const info = document.querySelector(".cm-completionInfo") as HTMLElement;
const list = (document.querySelector(".cm-tooltip-autocomplete") as HTMLElement).getBoundingClientRect();
const rect = info.getBoundingClientRect();
const overlapX = Math.max(0, Math.min(rect.right, list.right) - Math.max(rect.left, list.left));
const overlapY = Math.max(0, Math.min(rect.bottom, list.bottom) - Math.max(rect.top, list.top));
const side = info.classList.contains("cm-completionInfo-left")
? "left"
: info.classList.contains("cm-completionInfo-right")
? "right"
: "none";
return {
overlap: overlapX * overlapY,
visible: !!document.elementFromPoint(rect.left + 4, rect.top + 4)?.closest(".cm-completionInfo"),
inside: rect.left >= 0 && rect.right <= document.documentElement.clientWidth,
side,
};
});
await page.setViewportSize({ width: 760, height: 900 });
await openLookup();
await page.screenshot({ path: info.outputPath("completion-documentation.png"), animations: "disabled" });
const narrow = await geometry();
expect(narrow.overlap).toBe(0);
expect(narrow.visible).toBe(true);
expect(narrow.inside).toBe(true);
expect(narrow.side).toBe("left");
await page.keyboard.press("Escape");
await expect(popup).toBeHidden();
await page.setViewportSize({ width: 1400, height: 900 });
await openLookup();
const wide = await geometry();
expect(wide.overlap).toBe(0);
expect(wide.visible).toBe(true);
expect(wide.inside).toBe(true);
expect(wide.side).toBe("right");
});
test("typing closes an open documentation tooltip", async ({ workbench: page }) => {
const editor = await openSample(page);
await page.evaluate(() => {
+91
Переглянути файл
@@ -0,0 +1,91 @@
import { expect, openFromTree, test } from "./fixtures";
for (const theme of ["light", "dark"] as const) {
test(`${theme}: toolbar icon buttons provide hover feedback without changing their layout or icons`, async ({
workbench: page,
}) => {
const gear = page.getByRole("button", { name: "IDE and Project Settings", exact: true });
await gear.click();
await page.getByRole("menuitem", { name: "Theme", exact: true }).hover();
await page
.getByRole("menuitemcheckbox", { name: `Islands ${theme === "light" ? "Light" : "Dark"}`, exact: true })
.click();
await expect(page.locator("html")).toHaveAttribute("data-theme", theme);
const toolbar = page.locator("header").first();
const disabledRun = toolbar.getByRole("button", { name: "Run", exact: true });
await expect(disabledRun).toBeDisabled();
await disabledRun.hover();
await expect(disabledRun).toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
await openFromTree(page, "App.tsx");
await page.locator("[data-run-chooser]").click();
await page.getByRole("option", { name: "Current File", exact: true }).click();
const project = page.getByRole("region", { name: "Project", exact: true });
const buttons = [
...["Select Opened File", "Expand All", "Collapse All", "Options", "Hide"].map((name) =>
project.getByRole("button", { name, exact: true }),
),
...[
"Run Current File",
"Debug Current File",
"More Actions",
"Search Everywhere",
"IDE and Project Settings",
].map((name) => toolbar.getByRole("button", { name, exact: true })),
];
for (const button of buttons) {
await page.mouse.move(700, 500);
const bounds = await button.boundingBox();
const iconColors = await button.locator("svg [fill], svg [stroke]").evaluateAll((nodes) =>
nodes.map((node) => {
const style = getComputedStyle(node);
return { fill: style.fill, stroke: style.stroke };
}),
);
await expect(button).toBeEnabled();
// Hover inside the hit target but outside its centred icon.
await button.hover({ position: { x: bounds!.width / 2, y: 1 } });
await expect(button).not.toHaveCSS("background-color", "rgba(0, 0, 0, 0)");
expect(await button.boundingBox()).toEqual(bounds);
if (/^(Run|Debug) Current File$/.test((await button.getAttribute("aria-label")) ?? "")) {
expect(
await button.locator("svg [fill], svg [stroke]").evaluateAll((nodes) =>
nodes.map((node) => {
const style = getComputedStyle(node);
return { fill: style.fill, stroke: style.stroke };
}),
),
).toEqual(iconColors);
}
await button.focus();
await page.keyboard.press("Shift+Tab");
await page.keyboard.press("Tab");
await expect(button).toBeFocused();
await expect(button).toHaveCSS("outline-style", "solid");
await expect(button).toHaveCSS("outline-width", "2px");
}
const expand = project.getByRole("button", { name: "Expand All", exact: true });
await expand.hover();
const hover = await expand.evaluate((button) => getComputedStyle(button).backgroundColor);
await page.mouse.down();
await expect(expand).not.toHaveCSS("background-color", hover);
await page.mouse.up();
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveAttribute("aria-expanded", "true");
await project.getByRole("button", { name: "Collapse All", exact: true }).click();
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveAttribute("aria-expanded", "false");
await project.getByRole("button", { name: "Options", exact: true }).click();
await expect(page.getByRole("menu", { name: "Project options", exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await toolbar.getByRole("button", { name: "More Actions", exact: true }).click();
await expect(page.getByRole("menuitem", { name: /^Edit Configurations…/ })).toBeVisible();
await page.keyboard.press("Escape");
await toolbar.getByRole("button", { name: "Search Everywhere", exact: true }).click();
await expect(page.getByRole("dialog", { name: "Search Everywhere", exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await project.getByRole("button", { name: "Hide", exact: true }).click();
await expect(project).toBeHidden();
});
}
+11
Переглянути файл
@@ -26,6 +26,17 @@ args = ["language-server"]
root-markers = ["composer.json", ".phpactor.json"]
install-hint = "Install phpactor (https://phpactor.readthedocs.io/en/master/usage/standalone.html)"
# Alternative with its own Laravel and Blade support. https://github.com/samehelhawary/phoxite
[[language-servers]]
name = "phoxite"
fallback = true
command = "phoxite-lsp"
args = []
root-markers = ["composer.json", "artisan", "index.php"]
# It answers the Laravel strings itself.
replaces = ["laravel-lsp"]
install-hint = "Install phoxite-lsp from https://github.com/samehelhawary/phoxite/releases and put it on PATH"
# Laravel projects only: hover, definition and completion inside
# config('…'), route('…') and view('…'). Last: Intelephense keeps PHP hover,
# rename and symbols. https://github.com/laravel/lsp
+1
Переглянути файл
@@ -358,6 +358,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_conflict_versions,
vcs::vcs_diff_text,
vcs::vcs_diff_hunks,
vcs::diff_external_tool,
vcs::vcs_stage_hunks,
vcs::vcs_clone,
vcs::vcs_init,
+15
Переглянути файл
@@ -518,6 +518,21 @@ pub async fn vcs_diff_hunks(app: AppHandle, old_text: String, new_text: String)
.expect("line diff panicked")
}
/// Show Diff in External Tool: starts the tool set in the global settings (never a
/// project's, which a cloned repository could carry) on the two sides, on this machine
/// (a remote window passes the sides as text).
#[tauri::command]
#[specta::specta]
pub async fn diff_external_tool(
state: State<'_, AppState>,
left: ExternalDiffSide,
right: ExternalDiffSide,
title: String,
) -> IdeResult<()> {
let settings = state.global_settings.effective().external_diff;
state.host.blocking(move || launch_external_diff(&settings, &left, &right, &title)).await
}
/// Stages only the selected hunks of a file's working-tree changes.
/// Indices refer to `vcs_diff_hunks(index_text, worktree_text)`.
#[tauri::command]
+2
Переглянути файл
@@ -72,6 +72,7 @@ cancel_task always project_host bin
clear_caches always desktop bindings async
clipboard_file_list always desktop bindings async
clipboard_has_files always desktop bindings sync
clipboard_has_image always desktop bindings sync
clipboard_image always desktop bindings async
clipboard_set_file_list always desktop bindings async
clipboard_text trusted desktop bindings async
@@ -175,6 +176,7 @@ deploy_server_root trusted project_host bin
deploy_sync trusted project_host bindings async
deploy_test_connection always project_host bindings async
deploy_upload trusted project_host bindings async
diff_external_tool always desktop bindings async
doc_close always project_host bindings async
doc_edit always project_host bindings async
doc_folding always project_host bindings async
+63 -1
Переглянути файл
@@ -750,6 +750,12 @@ export const commands = {
vcsDiffText: (path: string, staged: boolean) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_diff_text", { path, staged })),
/** Line hunks between two arbitrary texts (diff viewer, commit dialog). */
vcsDiffHunks: (oldText: string, newText: string) => __TAURI_INVOKE<LineHunk[]>("vcs_diff_hunks", { oldText, newText }),
/**
* Show Diff in External Tool: starts the tool set in the global settings (never a
* project's, which a cloned repository could carry) on the two sides, on this machine
* (a remote window passes the sides as text).
*/
diffExternalTool: (left: ExternalDiffSide, right: ExternalDiffSide, title: string) => typedError<null, IdeError>(__TAURI_INVOKE("diff_external_tool", { left, right, title })),
/**
* Stages only the selected hunks of a file's working-tree changes.
* Indices refer to `vcs_diff_hunks(index_text, worktree_text)`.
@@ -2264,6 +2270,18 @@ export type AgentSettings_Deserialize = {
smoothText?: boolean,
/** Conversations and the composer expand to the full width of the pane instead of staying in a centred column. */
fitWindowWidth?: boolean,
/** While the agent works, playful words fill the pauses in what it reports. */
playfulStatus?: boolean,
/**
* Seconds the agent reports nothing new before the playful words take over; 0 shows them
* from the start.
*/
playfulAfterSeconds?: number,
/**
* The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
* the built-in ones of that activity; an empty list keeps its status factual.
*/
playfulWords?: { [key in string]: string[] },
thinking?: ThinkingDisplay,
toolCalls?: ToolCallDisplay,
/** A tool call's output (a command's, a diff) is shown without opening it. */
@@ -2304,6 +2322,18 @@ export type AgentSettings_Serialize = {
smoothText: boolean,
/** Conversations and the composer expand to the full width of the pane instead of staying in a centred column. */
fitWindowWidth: boolean,
/** While the agent works, playful words fill the pauses in what it reports. */
playfulStatus: boolean,
/**
* Seconds the agent reports nothing new before the playful words take over; 0 shows them
* from the start.
*/
playfulAfterSeconds: number,
/**
* The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
* the built-in ones of that activity; an empty list keeps its status factual.
*/
playfulWords: { [key in string]: string[] },
thinking: ThinkingDisplay,
toolCalls: ToolCallDisplay,
/** A tool call's output (a command's, a diff) is shown without opening it. */
@@ -5070,6 +5100,26 @@ export type ExtensionPointInfo = {
contributors: string[],
};
/** Tools › Diff & Merge › External Diff Tools: a program that shows two files' differences. */
export type ExternalDiffSettings = {
/** Offer Show Diff in External Tool in diff viewers. */
enabled?: boolean,
/** The program to start. */
path?: string,
/** Its arguments: `%1` the left file, `%2` the right file, `%3` the diff's title. */
parameters?: string,
};
/** One side of the diff: a file on disk, or text written to a temporary file. */
export type ExternalDiffSide = {
/** A saved file, passed to the tool as it is. */
path: string | null,
/** Content without a file of its own (a revision, a text), written to a temporary file. */
text: string | null,
/** The temporary file's name; its extension lets the tool pick a syntax. */
name: string,
};
/** A formatter that runs outside the language servers, with its own settings group. */
export type ExternalFormatter = "prettier" | "oxfmt" | "ruff";
@@ -6943,6 +6993,7 @@ export type LanguagesSettings = {
ruby?: RubySettings,
markdown?: MarkdownSettings,
arduino?: ArduinoSettings,
zig?: ZigSettings,
};
/** What a freshly opened window should do once its frontend is up. */
@@ -7031,7 +7082,7 @@ export type Launch_Serialize = {
export type LibraryGroup = {
/** Display name, e.g. `Python 3.12 (.venv)`. */
name: string,
/** `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath`. */
/** `python` | `jdk` | `nodeModules` | `nodeCore` | `rust` | `cargo` | `go` | `goModules` | `maven` | `gradle` | `classpath` | `zig` | `zigPackages`. */
kind: string,
roots: LibraryRoot[],
};
@@ -9463,6 +9514,8 @@ export type RunSettings = {
/** Ask before closing a Run tab whose process is still running. */
confirmTerminate?: boolean,
showOnStart?: boolean,
/** New Run/Debug tabs start pinned: a later run doesn't take their place once finished. */
pinTabs?: boolean,
/** Grace period between interrupt and kill when stopping a process. */
terminationTimeoutMs?: number,
};
@@ -9750,6 +9803,8 @@ export type Settings_Deserialize = {
terminal?: TerminalSettings,
actionsOnSave?: ActionsOnSaveSettings,
externalTools?: ExternalTool[],
/** Tools › Diff & Merge › External Diff Tools. */
externalDiff?: ExternalDiffSettings,
/**
* Language servers / debug adapters at a user-chosen location, by the
* command the language definition launches (`elixir-ls`, `codelldb`).
@@ -9814,6 +9869,8 @@ export type Settings_Serialize = {
terminal: TerminalSettings,
actionsOnSave: ActionsOnSaveSettings,
externalTools: ExternalTool[],
/** Tools › Diff & Merge › External Diff Tools. */
externalDiff: ExternalDiffSettings,
/**
* Language servers / debug adapters at a user-chosen location, by the
* command the language definition launches (`elixir-ls`, `codelldb`).
@@ -10955,6 +11012,11 @@ export type Worktree = {
prunable: boolean,
};
export type ZigSettings = {
/** Directory holding the `zig` executable; empty = the one on `PATH`. */
zig?: string,
};
/* Tauri Specta runtime */
async function typedError<T, E>(result: Promise<T>): Promise<{ status: "ok"; data: T } | { status: "error"; error: E }> {
try {
+37 -12
Переглянути файл
@@ -4,11 +4,13 @@
* (view/FindBar.tsx). Highlighting is ours because CodeMirror only highlights
* while its own panel is open. Match positions found by the bar's counter are
* kept in `findMarks` for the overview lane. The search context (comments /
* string literals) and excluded matches filter matches through the query's
* `test`, so CodeMirror's own commands honour them too.
* string literals), excluded matches and "Search In Changes" (a diff's changed
* ranges) filter matches through the query's `test`, so CodeMirror's own commands
* honour them too.
*/
import {
EditorSelection,
Facet,
Prec,
StateEffect,
StateField,
@@ -93,16 +95,33 @@ export function isExcluded(state: EditorState, from: number, to: number): boolea
return (state.field(findExcluded, false) ?? []).some((x) => x.from === from && x.to === to);
}
type MatchTest = (match: string, state: EditorState, from: number, to: number) => boolean;
const tests = new Map<SearchContext, MatchTest>();
/**
* The changed ranges of a diff pane, for "Search In Changes"; editors outside a diff have none.
* Called per match, so providers read state the diff already keeps.
*/
export const findChangedRanges = Facet.define<
(state: EditorState) => readonly FindScope[],
((state: EditorState) => readonly FindScope[]) | null
>({ combine: (values) => values[0] ?? null });
/** One stable test per context, so equal options give equal queries (`SearchQuery.eq`). */
function testFor(context: SearchContext): MatchTest {
let test = tests.get(context);
function inChangedRange(state: EditorState, from: number, to: number): boolean {
const ranges = state.facet(findChangedRanges)?.(state) ?? [];
return ranges.some((r) => r.from <= from && to <= r.to);
}
type MatchTest = (match: string, state: EditorState, from: number, to: number) => boolean;
const tests = new Map<string, MatchTest>();
/** One stable test per filter, so equal options give equal queries (`SearchQuery.eq`). */
function testFor(context: SearchContext, inChanges: boolean): MatchTest {
const key = `${context}:${inChanges}`;
let test = tests.get(key);
if (!test) {
test = (_match, state, from, to) =>
!isExcluded(state, from, to) && (context === "any" || contextAccepts(context, literalKindAt(state, from)));
tests.set(context, test);
!isExcluded(state, from, to) &&
(!inChanges || inChangedRange(state, from, to)) &&
(context === "any" || contextAccepts(context, literalKindAt(state, from)));
tests.set(key, test);
}
return test;
}
@@ -215,7 +234,13 @@ export interface FindOptions {
preserveCase?: boolean;
}
export function makeQuery(o: FindOptions) {
/** A bar's query: its options, plus filters that belong to what it searches rather than the last search. */
export interface FindQueryOptions extends FindOptions {
/** Only matches inside a diff's changed ranges (`findChangedRanges`). */
inChanges?: boolean;
}
export function makeQuery(o: FindQueryOptions) {
return new SearchQuery({
search: o.search,
// Plain-text search and replace are literal (`\n` is not a newline), as in IDEA.
@@ -224,11 +249,11 @@ export function makeQuery(o: FindOptions) {
wholeWord: o.wholeWord,
regexp: o.regexp,
replace: o.replace,
test: testFor(o.context ?? "any"),
test: testFor(o.context ?? "any", !!o.inChanges),
});
}
export function setQuery(view: EditorView, o: FindOptions) {
export function setQuery(view: EditorView, o: FindQueryOptions) {
const q = makeQuery(o);
if (q.eq(getSearchQuery(view.state))) return;
view.dispatch({ effects: setSearchQuery.of(q) });
+18
Переглянути файл
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { getIndentation, indentUnit } from "@codemirror/language";
import { completedSyntaxTree } from "@/test/syntax";
import { classHighlighter, highlightTree } from "@lezer/highlight";
import { findLanguageDescription, loadSupport, loadedSupport } from "./languages";
@@ -81,6 +82,23 @@ describe("frontend string interpolation", () => {
expect(out.some((t) => t.text.includes("{brace}") && t.style === "tok-string")).toBe(true);
});
it.each(["Kotlin", "Scala", "Dart", "Groovy", "C#"])(
"%s indents brackets opened after a string from the line's indentation",
async (mode) => {
const support = await loadSupport(findLanguageDescription(mode, "")!);
const doc = 'f(\n pair("a", g(\n x\n )),\n)';
const state = EditorState.create({
doc,
extensions: [support!, indentUnit.of(" "), EditorState.tabSize.of(4)],
});
completedSyntaxTree(state);
const indent = (line: number) => getIndentation(state, state.doc.line(line).from);
expect(indent(3)).toBe(8);
// C#'s mode leaves a closing bracket's indentation to the editor.
if (mode !== "C#") expect(indent(4)).toBe(4);
},
);
it("keeps Groovy dotted interpolation in code", async () => {
const out = await tokens("Groovy", '"$person.name tail"');
expect(out).toContainEqual(expect.objectContaining({ text: "name", style: "tok-variableName" }));
+5 -1
Переглянути файл
@@ -114,7 +114,11 @@ export function interpolationParser<S>(base: StreamParser<S>, dialect: Interpola
}
if (opening && style !== "comment" && style !== "string.special") {
stream.pos = from + opening.length;
base.token(new StringStream('""', 4, state.indentUnit), frame.code);
// Let the base tokenizer see an empty string at the literal's own column: a stream
// at column 0 would read as a new line and reset the base's line indentation.
const empty = new StringStream(stream.string.slice(0, from) + '""', 4, state.indentUnit);
empty.pos = empty.start = from;
base.token(empty, frame.code);
frame.literal = {
quote,
braces,
+8
Переглянути файл
@@ -28,6 +28,14 @@ describe("Sort Lines / Reverse Lines", () => {
expect(apply(doc, sel, sortLinesSpec)).toBe("a\nb\n--\nc\nd");
});
it("sorts by code unit, uppercase before lowercase, as IDEA does", () => {
const doc = '"github:opentofu/tofu-ls" = "0.5"\n"github:PowerShell/PowerShellEditorServices" = "4.7"';
expect(apply(doc, undefined, sortLinesSpec)).toBe(
'"github:PowerShell/PowerShellEditorServices" = "4.7"\n"github:opentofu/tofu-ls" = "0.5"',
);
expect(apply("b\nB\na\nA\n_\n1", undefined, sortLinesSpec)).toBe("1\nA\nB\n_\na\nb");
});
it("does nothing for a single line or an already sorted block", () => {
expect(apply("only", undefined, sortLinesSpec)).toBeNull();
expect(apply("a\nb", undefined, sortLinesSpec)).toBeNull();
+4 -3
Переглянути файл
@@ -7,8 +7,6 @@ import {
type TransactionSpec,
} from "@codemirror/state";
const collator = new Intl.Collator(undefined, { numeric: false, sensitivity: "variant" });
/** Line blocks the command applies to: one per non-empty selection range, or the document. */
function blocks(state: EditorState): Array<{ from: number; to: number }> {
const ranges = state.selection.ranges.filter((r) => !r.empty);
@@ -59,8 +57,11 @@ function rewrite(
};
}
/** Plain UTF-16 code-unit order, as IDEA sorts (`String.compareTo`): every uppercase letter before every lowercase one. */
const byCodeUnit = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
export function sortLinesSpec(state: EditorState): TransactionSpec | null {
return rewrite(state, (lines) => [...lines].sort((a, b) => collator.compare(a, b)), "input.sort");
return rewrite(state, (lines) => [...lines].sort(byCodeUnit), "input.sort");
}
export function reverseLinesSpec(state: EditorState): TransactionSpec | null {
+19 -6
Переглянути файл
@@ -99,6 +99,8 @@ export interface FindTarget {
/** Still open: an unmount that isn't a close (React's dev-mode remount) keeps the highlights. */
isOpen(): boolean;
results?(options: FindOptions): FindResultsSource | null;
/** A diff pane's "Search In Changes" filter, kept by the diff (not the last search). */
inChanges?: { get(): boolean; set(on: boolean): void };
}
const activeTab = (paneId: string) => useTabs.getState().panes[paneId]?.active ?? null;
@@ -373,6 +375,13 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
const [historyMenu, setHistoryMenu] = useState<"find" | "replace" | null>(null);
const [filterMenu, setFilterMenu] = useState(false);
const setOpts = (patch: Partial<FindOptions>) => updateOptions(id, () => patch);
// Search In Changes applies to finding only, as in IDEA: the replace bar searches the whole side.
const [inChangesOn, setInChangesOn] = useState(() => !!target.inChanges?.get());
const inChanges = !!target.inChanges && !replace && inChangesOn;
const toggleInChanges = () => {
target.inChanges?.set(!inChangesOn);
setInChangesOn(!inChangesOn);
};
useLayoutEffect(() => {
panelTargets.set(id, target);
@@ -421,15 +430,16 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
// Push the query into the editor. Like IDEA, only a change of the query (typing, options)
// selects the nearest match: showing the bar again over its editor leaves the caret alone.
const shown = useRef<{ target: FindTarget; version: unknown; opts: FindOptions } | null>(null);
const shown = useRef<{ target: FindTarget; version: unknown; opts: FindOptions; inChanges: boolean } | null>(null);
useEffect(() => {
const view = target.view();
if (!view) return;
const prev = shown.current;
const changed = prev?.target === target && prev.version === version && prev.opts !== opts;
shown.current = { target, version, opts };
const changed =
prev?.target === target && prev.version === version && (prev.opts !== opts || prev.inChanges !== inChanges);
shown.current = { target, version, opts, inChanges };
const valid = !opts.regexp || regexValid(opts.search);
setQuery(view, valid ? opts : { ...opts, search: "" });
setQuery(view, valid ? { ...opts, inChanges } : { ...opts, search: "" });
view.dispatch({ effects: setFindOpen.of(true) });
if (changed && valid && opts.search && useFindPreferences.getState().scrollToResults) {
const from = view.state.selection.main.from;
@@ -437,7 +447,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
findNext(view);
}
recount(target);
}, [opts, target, version]);
}, [opts, target, version, inChanges]);
// Keep the counter current while the document / selection changes.
useEffect(() => {
@@ -564,6 +574,9 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
checked: scoped || undefined,
run: () => toggleScope(target),
},
...(target.inChanges && !replace
? [{ label: "Search In Changes", checked: inChangesOn || undefined, run: toggleInChanges }]
: []),
{ kind: "separator" },
{ kind: "header", label: "Search Scope" },
...SEARCH_CONTEXTS.map((c) => ({
@@ -688,7 +701,7 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
icon="filter"
title="Filter Search Results"
size="small"
pressed={scoped || opts.context !== "any"}
pressed={scoped || inChanges || opts.context !== "any"}
onClick={() => setFilterMenu(true)}
/>
<IconButton ref={moreRef} icon="more" title="More" size="small" onClick={() => setMoreMenu(true)} />
+53
Переглянути файл
@@ -22,6 +22,7 @@ import {
explicitCompletion,
makeCompletion,
matchRanges,
positionCompletionInfo,
sortAlphabetically,
} from "./completion";
import {
@@ -659,6 +660,58 @@ describe("explicit completion", () => {
});
});
describe("documentation beside the lookup", () => {
const view = {} as EditorView;
const space = { left: 0, top: 0, right: 1200, bottom: 800 };
const option = { left: 100, right: 300, top: 120, bottom: 144 };
const info = { left: 0, right: 400, top: 0, bottom: 300 };
const beside = { left: 100, right: 520, top: 100, bottom: 400 };
const originalWidth = document.documentElement.clientWidth;
afterEach(() => {
Object.defineProperty(document.documentElement, "clientWidth", { value: originalWidth, configurable: true });
});
/** `windowWidth` is the room the pane may use; the editor's own box does not limit it. */
function place(list: typeof beside, windowWidth = 1200, bounds = space) {
Object.defineProperty(document.documentElement, "clientWidth", { value: windowWidth, configurable: true });
return positionCompletionInfo(view, list, option, info, bounds);
}
it("sits right of the list when there is room, top edges aligned", () => {
const pos = place(beside);
expect(pos.class).toBe("cm-completionInfo-right");
expect(pos.style).toContain("top: 0");
expect(pos.style).toContain("left: calc(100% + 6px)");
expect(pos.style).toContain("max-width: 440px");
expect(pos.style).toContain("max-height: 320px");
});
it("moves to the left of the list when the right side is narrower", () => {
const pos = place({ ...beside, left: 700, right: 1120 });
expect(pos.class).toBe("cm-completionInfo-left");
expect(pos.style).toContain("right: calc(100% + 6px)");
});
it("narrows the pane to the room the window has, not the editor's", () => {
// A 620px-wide editor would leave 94px; the window leaves 274px.
const pos = place(beside, 800, { ...space, right: 620 });
expect(pos.class).toBe("cm-completionInfo-right");
expect(pos.style).toContain("max-width: 274px");
});
it("keeps a readable width in a narrow window rather than covering the list", () => {
const pos = place(beside, 620);
expect(pos.class).toBe("cm-completionInfo-right");
expect(pos.style).toContain("max-width: 220px");
});
it("caps the height to the room below the list and to 320px", () => {
expect(place({ ...beside, top: 700, bottom: 780 }).style).toContain("max-height: 100px");
expect(place(beside, 1200, { ...space, bottom: 600 }).style).toContain("max-height: 320px");
});
});
describe("completion footer", () => {
let view: EditorView | null = null;
afterEach(() => {
+39 -1
Переглянути файл
@@ -25,7 +25,7 @@ import {
type CompletionSource,
} from "@codemirror/autocomplete";
import { EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state";
import { EditorView, ViewPlugin, keymap, type ViewUpdate } from "@codemirror/view";
import { EditorView, ViewPlugin, keymap, type Rect, type ViewUpdate } from "@codemirror/view";
import {
call,
commands,
@@ -159,6 +159,43 @@ function resetLookupDocs() {
docWaiters.clear();
}
const DOC_MIN_WIDTH = 220;
const DOC_MAX_WIDTH = 440;
const DOC_MAX_HEIGHT = 320;
const DOC_GAP = 6;
/**
* Places the documentation beside the lookup, on whichever side has more room,
* with the two popups' top edges aligned. Room is measured to the window's
* edges, so a narrow editor still has space for a readable pane; when even the
* window is too narrow, the pane keeps a readable width rather than covering the
* options.
*/
export function positionCompletionInfo(
_view: EditorView,
list: Rect,
_option: Rect,
_info: Rect,
space: Rect,
): { style: string; class: string } {
const windowWidth = document.documentElement.clientWidth;
const rightRoom = windowWidth - list.right - DOC_GAP;
const leftRoom = list.left - DOC_GAP;
const side = rightRoom >= leftRoom ? "right" : "left";
const room = side === "right" ? rightRoom : leftRoom;
const width = Math.max(DOC_MIN_WIDTH, Math.min(DOC_MAX_WIDTH, room));
return {
class: `cm-completionInfo-${side}`,
style: [
"top: 0",
// `left`/`right` names the side the pane sits on; the offset goes on the opposite edge.
`${side === "right" ? "left" : "right"}: calc(100% + ${DOC_GAP}px)`,
`max-width: ${width}px`,
`max-height: ${Math.min(DOC_MAX_HEIGHT, space.bottom - list.top)}px`,
].join("; "),
};
}
/**
* F1 while the lookup is open: shows the selected item's docs beside it
* (`shown`), or reports that they are already showing (`showing`) so the
@@ -867,6 +904,7 @@ export function completionExtension() {
);
},
tooltipClass: () => "cm-lsp-completion",
positionInfo: positionCompletionInfo,
}),
completionFooter,
lookupTracker,
+3 -1
Переглянути файл
@@ -109,7 +109,8 @@ export const lspTheme = EditorView.theme({
// (gutter + project sidebar) keeps the word well clear of that edge.
marginLeft:
"calc(-1 * (1px + var(--cm-completion-edge) + var(--cm-completion-inset) + var(--cm-completion-icon) + var(--cm-completion-gap)))",
overflow: "hidden",
// No overflow clipping: CodeMirror nests the documentation pane in this box and
// positions it outside it (see `positionCompletionInfo`). The footer rounds itself.
},
".cm-tooltip.cm-tooltip-autocomplete.cm-lsp-completion > ul": {
fontFamily: "var(--openidea-editor-font, var(--font-mono))",
@@ -194,6 +195,7 @@ export const lspTheme = EditorView.theme({
whiteSpace: "nowrap",
gap: "12px",
justifyContent: "space-between",
borderRadius: "0 0 calc(var(--radius-popup) - 1px) calc(var(--radius-popup) - 1px)",
},
".cm-lsp-completion-sort": {
padding: "0",
+25 -2
Переглянути файл
@@ -6,7 +6,7 @@ import { HomeEditor } from "./HomeEditor";
import homeStyles from "./Home.module.css";
import { HOME, disconnect, savedDraft, updateComposer, useAgents } from "./store";
const backend = vi.hoisted(() => ({ providers: [] as AgentProvider[], create: vi.fn() }));
const backend = vi.hoisted(() => ({ providers: [] as AgentProvider[], create: vi.fn(), probe: vi.fn() }));
const ok = <T,>(data: T) => Promise.resolve({ status: "ok", data });
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
@@ -22,7 +22,7 @@ vi.mock("@/platform/ipc", async (original) => ({
retryAtMs: null,
error: null,
}),
agentProbe: () => ok(null),
agentProbe: (provider: string, refresh: boolean) => backend.probe(provider, refresh),
vcsBranchInfo: () => ok({ head: "main" }),
vcsBranches: () => ok([]),
agentCreate: (req: NewAgentTask) => backend.create(req),
@@ -47,6 +47,7 @@ const option = (id: string, category: string, values: string[], current: string)
beforeEach(() => {
disconnect();
backend.create.mockReset().mockImplementation((req: NewAgentTask) => ok({ id: "new", config: req.config }));
backend.probe.mockReset().mockImplementation(() => ok(null));
backend.providers = [
{
id: "fake",
@@ -166,3 +167,25 @@ it("applies fitWidth on the New Task page only when fitWindowWidth is enabled",
useProject.setState({ settings });
}
});
it("refreshes the displayed agent version after a CLI upgrade when the window regains focus", async () => {
let installed = "18.20.0";
let cached = installed;
backend.probe.mockImplementation((provider: string, refresh: boolean) => {
if (refresh) cached = installed;
return ok({ provider, name: "omp", version: cached, protocol: "ACP v1", error: null });
});
render(<HomeEditor />);
await screen.findByText("omp · 18.20.0 · ACP v1");
installed = "18.20.2";
fireEvent(window, new Event("focus"));
await screen.findByText("omp · 18.20.2 · ACP v1");
});
it("does not reuse a previous page's cached agent version when opened again", async () => {
backend.probe.mockImplementation((provider: string, refresh: boolean) =>
ok({ provider, name: "omp", version: refresh ? "18.20.2" : "18.20.0", protocol: "ACP v1", error: null }),
);
render(<HomeEditor />);
await screen.findByText("omp · 18.20.2 · ACP v1");
});
+20 -9
Переглянути файл
@@ -82,7 +82,8 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
}, [root, project?.workspace]);
const provider = providers.find((p) => p.id === draft.provider) ?? providers[0];
const probe = useProbe(provider?.installed ? provider.id : null, provider?.command);
const shown = useEditorShown();
const probe = useProbe(provider?.installed ? provider.id : null, provider?.command, shown);
const catalog = useAgents((s) => s.modelCatalogs.get(provider?.id ?? ""));
const requestingModels = useAgents((s) => s.modelRequests.has(provider?.id ?? ""));
const launch = provider && JSON.stringify([provider.program, provider.args, provider.env, provider.command]);
@@ -96,7 +97,6 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
const { defaults, fitWindowWidth } = useAgentSettings();
const config = draftConfig(provider, draft, (provider && defaults[provider.id]) || {});
const homeRoot = useRef<HTMLDivElement>(null);
const shown = useEditorShown();
const unavailableModel = config.some(
(o) =>
o.category === "model" &&
@@ -293,18 +293,29 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
);
}
/** What the agent reports about itself when it starts (no session is opened), once per agent. */
function useProbe(provider: string | null, command?: string): AgentProbe | null {
/** Rechecks the installed agent when this page is shown or its window regains focus; opens no session. */
function useProbe(provider: string | null, command: string | undefined, shown: boolean): AgentProbe | null {
const [probe, setProbe] = useState<AgentProbe | null>(null);
useEffect(() => {
if (!provider) return;
if (!provider || !shown) return;
let live = true;
call(commands.agentProbe(provider, false))
.then((p) => live && setProbe(p))
.catch(() => {});
let pending = false;
const refresh = () => {
if (pending) return;
pending = true;
call(commands.agentProbe(provider, true))
.then((p) => live && setProbe(p))
.catch(() => {})
.finally(() => {
pending = false;
});
};
refresh();
window.addEventListener("focus", refresh);
return () => {
live = false;
window.removeEventListener("focus", refresh);
};
}, [provider, command]);
}, [provider, command, shown]);
return probe?.provider === provider ? probe : null;
}
+10
Переглянути файл
@@ -1031,6 +1031,16 @@
color: var(--fg-muted);
}
/* Announced to screen readers, not shown: the fact behind a playful status. */
.srOnly {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.retrying {
color: var(--warning);
}
+67 -3
Переглянути файл
@@ -86,6 +86,16 @@ import { ImagePreview, imageSrc } from "./ImagePreview";
import { useAgentSettings } from "./agentSettings";
import { foldedTurns, summarizeWork, workParts, type FoldedTurn, type WorkSummary } from "./timeline";
import { useRevealedText } from "./reveal";
import {
ACTIVITY_STATUS,
PLAYFUL_MIN_MS,
PLAYFUL_WORD_MS,
PLAYFUL_WORDS,
activityOf,
playfulIndex,
progressKey,
type Activity,
} from "./workingStatus";
import { AgentReply, MessageActions, ReplyActions } from "./AgentReply";
import {
commandPrefix,
@@ -2685,27 +2695,81 @@ function WorkingRow({
return (
<div className={styles.working} role="status">
<Spinner size={12} />
<T>{subagent.status === "needsInput" ? "Waiting for your answer…" : "Working…"}</T>
{subagent.status === "needsInput" ? (
<T>Waiting for your answer…</T>
) : (
<WorkingLabel turn={entries ?? []} seed={subagent.startedMs ?? 0} />
)}
{subagent.startedMs != null && <Elapsed since={subagent.startedMs} />}
</div>
);
}
if (task.status !== "running" && task.status !== "starting") return null;
if (entries?.some((e) => e.type === "permission" && !e.chosen && !e.questions?.length)) return null;
const lastUser = entries?.findLast((e): e is UserEntry => e.type === "user");
const userAt = entries?.findLastIndex((e) => e.type === "user") ?? -1;
const lastUser = userAt >= 0 ? (entries![userAt] as UserEntry) : undefined;
return (
<div className={styles.working} role="status">
<Spinner size={12} />
{task.retry ? (
<Retrying retry={task.retry} />
) : task.status === "starting" ? (
<T>Starting the agent…</T>
) : (
<T>{task.status === "starting" ? "Starting the agent…" : "Working…"}</T>
<WorkingLabel turn={entries?.slice(userAt + 1) ?? []} seed={lastUser?.sentMs ?? 0} />
)}
{lastUser?.sentMs != null && !lastUser.doneMs && <Elapsed since={lastUser.sentMs} />}
</div>
);
}
/**
* What the agent is doing, said by the activity's playful words in turns (the user's own, else the
* built-in ones) from the start, or once it has reported nothing new for the user's quiet time;
* screen readers hear only the fact. A word stays its full time while it still fits what the agent
* does, and a little while when it no longer does, so the row never flickers.
*/
function WorkingLabel({ turn, seed }: { turn: AgentEntry[]; seed: number }) {
const tx = useTx();
const { playfulStatus, playfulAfterSeconds, playfulWords } = useAgentSettings();
const now = useNow(1000);
const key = progressKey(turn);
const [progress, setProgress] = useState({ key, at: now });
if (progress.key !== key) setProgress({ key, at: now });
// The word on screen, and how many the turn has shown, so the next one continues the order.
const [playful, setPlayful] = useState<{ shown: number; word: PlayfulWord | null }>({ shown: 0, word: null });
const activity = activityOf(turn);
const kind = activity ?? "working";
const fact = tx(ACTIVITY_STATUS[kind]);
const own = playfulWords[kind];
const words = own ?? PLAYFUL_WORDS[kind];
const due = words.length > 0 && (!activity || now - progress.at >= playfulAfterSeconds * 1000);
const current = playful.word;
const fits = due && current?.kind === kind;
const stays = current && playfulStatus && now - current.since < (fits ? PLAYFUL_WORD_MS : PLAYFUL_MIN_MS);
let next = playful;
if (!stays && playfulStatus && due) {
const text = words[playfulIndex(words.length, seed, playful.shown)]!;
next = { shown: playful.shown + 1, word: { text, kind, own: !!own, since: now } };
} else if (!stays && current) next = { shown: playful.shown, word: null };
if (next !== playful) setPlayful(next);
if (!next.word) return fact;
return (
<>
<span aria-hidden>{next.word.own ? next.word.text : tx(next.word.text)}</span>
<span className={styles.srOnly}>{fact}</span>
</>
);
}
/** A playful word for `kind` on screen since `since`: the user's own as written, else a built-in one to translate. */
interface PlayfulWord {
text: string;
kind: Activity;
own: boolean;
since: number;
}
/** The approval the agent waits for, with its answers on 1, 2, 3… */
function PendingPermission({ task, entry }: { task: AgentTask; entry: PermissionEntry }) {
const ref = useRef<HTMLDivElement>(null);
+73
Переглянути файл
@@ -0,0 +1,73 @@
.body {
display: flex;
flex-direction: column;
gap: 10px;
height: 100%;
min-height: 0;
}
.notice {
margin: 0;
color: var(--fg-muted);
font-size: var(--fs-small);
overflow-wrap: anywhere;
}
.activity {
display: flex;
align-items: center;
gap: 8px;
}
.after {
display: flex;
align-items: center;
gap: 8px;
}
.seconds {
width: 64px;
font-variant-numeric: tabular-nums;
}
.items {
flex: 1;
min-height: 120px;
display: flex;
flex-direction: column;
gap: 4px;
padding: 8px;
overflow: auto;
border: 1px solid var(--border-strong);
border-radius: var(--radius-control);
}
.item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 6px;
padding: 4px 8px;
background: var(--bg-subtle);
border-radius: var(--radius-control);
}
.word {
overflow-wrap: anywhere;
}
.empty {
color: var(--fg-muted);
font-size: var(--fs-small);
}
.add {
display: flex;
align-items: center;
gap: 6px;
}
.input {
flex: 1;
min-width: 0;
}
+147
Переглянути файл
@@ -0,0 +1,147 @@
/**
* Settings › Agents › Working Status: whether the status under a conversation turns playful, after
* how long without news, and the playful words of each activity, the built-in ones until the user
* writes their own.
*/
import { useId, useState } from "react";
import { useTx } from "@/platform/i18n";
import { PLAYFUL_AFTER_LIMITS } from "@/platform/agentStatus";
import { Button, Checkbox, IconButton, Input, Select, T, type SelectOption } from "@/ui";
import { useSettingsForm } from "@/workbench/contributions";
import { AGENT_SETTINGS_DEFAULTS } from "./agentSettings";
import { ACTIVITIES, ACTIVITY_STATUS, PLAYFUL_WORDS, type Activity } from "./workingStatus";
import styles from "./WorkingStatus.module.css";
export function WorkingStatusPage() {
const tx = useTx();
const form = useSettingsForm();
const playful =
(form.useValue("agents.playfulStatus") as boolean | undefined) ?? AGENT_SETTINGS_DEFAULTS.playfulStatus;
const own = (form.useValue("agents.playfulWords") ?? {}) as Record<string, string[]>;
const [activity, setActivity] = useState<Activity>("working");
const [draft, setDraft] = useState("");
const selectId = useId();
const custom = own[activity];
const words = custom ?? PLAYFUL_WORDS[activity].map((w) => tx(w));
const options: SelectOption<Activity>[] = ACTIVITIES.map((a) => ({
value: a,
label: ACTIVITY_STATUS[a],
detail: own[a] ? "Custom" : undefined,
}));
const setWords = (next: string[] | null) => {
const others = Object.fromEntries(Object.entries(own).filter(([a]) => a !== activity));
form.set("agents.playfulWords", next ? { ...others, [activity]: next } : others);
};
const add = () => {
const word = draft.trim();
if (!word) return;
setDraft("");
if (!words.includes(word)) setWords([...words, word]);
};
return (
<section className={styles.body} aria-label={tx("Working Status")}>
<p className={styles.notice}>
<T>
While the agent works, the line under the conversation says what it is doing. With playful words on, words for
what it does take turns there instead, from the start or once it reports nothing new for a while; screen
readers still hear the plain status.
</T>
</p>
<Checkbox
checked={playful}
onChange={(on) => form.set("agents.playfulStatus", on)}
label="Playful words while the agent works"
/>
<PlayfulAfter disabled={!playful} />
<div className={styles.activity}>
<label htmlFor={selectId}>
<T>While the status says</T>
</label>
<Select id={selectId} value={activity} options={options} onChange={setActivity} disabled={!playful} />
</div>
<div className={styles.items} role="list" aria-label={tx("Playful words")}>
{words.length === 0 && (
<div className={styles.empty}>
<T>No playful words: the status stays factual</T>
</div>
)}
{words.map((word, i) => (
<div key={`${i}:${word}`} className={styles.item} role="listitem">
<span className={styles.word}>{word}</span>
<IconButton
icon="close"
size="small"
title={tx`Remove ${word}`}
disabled={!playful}
onClick={() => setWords(words.filter((_, j) => j !== i))}
/>
</div>
))}
</div>
<div className={styles.add}>
<input
type="text"
className={styles.input}
value={draft}
disabled={!playful}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key !== "Enter") return;
// Enter adds the word; it does not press the dialog's OK.
e.preventDefault();
add();
}}
placeholder={tx("e.g. Reticulating splines…")}
aria-label={tx("New playful word")}
/>
<Button size="small" disabled={!playful} onClick={add}>
Add
</Button>
<Button size="small" disabled={!playful || !custom} onClick={() => setWords(null)}>
Restore Built-in Words
</Button>
</div>
</section>
);
}
/** Seconds without news before the status turns playful; invalid text is flagged and reverted on blur. */
function PlayfulAfter({ disabled }: { disabled: boolean }) {
const tx = useTx();
const form = useSettingsForm();
const value =
(form.useValue("agents.playfulAfterSeconds") as number | undefined) ?? AGENT_SETTINGS_DEFAULTS.playfulAfterSeconds;
const [draft, setDraft] = useState<string | null>(null);
const id = useId();
const { min, max } = PLAYFUL_AFTER_LIMITS;
const parse = (text: string) => {
const n = /^\s*\d+\s*$/.test(text) ? Number(text) : NaN;
return n >= min && n <= max ? n : null;
};
const invalid = draft !== null && parse(draft) === null;
return (
<div className={styles.after}>
<label htmlFor={id}>
<T>Start after the agent reports nothing new for</T>
</label>
<Input
id={id}
className={styles.seconds}
inputMode="numeric"
value={draft ?? String(value)}
invalid={invalid}
disabled={disabled}
title={invalid ? tx`Enter a value between ${min} and ${max}` : undefined}
onChange={(e) => {
setDraft(e.target.value);
const n = parse(e.target.value);
if (n !== null) form.set("agents.playfulAfterSeconds", n);
}}
onBlur={() => setDraft(null)}
/>
<T>seconds</T>
</div>
);
}
+3
Переглянути файл
@@ -13,6 +13,9 @@ export const AGENT_SETTINGS_DEFAULTS: ResolvedAgentSettings = {
foldTurns: true,
smoothText: true,
fitWindowWidth: false,
playfulStatus: false,
playfulAfterSeconds: 0,
playfulWords: {},
thinking: "auto",
toolCalls: "grouped",
expandToolOutput: false,
+10
Переглянути файл
@@ -32,6 +32,7 @@ import {
SESSION_KIND,
TASK_DRAG,
TOOL_WINDOW,
WORKING_STATUS_PAGE,
providerIcon,
} from "./model";
import { sendPaths, sendSelection, trackEditorCopies } from "./references";
@@ -65,6 +66,15 @@ export function activateSettingsPages(): () => void {
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
}),
registerSettingsPage({
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)),
}),
registerSettingsPage({
id: MCP_PAGE,
title: "External MCP Servers",
+2
Переглянути файл
@@ -15,6 +15,8 @@ export const AGENTS_GROUP = "Agents";
export const MCP_PAGE = "agents.mcpServers";
/** Settings › Agents › Command Permissions. */
export const POLICY_PAGE = "agents.policy";
/** Settings › Agents › Working Status: the playful words under a working conversation. */
export const WORKING_STATUS_PAGE = "agents.workingStatus";
export const sessionKey = (task: string) => `agent:${task}`;
+121 -1
Переглянути файл
@@ -22,6 +22,7 @@ import { useChangesOptions } from "./changesOptions";
import { taskActions } from "./taskActions";
import { replyActions } from "./replyActions";
import { focusedSession } from "./sessionFocus";
import { PLAYFUL_MIN_MS, PLAYFUL_WORD_MS, PLAYFUL_WORDS } from "./workingStatus";
import styles from "./Session.module.css";
import chipStyles from "./ReferenceChip.module.css";
import { caretOf, textOf, typeIn } from "./composerTesting";
@@ -484,11 +485,130 @@ describe("turn folding", () => {
// The turn isn't over: its latest message is no final reply yet.
expect(stream().querySelector(`.${styles.agentMessage} > .${styles.messageFooter}`)).toBeNull();
// What the agent is doing ends the conversation, below its latest output.
const working = within(stream()).getByText("Working…").closest(`.${styles.working}`);
const working = stream().querySelector(`.${styles.working}`);
expect(working).toHaveRole("status");
expect(stream().lastElementChild).toBe(working);
});
});
describe("working status", () => {
const running = (entries: AgentEntry[]) => {
backend.entries.set("A", [
{ type: "user", text: "Question", attachments: [], steered: false, sentMs: 1000, doneMs: null },
...entries,
]);
useAgents.setState({
entries: new Map(backend.entries),
tasks: new Map(useAgents.getState().tasks).set("A", {
...useAgents.getState().tasks.get("A")!,
status: "running",
}),
});
};
const playful = (status: HTMLElement) => status.querySelector("[aria-hidden]")?.textContent ?? null;
const playfulOn = (agents: object = {}) =>
useProject.setState({ settings: { agents: { playfulStatus: true, ...agents } } as never });
it("says plainly what the agent does by default", async () => {
vi.useFakeTimers();
running([tool("one", { status: "running" })]);
render(<SessionEditor input={input("A")} />);
await act(async () => {});
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_WORD_MS * 2));
const status = stream().querySelector<HTMLElement>(`.${styles.working}`)!;
expect(playful(status)).toBeNull();
expect(status).toHaveTextContent("Reading…");
});
it("is playful from the start, holds each word while the work goes on, and turns to the new work's words", async () => {
vi.useFakeTimers();
playfulOn();
running([tool("one", { status: "running" })]);
render(<SessionEditor input={input("A")} />);
await act(async () => {});
const status = stream().querySelector<HTMLElement>(`.${styles.working}`)!;
const word = playful(status);
expect(PLAYFUL_WORDS.reading).toContain(word);
// Screen readers still hear the fact.
expect(status.querySelector(`.${styles.srOnly}`)).toHaveTextContent("Reading…");
// More of the same work keeps the word its full time.
running([tool("one", { status: "running" }), tool("two", { status: "running" })]);
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_WORD_MS - 1000));
expect(playful(status)).toBe(word);
await act(() => vi.advanceTimersByTimeAsync(1000));
const second = playful(status);
expect(PLAYFUL_WORDS.reading.filter((w) => w !== word)).toContain(second);
// New work leaves the word a moment, then says the new work playfully too.
running([tool("one", { status: "running" }), { type: "agent", text: "Found it" }]);
await act(() => vi.advanceTimersByTimeAsync(1000));
expect(playful(status)).toBe(second);
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_MIN_MS - 1000));
expect(PLAYFUL_WORDS.writing).toContain(playful(status));
expect(status.querySelector(`.${styles.srOnly}`)).toHaveTextContent("Writing…");
});
it("with a quiet time, is factual until the agent reports nothing new for it, and again on progress", async () => {
vi.useFakeTimers();
playfulOn({ playfulAfterSeconds: 10 });
running([tool("one", { status: "running" })]);
render(<SessionEditor input={input("A")} />);
await act(async () => {});
const status = stream().querySelector<HTMLElement>(`.${styles.working}`)!;
expect(status).toHaveTextContent("Reading…");
expect(playful(status)).toBeNull();
await act(() => vi.advanceTimersByTimeAsync(9000));
expect(playful(status)).toBeNull();
await act(() => vi.advanceTimersByTimeAsync(1000));
const word = playful(status);
expect(PLAYFUL_WORDS.reading).toContain(word);
// Progress right after a word appeared leaves it a moment before the fact returns.
running([tool("one", { status: "running" }), { type: "agent", text: "Found it" }]);
await act(() => vi.advanceTimersByTimeAsync(1000));
expect(playful(status)).toBe(word);
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_MIN_MS - 1000));
expect(playful(status)).toBeNull();
expect(status).toHaveTextContent("Writing…");
});
it("keeps each word its full time however soon the status turns playful", async () => {
vi.useFakeTimers();
playfulOn({ playfulAfterSeconds: 1 });
running([tool("one", { status: "running" })]);
render(<SessionEditor input={input("A")} />);
await act(async () => {});
const status = stream().querySelector<HTMLElement>(`.${styles.working}`)!;
await act(() => vi.advanceTimersByTimeAsync(1000));
const word = playful(status);
expect(PLAYFUL_WORDS.reading).toContain(word);
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_WORD_MS - 1000));
expect(playful(status)).toBe(word);
await act(() => vi.advanceTimersByTimeAsync(1000));
expect(PLAYFUL_WORDS.reading.filter((w) => w !== word)).toContain(playful(status));
});
it("shows the user's own words of the activity, and none where they left the list empty", async () => {
vi.useFakeTimers();
playfulOn({ playfulWords: { reading: ["Squinting really hard…"], working: [] } });
running([]);
render(<SessionEditor input={input("A")} />);
await act(async () => {});
const status = stream().querySelector<HTMLElement>(`.${styles.working}`)!;
// Nothing reported yet is `working`, whose list the user emptied.
expect(playful(status)).toBeNull();
expect(status).toHaveTextContent("Working…");
running([tool("one", { status: "running" })]);
await act(() => vi.advanceTimersByTimeAsync(1000));
expect(playful(status)).toBe("Squinting really hard…");
await act(() => vi.advanceTimersByTimeAsync(PLAYFUL_WORD_MS));
expect(playful(status)).toBe("Squinting really hard…");
});
});
describe("opened runs", () => {
it("stay open when the finished turn folds them away and is opened again", async () => {
const asked = {
+158
Переглянути файл
@@ -0,0 +1,158 @@
/**
* The label of the row under a conversation while the agent works: what the turn's latest
* output says it is doing, and playful words while it reports nothing new (or nothing yet).
*/
import type { AgentEntry } from "@/bindings";
import { subagentWorking } from "./model";
/** How long one playful word stays while the agent still reports nothing new. */
export const PLAYFUL_WORD_MS = 8_000;
/** How long a playful word stays at least, even when the agent reports something new meanwhile. */
export const PLAYFUL_MIN_MS = 3_000;
/** What the agent can be doing, as the status tells it; `working` covers the rest. */
export const ACTIVITIES = [
"working",
"thinking",
"writing",
"reading",
"editing",
"deleting",
"moving",
"searching",
"running",
"fetching",
"subagent",
] as const;
export type Activity = (typeof ACTIVITIES)[number];
/** The factual status of each activity, also what screen readers hear while it is playful. */
export const ACTIVITY_STATUS: Record<Activity, string> = {
working: "Working…",
thinking: "Thinking…",
writing: "Writing…",
reading: "Reading…",
editing: "Editing…",
deleting: "Deleting…",
moving: "Moving files…",
searching: "Searching…",
running: "Running a command…",
fetching: "Fetching…",
subagent: "Running a subagent…",
};
/** The built-in playful words of each activity, until the user writes their own. */
export const PLAYFUL_WORDS: Record<Activity, readonly string[]> = {
working: [
"Untangling imports…",
"Explaining it to the rubber duck…",
"Herding semicolons…",
"Rebasing onto reality…",
"Measuring twice…",
"Sharpening the pencils…",
"Invalidating a cache…",
],
thinking: [
"Refactoring a hunch…",
"Garbage-collecting thoughts…",
"Compiling a plan…",
"Caching an insight…",
"Bisecting the problem…",
"Naming things…",
],
writing: [
"Counting brackets…",
"Settling tabs versus spaces…",
"Choosing words carefully…",
"Polishing the prose…",
"Drafting, redrafting…",
],
reading: [
"Reading the fine manual…",
"Following the breadcrumbs…",
"Walking the call stack…",
"Reading between the lines…",
"Skimming the source…",
],
editing: [
"Squinting at the diff…",
"Negotiating with the borrow checker…",
"Asking the linter nicely…",
"Nudging a semicolon…",
"Moving code around gently…",
],
deleting: ["Tidying up…", "Taking out the trash…", "Pruning dead code…", "Saying goodbye…"],
moving: ["Rearranging the furniture…", "Packing boxes…", "Finding a better home…"],
searching: ["Grepping the void…", "Chasing a null pointer…", "Looking under the couch…", "Searching high and low…"],
running: [
"Warming up the compiler…",
"Pressing Enter with confidence…",
"Watching the logs scroll…",
"Waiting on the shell…",
],
fetching: ["Waiting on the network…", "Downloading the internet…", "Following links…"],
subagent: ["Delegating…", "Consulting a colleague…", "Calling in reinforcements…", "Holding a quick stand-up…"],
};
const TOOL_ACTIVITY: Record<string, Activity> = {
read: "reading",
edit: "editing",
delete: "deleting",
move: "moving",
search: "searching",
execute: "running",
fetch: "fetching",
think: "thinking",
};
/** What the turn's latest entry says the agent is doing; null before it reports anything. */
export function activityOf(turn: readonly AgentEntry[]): Activity | null {
const last = turn.at(-1);
if (!last) return null;
switch (last.type) {
case "thought":
return "thinking";
case "agent":
return "writing";
case "tool":
return last.status === "pending" || last.status === "running"
? (TOOL_ACTIVITY[last.kind] ?? "working")
: "working";
case "subagent":
return subagentWorking(last.status) ? "subagent" : "working";
default:
return "working";
}
}
/** Changes whenever the agent reports something new in the turn: an entry, more text, a tool's progress. */
export function progressKey(turn: readonly AgentEntry[]): string {
const last = turn.at(-1);
const detail =
last?.type === "agent" || last?.type === "thought"
? last.text.length
: last?.type === "tool"
? `${last.status}:${last.output?.length ?? 0}`
: last?.type === "subagent"
? last.status
: "";
return `${turn.length}:${last?.type ?? ""}:${detail}`;
}
/**
* Which of `count` playful words is the `n`th to show in the turn that started at `seed`. Each turn
* goes through every word in an order of its own.
*/
export function playfulIndex(count: number, seed: number, n: number): number {
const order = Array.from({ length: count }, (_, i) => i);
let state = seed >>> 0;
for (let i = order.length - 1; i > 0; i--) {
// mulberry32
state = (state + 0x6d2b79f5) >>> 0;
let r = Math.imul(state ^ (state >>> 15), state | 1);
r ^= r + Math.imul(r ^ (r >>> 7), r | 61);
const j = ((r ^ (r >>> 14)) >>> 0) % (i + 1);
[order[i], order[j]] = [order[j]!, order[i]!];
}
return order[n % count]!;
}
+83
Переглянути файл
@@ -0,0 +1,83 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { fireEvent, render, screen, within } from "@testing-library/react";
import { SettingsFormContext } from "@/workbench/contributions";
import { useSettingsFormFor } from "@/features/settings/components/context";
import { closeSettings, openSettings, stagedValue, useSettingsDialog } from "@/features/settings/model/staging";
import { WORKING_STATUS_PAGE } from "./model";
import { WorkingStatusPage as Page } from "./WorkingStatusPage";
import { PLAYFUL_WORDS } from "./workingStatus";
function WorkingStatusPage() {
const form = useSettingsFormFor(WORKING_STATUS_PAGE, "global");
return (
<SettingsFormContext.Provider value={form}>
<Page />
</SettingsFormContext.Provider>
);
}
const staged = () => stagedValue(useSettingsDialog.getState(), "global", "agents.playfulWords");
const words = () =>
within(screen.getByRole("list", { name: "Playful words" }))
.queryAllByRole("listitem")
.map((item) => item.textContent);
/** The page with playful words turned on, so its word controls are enabled. */
function renderOn() {
render(<WorkingStatusPage />);
fireEvent.click(screen.getByRole("checkbox", { name: "Playful words while the agent works" }));
}
describe("Working Status settings", () => {
beforeEach(() => openSettings(WORKING_STATUS_PAGE));
afterEach(() => closeSettings());
it("is off by default, and turning it on enables the words", () => {
render(<WorkingStatusPage />);
const toggle = screen.getByRole("checkbox", { name: "Playful words while the agent works" });
expect(toggle).not.toBeChecked();
expect(screen.getByRole("textbox", { name: "New playful word" })).toBeDisabled();
fireEvent.click(toggle);
expect(stagedValue(useSettingsDialog.getState(), "global", "agents.playfulStatus")).toBe(true);
expect(screen.getByRole("textbox", { name: "New playful word" })).toBeEnabled();
});
it("turns the built-in words into the user's own on the first edit, and restores them", () => {
renderOn();
const builtIn = [...PLAYFUL_WORDS.working];
expect(words()).toEqual(builtIn);
fireEvent.click(screen.getByRole("button", { name: `Remove ${builtIn[0]}` }));
const input = screen.getByRole("textbox", { name: "New playful word" });
fireEvent.change(input, { target: { value: " Reticulating splines… " } });
// Enter adds the word and is not left to press the Settings dialog's OK.
expect(fireEvent.keyDown(input, { key: "Enter" })).toBe(false);
const own = [...builtIn.slice(1), "Reticulating splines…"];
expect(words()).toEqual(own);
expect(staged()).toEqual({ working: own });
fireEvent.click(screen.getByRole("button", { name: "Restore Built-in Words" }));
expect(staged()).toEqual({});
expect(words()).toEqual(builtIn);
});
it("keeps an emptied list, which leaves the status factual", () => {
renderOn();
for (const word of PLAYFUL_WORDS.working) fireEvent.click(screen.getByRole("button", { name: `Remove ${word}` }));
expect(staged()).toEqual({ working: [] });
expect(screen.getByText("No playful words: the status stays factual")).toBeInTheDocument();
});
it("saves the quiet time while the text is a valid number, and drops invalid text on blur", () => {
renderOn();
const after = () => stagedValue(useSettingsDialog.getState(), "global", "agents.playfulAfterSeconds");
const seconds = screen.getByRole("textbox", { name: "Start after the agent reports nothing new for" });
expect(seconds).toHaveValue("0");
fireEvent.change(seconds, { target: { value: "25" } });
expect(after()).toBe(25);
fireEvent.change(seconds, { target: { value: "601" } });
expect(seconds).toHaveAttribute("aria-invalid", "true");
expect(after()).toBe(25);
fireEvent.blur(seconds);
expect(seconds).toHaveValue("25");
});
});
+1 -1
Переглянути файл
@@ -284,7 +284,7 @@ async function openCliDiff(diff: { left: string; right: string }): Promise<void>
import("@/features/vcs/diffInput"),
import("@/features/vcs/compareData"),
]);
await openVcsDiff(compareFilesData(diff.left, diff.right));
await openVcsDiff({ ...compareFilesData(diff.left, diff.right), swappable: true });
}
/** Closes the project tabs on `side` of the `arg` tab (default: the current one), keeping that tab. */
+5 -3
Переглянути файл
@@ -85,7 +85,7 @@ export function UsagesTabs() {
id: String(t.id),
label: label(t),
closable: true,
icon: t.pinned ? "pin" : undefined,
pinned: t.pinned,
}))}
activeId={String(search.id)}
onSelect={(id) => useUsages.setState({ active: Number(id) })}
@@ -97,16 +97,18 @@ export function UsagesTabs() {
onContextMenu={(id, e) => {
const t = tabs.find((x) => x.id === Number(id));
if (!t) return;
// IDEA's content tab menu.
showContextMenu(e, [
{ id: "pin", label: t.pinned ? "Unpin Tab" : "Pin Tab", run: () => pinUsageTab(t.id, !t.pinned) },
{ kind: "separator" },
{ id: "close", label: "Close Tab", run: () => closeUsageTab(t.id) },
{ id: "closeAll", label: "Close All Tabs", run: () => tabs.forEach((o) => closeUsageTab(o.id)) },
{
id: "closeOthers",
label: "Close Other Tabs",
disabled: tabs.length < 2,
run: () => tabs.forEach((o) => o.id !== t.id && closeUsageTab(o.id)),
},
{ kind: "separator" },
{ id: "pin", label: t.pinned ? "Unpin Tab" : "Pin Tab", run: () => pinUsageTab(t.id, !t.pinned) },
]);
}}
/>
+24 -8
Переглянути файл
@@ -409,6 +409,23 @@ export function Grid(props: GridProps) {
const anchor = scrollRef.current?.querySelectorAll<HTMLElement>("[data-column-filter]")[sel!.c1];
if (anchor) props.onFilter!(sel!.c1, anchor);
},
canEditCell: () => {
if (!canEdit()) return false;
const n = norm(sel!);
return n.top === n.bottom && n.left === n.right && props.rowState?.(n.top) !== "deleted";
},
editCell: () => {
if (actions.canEditCell()) startEdit(sel!.r1, sel!.c1);
},
hasSelection: () => !!sel && !editing,
copy: (kind) => {
if (!actions.hasSelection()) return;
if (kind === "header") copy("tsv", true);
else if (kind === "rowsTsv") copy("tsv", true, true);
else if (kind === "rowsCsv") copy("csv", true, true);
else copy(kind, false);
},
selectedRows,
};
Object.assign((cellActions.current ??= {} as CellActions), actions);
});
@@ -529,20 +546,19 @@ export function Grid(props: GridProps) {
{
label: "Copy as",
submenu: [
{ label: "TSV", verbatim: true, run: () => copy("tsv", false) },
{ label: "CSV", verbatim: true, run: () => copy("csv", false) },
{ label: "One-Row", run: () => copy("onerow", false) },
{ kind: "action", action: "db.copyAsTsv", label: "TSV", arg: cellActions.current },
{ kind: "action", action: "db.copyAsCsv", label: "CSV", arg: cellActions.current },
{ kind: "action", action: "db.copyAsOneRow", label: "One-Row", arg: cellActions.current },
],
},
{ label: "Copy with Header", run: () => copy("tsv", true) },
{ label: "Copy Rows as TSV", run: () => copy("tsv", true, true) },
{ label: "Copy Rows as CSV", run: () => copy("csv", true, true) },
{ kind: "action", action: "db.copyWithHeader", arg: cellActions.current },
{ kind: "action", action: "db.copyRowsAsTsv", arg: cellActions.current },
{ kind: "action", action: "db.copyRowsAsCsv", arg: cellActions.current },
];
if (editable && onEdit) {
const n = norm(sel);
items.push(
{ kind: "separator" },
{ label: "Edit Cell", disabled: n.top !== n.bottom || n.left !== n.right, run: () => startEdit(n.top, n.left) },
{ kind: "action", action: "db.editCell", arg: cellActions.current },
{ kind: "action", action: "db.setCellNull", arg: cellActions.current },
{ kind: "action", action: "db.setCellDefault", arg: cellActions.current },
);
+81 -21
Переглянути файл
@@ -137,7 +137,8 @@ function readonlyNotice(reason: EditBlockReason): string {
}
/** IDEA's pager at the bottom of a result: |< < 1-500 of 501+ > >| and the page size; paging runs the query again. */
function Pager({ tab }: { tab: ResultTab }) {
/** The result tab's page position and the page moves it allows, shared by the pager and the `db.*Page` actions. */
function pagerOf(tab: ResultTab) {
const r = tab.outcome.result!;
const page = tab.page ?? 0;
const pageSize = tab.pageSize ?? Math.max(r.rows.length, 1);
@@ -154,6 +155,21 @@ function Pager({ tab }: { tab: ResultTab }) {
}
if (lastPage !== null && lastPage !== page) go(lastPage);
};
return {
page,
pageSize,
w,
canPage,
go,
goLast,
canPrevious: canPage && page > 0,
canNext: canPage && r.hasMore,
canLast: canPage && !((!r.hasMore && w.total !== null) || (w.total === null && !countable(tab))),
};
}
function Pager({ tab }: { tab: ResultTab }) {
const { page, pageSize, w, canPage, go, goLast, canPrevious, canNext, canLast } = pagerOf(tab);
const { first, last } = w;
const total = w.total === null ? `${w.last + 1}+` : String(w.total);
const sizes = PAGE_SIZES.includes(pageSize) ? PAGE_SIZES : [...PAGE_SIZES, pageSize].sort((a, b) => a - b);
@@ -162,15 +178,17 @@ function Pager({ tab }: { tab: ResultTab }) {
<IconButton
icon="page-first"
title="First Page"
shortcut={shortcutLabel("db.firstPage")}
size="small"
disabled={!canPage || page === 0}
disabled={!canPrevious}
onClick={() => go(0)}
/>
<IconButton
icon="chevron-left"
title="Previous Page"
shortcut={shortcutLabel("db.previousPage")}
size="small"
disabled={!canPage || page === 0}
disabled={!canPrevious}
onClick={() => go(page - 1)}
/>
<button
@@ -185,15 +203,17 @@ function Pager({ tab }: { tab: ResultTab }) {
<IconButton
icon="chevron-right"
title="Next Page"
shortcut={shortcutLabel("db.nextPage")}
size="small"
disabled={!canPage || !r.hasMore}
disabled={!canNext}
onClick={() => go(page + 1)}
/>
<IconButton
icon="page-last"
title="Last Page"
shortcut={shortcutLabel("db.lastPage")}
size="small"
disabled={!canPage || (!r.hasMore && w.total !== null) || (w.total === null && !countable(tab))}
disabled={!canLast}
onClick={() => void goLast()}
/>
<Select
@@ -365,6 +385,10 @@ function Result({ tab }: { tab: ResultTab }) {
return { ...e, deletes, inserts: e.inserts.filter((_, i) => !insertsGone.has(i)) };
});
const addRow = () => setEdits((e) => ({ ...e, inserts: [...e.inserts, new Map()] }));
const restoreRows = (rows: number[]) =>
setEdits((e) => ({ ...e, deletes: new Set([...e.deletes].filter((d) => !rows.includes(d))) }));
const dirty = hasEdits(edits);
const submitting = useSyncExternalStore(subscribeResults, () => !!r && submittingResults.has(r));
const busy = submitting || !!tab.busy;
@@ -397,6 +421,17 @@ function Result({ tab }: { tab: ResultTab }) {
}
};
const showExport = (at: { x: number; y: number }) =>
r &&
showContextMenu(
at,
exportMenu(
{ columns, rows: r.rows, driver, table: queryTable(text, { driver }) },
queryTable(text, { driver }),
extractor,
),
);
// Submit / Revert / Go to Column (⌘↩ / ⌥⌘Z / ⌘F12) reach the latest state through the handle, as in the table editor.
const canSubmit = editable && dirty && !busy;
const viewRef = useRef<HTMLDivElement>(null);
@@ -421,6 +456,30 @@ function Result({ tab }: { tab: ResultTab }) {
const rect = viewRef.current?.getBoundingClientRect();
if (view === "table" && rect) setColumnsAt({ x: rect.left + rect.width / 2, y: rect.top + 48 });
};
const pager = r ? pagerOf(tab) : null;
const rowsEditable = editable && !busy && view === "table";
handle.commands = pager
? {
reload: { enabled: () => !busy, run: () => void rerunResult(tab.id) },
firstPage: { enabled: () => pager.canPrevious, run: () => pager.go(0) },
previousPage: { enabled: () => pager.canPrevious, run: () => pager.go(pager.page - 1) },
nextPage: { enabled: () => pager.canNext, run: () => pager.go(pager.page + 1) },
lastPage: { enabled: () => pager.canLast, run: () => void pager.goLast() },
addRow: { enabled: () => editable && !busy, run: addRow },
exportData: {
enabled: () => true,
run: () => {
const rect = viewRef.current?.querySelector("[data-db-export]")?.getBoundingClientRect();
if (rect) showExport({ x: rect.left, y: rect.bottom });
},
},
deleteRows: { enabled: (rows) => rowsEditable && rows.length > 0, run: deleteRows },
restoreRows: {
enabled: (rows) => rowsEditable && rows.some((row) => edits.deletes.has(row)),
run: restoreRows,
},
}
: undefined;
tableEditorChanged(handle);
});
const hasResult = !!r;
@@ -430,12 +489,6 @@ function Result({ tab }: { tab: ResultTab }) {
);
if (!r) return null;
const data = (): ExportData => ({
columns,
rows: r.rows,
driver,
table: queryTable(text, { driver }),
});
const tableLabel = target ? `${target.schema ? `${target.schema}.` : ""}${target.table}` : "";
const tablePkCount = detailsValue?.columns.filter((c) => c.primaryKey).length ?? 0;
let notice: string | null = null;
@@ -456,7 +509,13 @@ function Result({ tab }: { tab: ResultTab }) {
<IconButton icon="database" title="Table" aria-pressed={view === "table"} onClick={() => setView("table")} />
<IconButton icon="db-chart" title="Chart" aria-pressed={view === "chart"} onClick={() => setView("chart")} />
<span className={styles.toolbarSeparator} />
<IconButton icon="refresh" title="Rerun Query" disabled={busy} onClick={() => void rerunResult(tab.id)} />
<IconButton
icon="refresh"
title="Rerun Query"
shortcut={shortcutLabel("db.reloadPage")}
disabled={busy}
onClick={() => void rerunResult(tab.id)}
/>
<PinButton tab={tab} />
{view === "table" && (
<IconButton
@@ -472,8 +531,9 @@ function Result({ tab }: { tab: ResultTab }) {
<IconButton
icon="plus"
title="Add Row"
shortcut={shortcutLabel("db.addRow")}
disabled={busy}
onClick={() => setEdits((e) => ({ ...e, inserts: [...e.inserts, new Map()] }))}
onClick={addRow}
/>
<Button
size="small"
@@ -503,7 +563,9 @@ function Result({ tab }: { tab: ResultTab }) {
<IconButton
icon="export"
title="Export Data"
onClick={(e) => showContextMenu(e, exportMenu(data(), queryTable(text, { driver }), extractor))}
shortcut={shortcutLabel("db.exportData")}
data-db-export=""
onClick={(e) => showExport({ x: e.clientX, y: e.clientY })}
/>
{view === "table" && <PanelToggle panel={panel} onChange={setPanel} />}
</Toolbar>
@@ -541,15 +603,13 @@ function Result({ tab }: { tab: ResultTab }) {
rowMenu={(rows) =>
editable && !busy
? [
{ label: "Delete Rows", icon: "trash", run: () => deleteRows(rows) },
{
label: "Restore Rows",
run: () =>
setEdits((e) => ({
...e,
deletes: new Set([...e.deletes].filter((d) => !rows.includes(d))),
})),
kind: "action",
action: "db.deleteRows",
icon: "trash",
arg: { rows, editor: handleRef.current },
},
{ kind: "action", action: "db.restoreRows", arg: { rows, editor: handleRef.current } },
]
: []
}
+53 -30
Переглянути файл
@@ -215,18 +215,61 @@ export function TableEditor({ input }: { input: EditorInput }) {
const r = viewRef.current?.getBoundingClientRect();
if (page && r) setColumnsAt({ x: r.left + r.width / 2, y: r.top + 48 });
};
const addRow = () => setEdits((e) => ({ ...e, inserts: [...e.inserts, new Map()] }));
const restoreRows = (rows: number[]) =>
setEdits((e) => ({ ...e, deletes: new Set([...e.deletes].filter((d) => !rows.includes(d))) }));
const showExport = (at: { x: number; y: number }) =>
page &&
showContextMenu(
at,
exportMenu(
{
columns: gridColumns,
rows: page.result.rows,
table: ref.table,
driver: sourceById(ref.id)?.driver ?? "sqlite",
},
`${ref.schema}.${ref.table}`,
extractor,
),
);
const canPrevious = offset > 0 && !loading;
const canNext = !!page?.result.hasMore && !loading;
handle.commands = {
reload: { enabled: () => !loading, run: reload },
firstPage: { enabled: () => canPrevious, run: () => setOffset(0) },
previousPage: { enabled: () => canPrevious, run: () => setOffset(Math.max(0, offset - limit)) },
nextPage: { enabled: () => canNext, run: () => setOffset(offset + limit) },
addRow: { enabled: () => editable, run: addRow },
exportData: {
enabled: () => !!page,
run: () => {
const r = viewRef.current?.querySelector("[data-db-export]")?.getBoundingClientRect();
if (r) showExport({ x: r.left, y: r.bottom });
},
},
deleteRows: { enabled: (rows) => editable && rows.length > 0, run: deleteRows },
restoreRows: { enabled: (rows) => editable && rows.some((r) => edits.deletes.has(r)), run: restoreRows },
};
useEffect(() => registerTableEditor(viewRef.current!, handle), [handle]);
useEffect(() => tableEditorChanged(handle), [handle, dirty, editable]);
const orderInvalid = orderDraft !== null && !parseOrderBy(orderDraft, names);
return (
<div className={styles.view} ref={viewRef} data-db-table-editor="">
<div className={styles.toolbar}>
<IconButton icon="refresh" title="Reload Page" onClick={reload} disabled={loading} />
<IconButton
icon="refresh"
title="Reload Page"
shortcut={shortcutLabel("db.reloadPage")}
onClick={reload}
disabled={loading}
/>
<div className={styles.pager}>
<IconButton
icon="chevron-left"
title="Previous Page"
disabled={offset === 0 || loading}
shortcut={shortcutLabel("db.previousPage")}
disabled={!canPrevious}
onClick={() => setOffset(Math.max(0, offset - limit))}
/>
<span>
@@ -236,7 +279,8 @@ export function TableEditor({ input }: { input: EditorInput }) {
<IconButton
icon="chevron-right"
title="Next Page"
disabled={!page?.result.hasMore || loading}
shortcut={shortcutLabel("db.nextPage")}
disabled={!canNext}
onClick={() => setOffset(offset + limit)}
/>
<Select
@@ -251,11 +295,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
</div>
{editable && (
<>
<IconButton
icon="plus"
title="Add Row"
onClick={() => setEdits((e) => ({ ...e, inserts: [...e.inserts, new Map()] }))}
/>
<IconButton icon="plus" title="Add Row" shortcut={shortcutLabel("db.addRow")} onClick={addRow} />
<Button
size="small"
variant="primary"
@@ -281,23 +321,10 @@ export function TableEditor({ input }: { input: EditorInput }) {
<IconButton
icon="export"
title="Export Data"
shortcut={shortcutLabel("db.exportData")}
data-db-export=""
disabled={!page}
onClick={(e) =>
page &&
showContextMenu(
e,
exportMenu(
{
columns: gridColumns,
rows: page.result.rows,
table: ref.table,
driver: sourceById(ref.id)?.driver ?? "sqlite",
},
`${ref.schema}.${ref.table}`,
extractor,
),
)
}
onClick={(e) => showExport({ x: e.clientX, y: e.clientY })}
/>
<IconButton
icon="import"
@@ -396,12 +423,8 @@ export function TableEditor({ input }: { input: EditorInput }) {
rowMenu={(rows) =>
editable
? [
{ label: "Delete Rows", icon: "trash", run: () => deleteRows(rows) },
{
label: "Restore Rows",
run: () =>
setEdits((e) => ({ ...e, deletes: new Set([...e.deletes].filter((d) => !rows.includes(d))) })),
},
{ kind: "action", action: "db.deleteRows", icon: "trash", arg: { rows, editor: handle } },
{ kind: "action", action: "db.restoreRows", arg: { rows, editor: handle } },
]
: []
}
+38
Переглянути файл
@@ -1,6 +1,8 @@
import { registerActions, type ActionContext } from "@/platform/actions";
import { setContext } from "@/platform/context";
export type CellCopy = "tsv" | "csv" | "onerow" | "header" | "rowsTsv" | "rowsCsv";
export interface CellActions {
canToggle(): boolean;
canSetNull(): boolean;
@@ -11,11 +13,31 @@ export interface CellActions {
setDefault(): void;
/** Opens the local filter of the selected cell's column. */
filter(): void;
canEditCell(): boolean;
editCell(): void;
hasSelection(): boolean;
copy(kind: CellCopy): void;
/** Rows of the selection, top to bottom. */
selectedRows(): number[];
}
const grids = new WeakMap<Element, CellActions>();
let active: CellActions | null = null;
/** The focused grid (not while a text field in it has focus). */
export function activeCellGrid(): CellActions | null {
return active;
}
const COPIES: Array<[CellCopy, string, string]> = [
["tsv", "db.copyAsTsv", "Copy as TSV"],
["csv", "db.copyAsCsv", "Copy as CSV"],
["onerow", "db.copyAsOneRow", "Copy as One-Row"],
["header", "db.copyWithHeader", "Copy with Header"],
["rowsTsv", "db.copyRowsAsTsv", "Copy Rows as TSV"],
["rowsCsv", "db.copyRowsAsCsv", "Copy Rows as CSV"],
];
export function registerCellGrid(root: Element, actions: CellActions): () => void {
grids.set(root, actions);
return () => {
@@ -70,6 +92,22 @@ export function installCellActions(): () => void {
enabled: (c) => handle(c)?.canFilter() ?? false,
run: (c) => handle(c)?.filter(),
},
{
id: "db.editCell",
title: "Edit Cell",
category: "Database",
keyWhen: "dbCellGridFocus",
enabled: (c) => handle(c)?.canEditCell() ?? false,
run: (c) => handle(c)?.editCell(),
},
...COPIES.map(([kind, id, title]) => ({
id,
title,
category: "Database",
keyWhen: "dbCellGridFocus",
enabled: (c: ActionContext) => handle(c)?.hasSelection() ?? false,
run: (c: ActionContext) => handle(c)?.copy(kind),
})),
]);
return () => {
dispose();
+45 -2
Переглянути файл
@@ -8,8 +8,15 @@ import { lazyComponent, lazyWhen, type MenuItem } from "@/ui";
import { activeEditor, lazyEditorExtension, registerEditorContribution } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { onIdeEvent } from "@/platform/ipc";
import { registerActions } from "@/platform/actions";
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
import { registerActions, type ActionContext } from "@/platform/actions";
import { activeCellGrid } from "./cellActions";
import {
activeTableEditor,
focusedTableEditor,
installTableEditorFocus,
type TableCommand,
type TableCommandTarget,
} from "./tableEditorFocus";
import { useProject } from "@/platform/project";
import {
registerEditorKind,
@@ -53,6 +60,25 @@ function useDatabaseHeaderMenu(): MenuItem[] {
const useDialogOpen = () => useDatabase((s) => !!s.dialog);
/** Table editor / result grid commands as actions (IDEA's data editor actions). */
const TABLE_COMMANDS: Array<[TableCommand, string, string, string[]]> = [
["reload", "db.reloadPage", "Reload Page", ["refresh", "rerun"]],
["firstPage", "db.firstPage", "First Page", ["pagination"]],
["previousPage", "db.previousPage", "Previous Page", ["pagination"]],
["nextPage", "db.nextPage", "Next Page", ["pagination"]],
["lastPage", "db.lastPage", "Last Page", ["pagination"]],
["addRow", "db.addRow", "Add Row", ["insert row", "new row"]],
["exportData", "db.exportData", "Export Data", ["export", "save as"]],
["deleteRows", "db.deleteRows", "Delete Rows", ["remove rows"]],
["restoreRows", "db.restoreRows", "Restore Rows", ["undelete rows"]],
];
/** The editor and rows a menu passed (focus has moved to the menu), else the focused grid's. */
function tableTarget(arg: unknown): TableCommandTarget {
if (arg && typeof arg === "object" && "rows" in arg) return arg as TableCommandTarget;
return { rows: activeCellGrid()?.selectedRows() ?? [], editor: null };
}
export function activate(): () => void {
const disposers = [
onIdeEvent("dbSourcesChanged", () => {
@@ -280,6 +306,23 @@ export function activate(): () => void {
when: "dbTableEditorFocus && dbTableEditorChanges",
run: () => activeTableEditor()?.revert(),
},
...TABLE_COMMANDS.map(([command, id, title, keywords]) => ({
id,
title,
category: "Tools",
keywords: ["table editor", "data editor", ...keywords],
keyWhen: "dbTableEditorFocus",
enabled: ({ arg }: ActionContext) => {
const { rows, editor } = tableTarget(arg);
const handler = (editor ?? focusedTableEditor())?.commands?.[command];
return !!handler && handler.enabled(rows);
},
run: ({ arg }: ActionContext) => {
const { rows, editor } = tableTarget(arg);
const handler = (editor ?? activeTableEditor())?.commands?.[command];
if (handler?.enabled(rows)) handler.run(rows);
},
})),
{
id: "db.explainPlan",
title: "Explain Plan",
+33 -1
Переглянути файл
@@ -2,7 +2,7 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DbDriver, DbTablePage } from "@/platform/ipc";
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
import { installCellActions } from "./cellActions";
import { activeCellGrid, installCellActions } from "./cellActions";
import { getContext } from "@/platform/context";
import { TableEditor } from "./TableEditor";
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
@@ -128,6 +128,38 @@ describe("table editor capabilities", () => {
}
});
it("runs the row and toolbar commands of the db.* actions on the focused grid's selection (#3506)", async () => {
backend.driver = "postgres";
const uninstallFocus = installTableEditorFocus();
const uninstallCells = installCellActions();
try {
await act(async () => {
render(<TableEditor input={tableInput("source", "public", "users")} />);
});
const cell = await screen.findByRole("gridcell", { name: "Ann" });
fireEvent.mouseDown(cell, { button: 0 });
act(() => screen.getByRole("grid").focus());
const rows = activeCellGrid()!.selectedRows();
expect(rows).toEqual([0]);
const commands = activeTableEditor()!.commands!;
expect(commands.nextPage!.enabled(rows)).toBe(false);
expect(commands.previousPage!.enabled(rows)).toBe(false);
expect(commands.exportData!.enabled(rows)).toBe(true);
expect(commands.restoreRows!.enabled(rows)).toBe(false);
act(() => commands.deleteRows!.run(rows));
expect(getContext().dbTableEditorChanges).toBe(true);
expect(activeTableEditor()!.commands!.restoreRows!.enabled(rows)).toBe(true);
act(() => activeTableEditor()!.commands!.restoreRows!.run(rows));
expect(getContext().dbTableEditorChanges).toBe(false);
act(() => activeTableEditor()!.commands!.addRow!.run([]));
expect(screen.getAllByRole("row").length).toBeGreaterThan(2);
expect(getContext().dbTableEditorChanges).toBe(true);
} finally {
uninstallCells();
uninstallFocus();
}
});
it("counts the editor-area host focusing the tab as table-editor focus (#2307)", async () => {
backend.driver = "postgres";
const uninstall = installTableEditorFocus();
+31
Переглянути файл
@@ -6,11 +6,37 @@
import { flushSync } from "react-dom";
import { setContext } from "@/platform/context";
/** Toolbar and row commands of a table editor or result grid, run as `db.*` actions. */
export type TableCommand =
| "reload"
| "firstPage"
| "previousPage"
| "nextPage"
| "lastPage"
| "addRow"
| "exportData"
| "deleteRows"
| "restoreRows";
export interface TableCommandHandler {
enabled(rows: number[]): boolean;
/** `rows`: the grid's selected rows (row commands). */
run(rows: number[]): void;
}
/** What a row menu passes to a `db.*` row action: the menu holds focus, not the grid. */
export interface TableCommandTarget {
rows: number[];
editor: TableEditorHandle | null;
}
export interface TableEditorHandle {
dirty: boolean;
submit(): void;
revert(): void;
showColumns(): void;
/** The commands this view has; one it lacks is disabled. */
commands?: Partial<Record<TableCommand, TableCommandHandler>>;
}
const handles = new WeakMap<Element, TableEditorHandle>();
@@ -55,6 +81,11 @@ export function tableEditorChanged(handle: TableEditorHandle) {
if (active === handle) update();
}
/** The active editor as is, for enablement checks (no side effects). */
export function focusedTableEditor(): TableEditorHandle | null {
return active;
}
/** The active editor, after confirming the cell being edited so its value counts. */
export function activeTableEditor(): TableEditorHandle | null {
const el = document.activeElement;
+47 -1
Переглянути файл
@@ -6,7 +6,7 @@ import {
removeAllBreakpoints,
useBreakpoints,
} from "../breakpoints/store";
import { handleDebugEvent, startPreparedSession, startSession, useDebug } from "../state";
import { handleDebugEvent, pinSession, rerunSession, startPreparedSession, startSession, useDebug } from "../state";
import type { LaunchConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import {
@@ -237,3 +237,49 @@ it("replaces finished tabs as soon as a prepared start begins", async () => {
await expect(started).resolves.toBe(43);
expect(Object.keys(useDebug.getState().sessions)).toEqual(["43"]);
});
it("replaces only the finished tab of the same name; other finished tabs stay", async () => {
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 1 }).mockResolvedValueOnce({ status: "ok", data: 2 });
await startSession({ ...config("launch"), name: "Server" });
await startSession({ ...config("launch"), name: "Client" });
handleDebugEvent(1, { kind: "terminated" });
handleDebugEvent(2, { kind: "terminated" });
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 3 });
await startSession({ ...config("launch"), name: "Server" });
expect(Object.values(useDebug.getState().sessions).map((s) => [s.name, s.status])).toEqual([
["Client", "terminated"],
["Server", "running"],
]);
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 4 });
const started = startPreparedSession({ id: "other", name: "Other" } as never, async () => ({
...config("launch"),
name: "Other",
}));
// No finished tab named "Other": the first finished one (Client) gives way.
expect(Object.values(useDebug.getState().sessions).map((s) => s.name)).toEqual(["Server", "Other"]);
await started;
expect(Object.values(useDebug.getState().sessions).map((s) => s.name)).toEqual(["Server", "Other"]);
});
it("keeps a pinned finished tab; Rerun on it takes its place and keeps it pinned", async () => {
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 1 });
await startSession({ ...config("launch"), name: "Server" });
pinSession(1, true);
handleDebugEvent(1, { kind: "terminated" });
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 2 });
await startSession({ ...config("launch"), name: "Server" });
const tabs = () => Object.values(useDebug.getState().sessions).map((s) => [s.id, s.status, !!s.pinned]);
expect(tabs()).toEqual([
[1, "terminated", true],
[2, "running", false],
]);
handleDebugEvent(2, { kind: "terminated" });
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 3 });
await rerunSession(1);
expect(tabs()).toEqual([
[2, "terminated", false],
[3, "running", true],
]);
});
+2
Переглянути файл
@@ -18,6 +18,7 @@ import {
useDebugRunSessions,
} from "@/workbench/contributions";
import { registerDebugActions } from "./actions";
import { registerDebugTabActions } from "./tabActions";
import { loadBreakpoints } from "./breakpoints/store";
import { loadExceptionBreakpoints } from "./breakpoints/exceptions";
import { loadJsBreakpoints, watchPageSessions } from "./js/eventBreakpoints";
@@ -72,6 +73,7 @@ export function activate(): () => void {
const disposers = [
() => useDebugRunSessions.setState({ sessions: [], serviceSessions: [], Console: null }),
registerDebugActions(),
registerDebugTabActions(),
// Remote JVM Debug, Go Remote, …: Run/Debug Configurations › Add New Configuration.
...REMOTE_TYPES.map(registerRunConfigType),
registerRunConfigType(jsBrowserType),
+55 -24
Переглянути файл
@@ -74,6 +74,8 @@ export interface DebugSession {
programInput?: boolean;
/** Process the session is attached to (a Run tab's build tool); stopped with the session. */
process: RunId | null;
/** Pinned tab (root sessions): once finished, a later session opens a new tab instead of taking its place. */
pinned?: boolean;
status: SessionStatus;
stoppedThread: number | null;
stopReason: string | null;
@@ -304,15 +306,30 @@ function settleStart(id: DebugSessionId | null, discard = false) {
for (const s of leftovers) if (isLive(useDebug.getState().sessions[s])) markTerminated(s);
}
/** Drops finished sessions; running ones stay (multiple concurrent sessions are fine). */
function dropFinished() {
useDebug.setState((s) => {
const sessions = Object.fromEntries(Object.entries(s.sessions).filter(([, v]) => isLive(v)));
const consoleLines = Object.fromEntries(Object.entries(s.console).filter(([k]) => sessions[+k]));
for (const id of ansiStreams.keys()) if (!sessions[id]) ansiStreams.delete(id);
return { sessions, console: consoleLines, active: s.active != null && sessions[s.active] ? s.active : null };
});
publishContext();
/** The session being rerun: its tab is the one the new session takes, pinned or not. */
let rerunOf: DebugSessionId | null = null;
/**
* As IDEA reuses run content: a new session takes the place of one finished tab (with its
* children) that isn't pinned, preferring one named like it, then the selected one; other
* finished tabs stay. Returns whether the new tab is pinned: as the tab it replaced on a
* rerun, else per the settings.
*/
function replaceFinished(name: string): boolean | undefined {
const { sessions, active } = useDebug.getState();
const own = rerunOf != null ? sessions[rerunOf] : undefined;
rerunOf = null;
if (own && !isLive(own)) {
removeSession(own.id);
return own.pinned;
}
const finished = Object.values(sessions).filter((s) => s.parent == null && !isLive(s) && !s.pinned);
const selected = active != null ? sessions[active] : undefined;
const ordered =
selected && finished.includes(selected) ? [selected, ...finished.filter((s) => s !== selected)] : finished;
const reused = ordered.find((s) => s.name === name) ?? ordered[0];
if (reused) removeSession(reused.id);
return workflowSettings().run.pinTabs || undefined;
}
/**
@@ -670,12 +687,17 @@ export async function startPreparedSession(
const id = --preparationSeq as DebugSessionId;
const controller = new AbortController();
preparations.set(id, controller);
// The new tab takes the place of finished ones while its build runs, not once the adapter starts.
dropFinished();
// The new tab takes the place of a finished one while its build runs, not once the adapter starts.
const pinned = replaceFinished(config.name);
useDebug.setState((s) => ({
sessions: {
...s.sessions,
[id]: blank(id, { name: config.name, adapter: config.debugAdapter ?? "", runConfig: config }),
[id]: blank(id, {
name: config.name,
adapter: config.debugAdapter ?? "",
runConfig: config,
pinned,
}),
},
console: { ...s.console, [id]: [] },
active: id,
@@ -728,7 +750,7 @@ export async function startSession(
// Attaching to a JVM that may be gone: the finished session stays until the attach succeeds.
const afterDetach = justDetached(options.process);
const previousActive = useDebug.getState().active;
if (!afterDetach) dropFinished();
let pinned = !afterDetach && !options.preparation ? replaceFinished(launch.name) : undefined;
try {
if (options.show !== false && workflowSettings().run.showOnStart) toolWindowService().show("debug");
} catch {
@@ -743,7 +765,7 @@ export async function startSession(
const id = await call(commands.debugStart(launch));
console.info("Debug adapter started", { name: launch.name, ms: performance.now() - adapterStarted });
owned.add(id);
if (afterDetach) dropFinished();
if (afterDetach && !options.preparation) pinned = replaceFinished(launch.name);
if (options.preparation?.signal.aborted) {
await call(commands.debugStop(id)).catch(() => undefined);
settleStart(id);
@@ -775,6 +797,7 @@ export async function startSession(
adapter: cur.adapter || launch.adapter,
launch: options.rerunnable === false ? null : launch,
process: options.process ?? null,
pinned: preparation ? preparation.pinned : pinned,
status: cur.status === "starting" ? "running" : cur.status,
},
},
@@ -891,6 +914,11 @@ export async function closeSessionTab(id: DebugSessionId): Promise<boolean> {
return true;
}
/** Pins or unpins a session's tab. */
export function pinSession(id: DebugSessionId, pinned: boolean) {
patch(id, { pinned });
}
/** Forgets a session and its children; a selected one passes the selection to the tab on its left. */
export function removeSession(id: DebugSessionId) {
const st = useDebug.getState();
@@ -918,6 +946,7 @@ export function removeSession(id: DebugSessionId) {
});
for (const goneId of gone) {
owned.delete(goneId);
ansiStreams.delete(goneId);
unfollowProcessOutput(goneId);
}
updateExecutionPoint();
@@ -928,18 +957,20 @@ export async function rerunSession(id: DebugSessionId, options: { show?: boolean
const s = useDebug.getState().sessions[id];
if (!s) return;
const root = rootOf(s);
if (root.runConfig) {
if (isLive(root)) await stopSession(root.id);
await executeAction(
"run.debugConfig",
options.show === false ? { config: root.runConfig, show: false } : root.runConfig,
);
return;
}
const launch = root.launch;
if (!launch) return;
if (!root.runConfig && !launch) return;
if (isLive(root)) await stopSession(root.id);
await startSession(launch, { show: options.show });
rerunOf = root.id;
try {
if (root.runConfig)
await executeAction(
"run.debugConfig",
options.show === false ? { config: root.runConfig, show: false } : root.runConfig,
);
else await startSession(launch!, { show: options.show });
} finally {
rerunOf = null;
}
}
async function loadCapabilities(id: DebugSessionId) {
+94
Переглянути файл
@@ -0,0 +1,94 @@
import { registerActions, type ActionContext } from "@/platform/actions";
import type { MenuItem } from "@/ui";
import type { DebugSessionId } from "@/platform/ipc";
import { closeSessionTab, pinSession, useDebug } from "./state";
import { sessionTabs } from "./ui/sessionTabs";
/** The sessions the Debug tabs close: each tab's owner, in tab order. */
function owners(): DebugSessionId[] {
return [...new Set(sessionTabs(Object.values(useDebug.getState().sessions)).map((t) => t.owner))];
}
/** The tab owner an action is for: its argument, else the selected tab's. */
function target({ arg }: ActionContext): DebugSessionId | null {
const { sessions, active } = useDebug.getState();
const id = typeof arg === "number" ? arg : active;
if (id == null || !sessions[id]) return null;
return sessionTabs(Object.values(sessions)).find((t) => t.session.id === id || t.owner === id)?.owner ?? null;
}
/** `id` and the sessions it runs under: closing one of those would close `id` too. */
function lineage(id: DebugSessionId): Set<DebugSessionId> {
const { sessions } = useDebug.getState();
const out = new Set<DebugSessionId>();
for (let cur = sessions[id]; cur && !out.has(cur.id); cur = cur.parent != null ? sessions[cur.parent] : undefined)
out.add(cur.id);
return out;
}
/** Closes the tabs one after another; a running session the user keeps stops the rest. */
async function closeTabs(ids: readonly DebugSessionId[]) {
for (const id of ids) if (useDebug.getState().sessions[id] && !(await closeSessionTab(id))) return;
}
/** A pinnable tab: a user-started session's (a child's tab goes with its parent). */
function pinnable(id: DebugSessionId | null) {
const s = id != null ? useDebug.getState().sessions[id] : undefined;
return s && s.parent == null ? s : undefined;
}
export function registerDebugTabActions(): () => void {
return registerActions([
{
id: "debug.closeTab",
title: "Close Tab",
category: "Debug",
enabled: (c) => target(c) !== null,
run: (c) => void closeSessionTab(target(c)!),
},
{
id: "debug.closeOtherTabs",
title: "Close Other Tabs",
category: "Debug",
enabled: (c) => target(c) !== null && owners().length > 1,
run: async (c) => {
const keep = lineage(target(c)!);
await closeTabs(owners().filter((id) => !keep.has(id)));
},
},
{
id: "debug.closeAllTabs",
title: "Close All Tabs",
category: "Debug",
enabled: () => owners().length > 0,
run: () => closeTabs(owners()),
},
{
id: "debug.pinTab",
title: "Pin / Unpin Tab",
category: "Debug",
icon: "pin",
enabled: (c) => !!pinnable(target(c)),
run: (c) => {
const s = pinnable(target(c));
if (s) pinSession(s.id, !s.pinned);
},
},
]);
}
/** The context menu of a Debug tab (IDEA's content tab menu); `owner` is the session the tab stands for. */
export function debugTabMenu(owner: DebugSessionId): MenuItem[] {
const s = pinnable(owner);
return [
{ kind: "action", action: "debug.closeTab", arg: owner },
{ kind: "action", action: "debug.closeAllTabs", arg: owner },
{ kind: "action", action: "debug.closeOtherTabs", arg: owner },
...(s
? ([
{ kind: "separator" },
{ kind: "action", action: "debug.pinTab", arg: owner, label: s.pinned ? "Unpin Tab" : "Pin Tab" },
] satisfies MenuItem[])
: []),
];
}
+10 -2
Переглянути файл
@@ -41,6 +41,7 @@ import {
} from "../state";
import { remoteWaitingNote } from "../remote";
import { sessionTabs } from "./sessionTabs";
import { debugTabMenu } from "../tabActions";
import { stopNote } from "../js/eventBreakpoints";
import { NetworkView } from "../js/NetworkView";
import { liveWatchesApply, useLiveWatches } from "../js/liveWatches";
@@ -138,13 +139,15 @@ export function DebugTabs() {
const list = Object.values(sessions);
if (!list.length) return null;
const tabs = sessionTabs(list);
const items: TabItem[] = tabs.map(({ session: s, child }) => ({
const ownerOf = (id: string) => tabs.find((t) => t.session.id === +id)?.owner ?? +id;
const items: TabItem[] = tabs.map(({ session: s, child, owner }) => ({
id: String(s.id),
label: child ? tx`${s.name} (child)` : s.name,
text: s.name,
icon: "debug",
italic: s.status === "terminated",
closable: true,
pinned: !child && !!sessions[owner]?.pinned,
tooltip: statusText(s),
}));
// A browser launch's own session has no tab: its page's tab stands for it.
@@ -157,7 +160,12 @@ export function DebugTabs() {
items={items}
activeId={shown ? String(shown.session.id) : null}
onSelect={(id) => selectSession(+id)}
onClose={(id) => void closeSessionTab(tabs.find((t) => t.session.id === +id)?.owner ?? +id)}
onClose={(id) => void closeSessionTab(ownerOf(id))}
onTogglePin={(id) => void executeAction("debug.pinTab", ownerOf(id))}
onContextMenu={(id, e) => {
e.preventDefault();
showContextMenu(e, debugTabMenu(ownerOf(id)), { owner: e.currentTarget });
}}
panelIdPrefix="openidea-debug"
/>
);
+2 -2
Переглянути файл
@@ -7,7 +7,7 @@
import { useMemo, useRef, useState, type MouseEvent, type ReactNode } from "react";
import { buildFileTree, dirKeys, type FileTreeNode } from "@/features/vcs/fileTree";
import { openDiff, withChain } from "@/features/vcs/diffInput";
import { KIND_COLOR, baseName, fileCount, type EffectiveKind } from "@/features/vcs/model";
import { KIND_COLOR, fileCount, renameFrom, type EffectiveKind } from "@/features/vcs/model";
import type { Commit } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { Icon, IconButton, Spinner, T, Tree, fileIconName, showContextMenu, type MenuItem } from "@/ui";
@@ -252,7 +252,7 @@ function ChangeRow({ node }: { node: FileTreeNode<CreateChange> }) {
<span className={styles.fileName} style={{ color: KIND_COLOR[kindOf(f)] }}>
{node.name}
</span>
{f.oldPath && <span className={styles.fileDetail}>{tx`renamed from ${baseName(f.oldPath)}`}</span>}
{f.oldPath && <span className={styles.fileDetail}>{renameFrom(f.path, f.oldPath)}</span>}
</span>
);
}
+2 -2
Переглянути файл
@@ -10,7 +10,7 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import clsx from "clsx";
import { dirKeys, type FileTreeNode } from "@/features/vcs/fileTree";
import { baseName, dirName, fileCount, KIND_COLOR } from "@/features/vcs/model";
import { dirName, fileCount, KIND_COLOR, renameFrom } from "@/features/vcs/model";
import { currentRepoRoot } from "@/features/vcs/store";
import { useTx } from "@/platform/i18n";
import { Icon, Tree, fileIconName, showContextMenu, T, type MenuItem, type TreeHandle } from "@/ui";
@@ -202,7 +202,7 @@ function ChangeRow(props: {
{node.name}
</span>
{flat && dirName(f.filename) && <span className={styles.fileDir}>{dirName(f.filename)}</span>}
{f.previousFilename && <span className={styles.fileDir}>{tx`renamed from ${baseName(f.previousFilename)}`}</span>}
{f.previousFilename && <span className={styles.fileDir}>{renameFrom(f.filename, f.previousFilename)}</span>}
</>
) : (
<>
+9 -4
Переглянути файл
@@ -2,9 +2,10 @@
* External Libraries: the project's SDK / library source folders (the Python
* interpreter's standard library and site-packages, the JDK, node_modules
* packages, Cargo crates and the Rust standard library, GOROOT and Go modules,
* Maven / Gradle dependency jars) as a Project view root. Their files open
* read-only, like IDEA's library sources. Archives (the JDK's `src.zip`, jars)
* are browsed through the backend's `<archive>!/<entry>` paths.
* the Zig standard library and its fetched build.zig.zon packages, Maven /
* Gradle dependency jars) as a Project view root. Their files open read-only,
* like IDEA's library sources. Archives (the JDK's `src.zip`, jars, Zig
* package tarballs) are browsed through the backend's `<archive>!/<entry>` paths.
*/
import { Channel } from "@tauri-apps/api/core";
import { commands, type LibraryGroup, type RequestId } from "@/bindings";
@@ -32,10 +33,12 @@ const GROUP_ICONS: Record<string, string> = {
classpath: "file-java",
ruby: "file-ruby",
gems: "file-ruby",
zig: "file-zig",
zigPackages: "file-zig",
};
/** SDK groups, which IDEA writes in angle brackets (`< 21 >`); library groups (`Maven: g:a:v`) go without. */
const SDK_KINDS = new Set(["jdk", "python", "ruby", "go", "rust"]);
const SDK_KINDS = new Set(["jdk", "python", "ruby", "go", "rust", "zig"]);
/** An archive's root (`/jdk/lib/src.zip!`): its entries live below `<archive>!/`. */
const isArchiveRoot = (path: string) => path.endsWith("!");
@@ -62,6 +65,7 @@ const MANIFESTS = new Set([
"go.mod",
"go.sum",
"go.work",
"build.zig.zon",
".classpath",
"pyproject.toml",
"setup.py",
@@ -129,6 +133,7 @@ const sdkKey = (s: ReturnType<typeof useProject.getState>) => {
l?.go?.goroot,
l?.go?.gopath,
l?.go?.modules,
l?.zig?.zig,
s.settings?.projectStructure?.libraries,
s.settings?.projectStructure?.sourceRoots,
]);
+25 -7
Переглянути файл
@@ -29,13 +29,24 @@ describe("External Libraries", () => {
it("gives each ecosystem's groups their icon", () => {
const root = librariesRoot(
["jdk", "nodeCore", "nodeModules", "rust", "cargo", "go", "goModules", "maven", "gradle", "other"].map(
(kind) => ({
name: kind,
kind,
roots: [{ name: "r", path: `/libs/${kind}` }],
}),
),
[
"jdk",
"nodeCore",
"nodeModules",
"rust",
"cargo",
"go",
"goModules",
"maven",
"gradle",
"zig",
"zigPackages",
"other",
].map((kind) => ({
name: kind,
kind,
roots: [{ name: "r", path: `/libs/${kind}` }],
})),
)!;
expect(Object.fromEntries(root.children!.map((g) => [g.label, g.icon]))).toEqual({
"< jdk >": "file-java",
@@ -47,6 +58,8 @@ describe("External Libraries", () => {
goModules: "file-gomod",
maven: "maven-project",
gradle: "file-gradle",
"< zig >": "file-zig",
zigPackages: "file-zig",
other: "library",
});
});
@@ -63,18 +76,22 @@ describe("External Libraries", () => {
group("Go SDK 1.27.4", "go"),
group("Maven: com.acme:core:2.1.27", "maven"),
group("Node.js Core", "nodeCore"),
group("Zig 0.16.0", "zig"),
group("Zig packages", "zigPackages"),
];
const labels = (groups: typeof detected) => librariesRoot(groups)!.children!.map((g) => g.label);
expect(labels(detected)).toEqual([
"< Go SDK 1.27.4 >",
"< Python 3.14 >",
"< temurin-21 >",
"< Zig 0.16.0 >",
"Cargo dependencies",
"Gradle: com.acme:lib:1.0",
"Maven: com.acme:core:2.1.27",
"Maven: org.junit:junit:4.13",
"node_modules",
"Node.js Core",
"Zig packages",
]);
expect(labels([...detected].reverse())).toEqual(labels(detected));
});
@@ -104,6 +121,7 @@ describe("External Libraries", () => {
expect(touchesManifest(["C:\\p\\go.mod"])).toBe(true);
expect(touchesManifest(["/p/.venv/pyvenv.cfg"])).toBe(true);
expect(touchesManifest(["/p/pnpm-workspace.yaml", "/p/Gemfile.lock"])).toBe(true);
expect(touchesManifest(["/p/build.zig.zon", "/p/go.work"])).toBe(true);
expect(touchesManifest(["/p/node_modules/react/package.json"])).toBe(false);
expect(touchesManifest(["/p/src/package.json.bak", "/p/README.md"])).toBe(false);
});
+2 -1
Переглянути файл
@@ -12,7 +12,7 @@ import {
import { defaultKeymap, indentWithTab } from "@codemirror/commands";
import { bracketMatching, indentOnInput, syntaxHighlighting } from "@codemirror/language";
import type { NotebookCellDoc } from "@/bindings";
import { cellEditorExtensions } from "@/editor/api";
import { cellEditorExtensions, embeddedEditorExtensions } from "@/editor/api";
import { openideaTheme } from "@/editor/core/cm/theme";
import { openideaHighlightStyle } from "@/editor/core/cm/highlight";
import { selectionMarks } from "@/editor/core/cm/selectionMarks";
@@ -97,6 +97,7 @@ export function CellEditor({
]),
),
keymap.of([indentWithTab, ...defaultKeymap]),
embeddedEditorExtensions(session.path),
language.of([]),
services.current.of(languageServices(type, initialDoc.current)),
readonly.current.of(EditorState.readOnly.of(session.getState().frozen)),
+1 -1
Переглянути файл
@@ -163,7 +163,7 @@
width: 16px;
height: 16px;
}
.runnable {
.overlay {
position: absolute;
inset: 0;
pointer-events: none;
+28
Переглянути файл
@@ -837,3 +837,31 @@ it("shows a decoration's suffix after the root name, with icons and struck-out s
act(() => setFileDecorations("test-suffix", new Map()));
await waitFor(() => expect(row("acme").textContent).not.toContain("main/"));
});
it("marks file and folder symlinks with the link arrow, leaving real folders and files alone", async () => {
fs = new MemoryFs(
{
"/w/acme/dir1/keep.txt": "x",
"/w/acme/dir2/keep.txt": "x",
"/w/acme/note.txt": "x",
},
ROOT,
// `ln -s dir1 link1` on macOS/Linux; the backend reports kind "symlink", size 0.
{ "/w/acme/link1": "/w/acme/dir1", "/w/acme/note-link.txt": "/w/acme/note.txt" },
);
setProjectFsForTests(fs, ROOT);
initProjectTree(ROOT, "acme");
const { row } = setup();
const iconAt = (label: string) => row(label).querySelector("[data-project-path]")?.getAttribute("data-project-icon");
await waitFor(() => expect(row("link1")).toBeTruthy());
// The link to a folder carries the arrow (IDEA's symlink badge)…
expect(within(row("link1")).getByLabelText("Symbolic link").tagName).toBe("svg");
expect(iconAt("link1")).toBe("folder");
expect(iconAt("dir1")).toBe("folder");
// …so does a link to a file, as in IDEA; real folders and files do not.
expect(within(row("note-link.txt")).getByLabelText("Symbolic link").tagName).toBe("svg");
expect(iconAt("note-link.txt")).toBe("file-text");
expect(within(row("dir1")).queryByLabelText("Symbolic link")).toBeNull();
expect(within(row("dir2")).queryByLabelText("Symbolic link")).toBeNull();
expect(within(row("note.txt")).queryByLabelText("Symbolic link")).toBeNull();
});
+3 -1
Переглянути файл
@@ -322,8 +322,10 @@ const Row = memo(function Row({
size={16}
className={clsx(styles.icon, node.dir && styles.folderIcon, dimIcon && styles.faded)}
/>
{/* IDEA's symlink arrow, on file and folder links (the entry kind comes with the listing). */}
{node.symlink && <Icon name="symlink-mark" size={16} className={styles.overlay} label="Symbolic link" />}
{!!file?.runnable && icon !== "spring-boot" && icon !== "jvm-test" && (
<Icon name="runnable-mark" size={16} className={styles.runnable} />
<Icon name="runnable-mark" size={16} className={styles.overlay} />
)}
</span>
{isEditing && editing ? (
+65 -23
Переглянути файл
@@ -99,10 +99,16 @@ export function beginLocalImport(): LocalImport {
};
}
type MemNode = { kind: "file"; size: number } | { kind: "dir" };
type MemNode = { kind: "file"; size: number } | { kind: "dir" } | { kind: "symlink"; target: string };
/** What a link resolves to (the loop in `resolve` never stops on a link). */
type ResolvedNode = Exclude<MemNode, { kind: "symlink" }>;
const err = (kind: "notFound" | "alreadyExists" | "invalidInput", message: string) => new IpcError({ kind, message });
/** The tree's own notion (see `isDirEntry`): a folder, or a link to one. */
const isFolder = (e: FileEntry) => e.kind === "dir" || (e.kind === "symlink" && e.size === 0);
/** Minimal in-memory file system with the backend's semantics (no overwrite, folders first). */
export class MemoryFs implements ProjectFs {
readonly nodes = new Map<string, MemNode>();
@@ -110,7 +116,7 @@ export class MemoryFs implements ProjectFs {
/** Called after every mutation with the changed paths (simulates the watcher). */
onChange?: (e: { created: string[]; modified: string[]; removed: string[] }) => void;
constructor(files: Record<string, string | null> = {}, root = "/") {
constructor(files: Record<string, string | null> = {}, root = "/", links: Record<string, string> = {}) {
this.nodes.set(root, { kind: "dir" });
for (const [path, content] of Object.entries(files)) {
if (content === null) this.mkdirp(path);
@@ -119,6 +125,10 @@ export class MemoryFs implements ProjectFs {
this.nodes.set(path, { kind: "file", size: content.length });
}
}
for (const [path, target] of Object.entries(links)) {
this.mkdirp(parentOf(path));
this.nodes.set(path, { kind: "symlink", target });
}
}
private mkdirp(path: string) {
@@ -132,28 +142,60 @@ export class MemoryFs implements ProjectFs {
return [...this.nodes.keys()].filter((p) => p !== dir && parentOf(p) === dir);
}
async readDir(path: string): Promise<FileEntry[]> {
const n = this.nodes.get(path);
if (!n) throw err("notFound", `${path} not found`);
if (n.kind !== "dir") throw err("invalidInput", `${path} is not a directory`);
/** Follows symlinks (bounded, so a link cycle errors instead of hanging). */
private resolve(path: string): { path: string; node: ResolvedNode | undefined } {
let p = path;
let n = this.nodes.get(p);
for (let hops = 0; n?.kind === "symlink"; hops++) {
if (hops > 16) throw err("invalidInput", `${path} is a symlink loop`);
p = n.target;
n = this.nodes.get(p);
}
// The loop only exits on a non-link entry (or a missing one).
return { path: p, node: n as ResolvedNode | undefined };
}
async readDir(at: string): Promise<FileEntry[]> {
// Like the backend, listing a symlink to a folder lists through the link.
const { path, node } = this.resolve(at);
if (!node) throw err("notFound", `${path} not found`);
if (node.kind !== "dir") throw err("invalidInput", `${at} is not a directory`);
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
return this.childrenOf(path)
.map((p) => {
const c = this.nodes.get(p)!;
const name = nameOf(p);
const excluded = [...this.ignored].some((i) => p === i || isInside(p, i));
return {
name,
path: p,
kind: c.kind,
size: c.kind === "file" ? c.size : 0,
mtimeMs: 0,
ignored: excluded,
excluded,
hidden: name.startsWith("."),
} satisfies FileEntry;
})
.sort((a, b) => Number(b.kind === "dir") - Number(a.kind === "dir") || collator.compare(a.name, b.name));
return (
this.childrenOf(path)
.map((p) => {
const c = this.nodes.get(p)!;
const name = nameOf(p);
const excluded = [...this.ignored].some((i) => p === i || isInside(p, i));
if (c.kind === "symlink") {
const t = this.resolve(p);
return {
name,
path: p,
kind: "symlink",
// A link to a folder has size 0; a dangling one the link's own length (the backend's `symlink_metadata`).
size: t.node ? (t.node.kind === "dir" ? 0 : t.node.size) : c.target.length,
...(t.node && { targetKind: t.node.kind === "dir" ? "dir" : "file" }),
mtimeMs: 0,
ignored: excluded,
excluded,
hidden: name.startsWith("."),
} satisfies FileEntry;
}
return {
name,
path: p,
kind: c.kind,
size: c.kind === "file" ? c.size : 0,
mtimeMs: 0,
ignored: excluded,
excluded,
hidden: name.startsWith("."),
} satisfies FileEntry;
})
// Folders first, counting a link to a folder as a folder (the backend's ordering).
.sort((a, b) => Number(isFolder(b)) - Number(isFolder(a)) || collator.compare(a.name, b.name))
);
}
private emit(e: Partial<{ created: string[]; modified: string[]; removed: string[] }>) {
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more