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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 825196e000 fix(agents): size the prompt to its wrapped content 2026-11-23 21:59:19 +08:00
aconeshanaтаaconeshana d4b5581441 fix(ui): paste into a tree's speed search, not the view's Paste (#5401)
In the Project view, copy a keyword, press ⌘F, then ⌘V: the app reported "No files on the clipboard" and the search box stayed empty, instead of pasting the keyword the user had copied to search with.
A tree's speed search is not a text field — its query is built from printable keydowns. So `⌘V` never reached the query: the keymap dispatcher ran `project.paste` on the selected folder, and the paste event that followed bubbled to the Project view's clipboard fallback, which runs the same action again.
The shared `Tree` now claims `⌘V` while a search is active (as it already claims `⌫` since #3226) and takes the clipboard text into its query: pasted text is flattened onto one line and the search jumps to the nearest match. With the search closed, or with a clipboard that holds no text, the view's Paste runs exactly as before.
Every tree with a speed search gets this — the Project view, the Database view, the Services tree and the GitHub changes tree all render `src/ui/Tree.tsx`.

Co-authored-by: aconeshana <[email protected]>
2026-11-23 21:00:08 +08:00
Bert Verhelstтаbertyhell d96060f08b fix(ui): scroll text fields while drag-selecting past their edges (#5429)
Drag-selecting in a long Find in Files query (or any text field) and moving the pointer past the field's left or right edge didn't scroll the text, so you couldn't select past what's visible. IntelliJ IDEA does scroll. WebKitGTK extends the selection in this case but never scrolls the field to follow it. Arrow keys do scroll. Now, while a drag that started in the field is past one of its edges, the field moves the selection end and the scroll position itself, faster the further out the pointer is. Once the pointer is back inside, WebKit's own selection takes over again. Both `Input` and `SearchField` get this.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:59:53 +08:00
Bert Verhelstтаbertyhell 507258daec fix(editor): stop clipping Code Vision hints that are taller than 16px (#5418)
The Code Vision row above a declaration (usage count, author) cut off the top or bottom of its text, most visibly for Chinese labels like "10 个用法" / "无用法". The row was a fixed `height: 16px` with `overflow: hidden`, while its text is the editor font size minus 1px. At larger editor fonts, or with CJK fallback fonts that ink below the Latin metrics (Microsoft YaHei, Noto Sans CJK), the glyphs didn't fit.
The row now has `min-height: 16px`, and its items use `line-height: normal`, so the row grows to the ascent and descent of the fonts actually used. At the default font a Latin-only row is still exactly 16px. The line-end hint (Code Vision kinds set to "right") has the same 1em box with `overflow: hidden`. It keeps its size and position but now clips only horizontally.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:59:37 +08:00
Mr0Bread dae402b966 perf(vcs): make a git history page cost independent of the commit count (#5446)
A Git Log page costs a fixed ~15 ms in a repository with 248 refs (the 100k-commit fixture), even for a one-row page. Every page listed and peeled all refs twice (once for the decorations, once more for the view cache key via `log_refs`), at ~25 µs per ref. The decorations are now cached until `HEAD`, `packed-refs` or a directory under `refs/` changes, and the cache key uses a change counter instead of the full ref map. A warm page no longer reads any ref.
The cost scales with the number of refs, not commits: the audit's 10k/100k fixtures have 50/248 refs, which is why it looked proportional to the commit count. A repository with thousands of remote branches pays correspondingly more.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 20:43:54 +08:00
Bert Verhelstтаbertyhell 39e803b8f9 fix(vcs): keep a filtered log narrow while older matches are still unloaded (#5421)
With a User filter on a merge-heavy history, the first page of the Git Log fanned the top merge out into dozens of dashed lanes, and the graph column pushed the commit subjects to the right. It went back to one line only after every match was loaded. The cause: `pruneFilteredEdges` (the #2670 fix) only judges a filtered connection when its target is on the loaded page. With the first 300 rows of the issue's repository, the merge kept 43 connections, 42 of them to rows that weren't loaded yet.
Now, while another kept connection of the commit already leads below the page, a filtered connection to an unloaded target waits until that target loads, and is then judged exactly like before. If no kept connection leads below the page, one filtered connection stays, so a row never looks like the end of its history. This is a heuristic: a connection that turns out to be needed (two unrelated side branches, both below the page) appears once its target loads. The sibling-branch test pins that behaviour. An exact answer on the first page would need the backend projection (`Visibility::parents`) to drop ancestors that another projected parent already reaches. This PR doesn't touch Rust; that could be a follow-up.
Go to Parent now pages until every unpruned connection of the commit is loaded, as it did before, so a merge still offers all its parents.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:43:44 +08:00
TWINKLE d6b56856d2 Fix/terminal ime caret (#5458)
Closes #4112 (its remaining half: #4347 stopped the terminal sliding sideways while composing, the
candidate window still opened at the far right of pi's input box).
xterm anchors the IME candidate window on its hidden helper textarea, and keeps that textarea on the
terminal cursor — on every render, on `compositionstart` and again on each `compositionupdate`. A
program that paints its own caret leaves the terminal cursor elsewhere: pi asks for a column past the
right edge of its input box (`ESC[21;411H` in a 206-column terminal, which xterm clamps) while it

Co-authored-by: H-TWINKLE <[email protected]>
2026-11-23 20:40:44 +08:00
Yann 8a84e8f473 fix(agents): preserve and display tool result images (#5447)
Claude Code can return an image from a tool call without including a Markdown image in its final reply. OpenIDEA discarded that image while normalizing and saving the tool result, so the conversation showed no preview.
Preserve inline tool images separately from truncated text and show them below the folded work summary. The existing image viewer opens the full preview; expanding the work does not duplicate it, and old conversations without an image field still load.

Co-authored-by: YannABC <[email protected]>
2026-11-23 20:40:35 +08:00
Bert Verhelstтаbertyhell f31aa29f3e fix(agents): update the context meter when Claude Code compacts the conversation (#5441)
After a compaction the context meter kept the pre-compaction usage until the next request. compact_boundary now sets the usage to post_tokens; without it the driver asks Claude Code (get_context_usage).

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:03:15 +08:00
faysouтаfaysou 639e4b3df9 fix(editor): keep completion types and usage captions visible in narrow popups (#5387)
The completion popup can clip a return type after the editor font loads. Its return-type column now uses the row’s existing gap. In Show Usages, same-named files can be hard to distinguish because the filename and directory share too little space. The filename column now gets 38% of a narrow row, with the existing 176 px cap.
| Popup | Before | After |
| ----- | ------ | ----- |
| Completion | ![Return type ends in an ellipsis](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/completion-before.png) | ![RegionalSettlementResult fits](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/completion-after.png) |
| Show Usages | ![The checkout directory is truncated](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/usages-before.png) | ![Both billing and checkout are visible](https://raw.githubusercontent.com/faysou/openidea/691de74a16586ccc65eb229315507ba0f5938933/usages-after.png) |

Co-authored-by: faysou <[email protected]>
2026-11-23 20:02:54 +08:00
Bert Verhelstтаbertyhell 01b9908898 fix(search): offer every project file type in the file mask menu (#5416)
The **File mask** menu in Find in Files now lists every language file type present in the project, most common first, after the recently used masks. Before, `refreshProjectMasks` kept only the 5 most common types, so in a project with six (rs, md, json, toml, yml, properties) the least common one, `*.properties`, could not be picked. The menu already scrolls and stays inside the window, so a long list stays usable.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:02:43 +08:00
Bert Verhelstтаbertyhell 7f201ed87d fix(editor): stop linked tag editing while a tag is being deleted (#5434)
Backspacing through a closing tag such as `</div>` also emptied the opening tag, leaving `<>`. The first Backspace removes `>`. The parser still reads `</div` as the element's close tag, so every later Backspace in the name counted as a rename and was mirrored. Linked tag editing now only pairs two tags that both still end in `>`. A tag missing its `>` is being deleted, so nothing is mirrored into it or out of it. The same applies to an opening tag deleted before its children, in all the HTML-based modes and in JSX/TSX. XML does not use linked tags (`LINKED_TAG_LANGUAGES` in `prefs.ts`).

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:02:33 +08:00
Shohruh Ismoilovтаshohruh-genius 85344b86b5 fix(templates): offer Svelte components in the New menu (#5440)
The New menu had no built-in template for `.svelte` files. Add **Svelte Component** for Vite and Node.js projects, including SvelteKit workspace members. The template accepts SvelteKit filenames such as `+page.svelte`.

Co-authored-by: shohruh-genius <[email protected]>
2026-11-23 20:02:23 +08:00
faysouтаfaysou 12e85a7c1b test(vcs): check Git Log graph options as separate equivalence cases (#5424)
The Git Log graph-equivalence test compares layouts for eight option combinations, each with five fragment configurations. Running all 40 comparisons in one Vitest case exceeded the five-second timeout on shared Linux runners. Give each option combination its own test for histories with and without refs. Each case still compares the complete layout with the dense reference implementation for all five fragment configurations and the same 2,400 commits.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:02:13 +08:00
faysouтаfaysou 861acabf77 test(search): open the action search from the toolbar (#5386)
The action-search test could time out before reaching its first search assertion when the runner delayed the second Shift press. Open Search Everywhere through the title-bar button for this test, then enter a query and run the matching action. The adjacent shortcut test exercises double Shift directly.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:02:04 +08:00
faysouтаfaysou 96395c979f test(project): control the clock during diagonal submenu navigation (#5384)
The Project tree test moves the pointer diagonally toward the New submenu in ten steps. On a busy runner, the time spent delivering input and checking assertions can exceed the menu’s hover delay and close it mid-gesture. Use Playwright’s browser clock to advance 75 ms at each step and check that the submenu stays open through the final 350 ms pause.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:55 +08:00
Mr0Bread e9f768d8b5 perf(events): serialise an event once for all windows (#5445)
With auxiliary windows open (comparison, diff, etc. that share the project's documents), every backend event was serialised once per window, because `emit_to` serialises its payload on each call. For a large diagnostics event that is 2.3 MB (10k items) or 11.6 MB (50k items) of JSON built again for each window, on the thread that emits the event. `TauriSink` now serialises the event once and sends the same JSON string to each window with `emit_str_to`. The payload is the same `serde_json::to_string(&event)` that `emit_to` produced, so the frontend (`getCurrentWebviewWindow().listen` in `src/platform/ipc.ts`) receives exactly what it did before. Which windows get which events is unchanged.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 20:01:45 +08:00
Mr0Bread d15abe54e2 perf(vcs): read the restricted-mode scoped status with a pathspec (#5451)
In Restricted Mode, the refresh after a watcher batch (`status_paths`) ignored its paths and answered with the full gitoxide status, which walks the whole tree to report one saved file. In a 100k-file repository that took about 87 ms against about 15 ms for a trusted project. It now runs `git status` with the pathspec, as a trusted project does.
The audit (row S4) blamed the extra `git config --null --list` process. That process is not the cause: the full `status()` never runs it (it runs `gitoxide`), and the old restricted `status_paths` did not run it either. The cause is the early return to the full status in `Repo::status_paths`, left from #3267, when the scoped read was in-process and `git` was not allowed. #3280 moved the scoped read to `git`, with the filter overrides the restricted fallback already used, but the restricted bypass stayed.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-23 20:01:29 +08:00
faysouтаfaysou b501f51526 test(run): compile the output counting reader only on Unix (#5407)
The Windows Clippy job fails because the test reader `Counted` is compiled on Windows, where its only caller is excluded. The flooding-process test uses `awk` and already requires Unix. Apply the same condition to the reader and its `Read` implementation. The cross-platform queue shutdown test keeps its own reader.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:20 +08:00
faysouтаfaysou 50cd478773 test(vfs): allow watch events for an excluded directory itself (#5382)
The per-directory watcher skips the contents of excluded directories. A watch on the parent can still report the directory itself, which macOS did for `node_modules`. The regression test now accepts that event while continuing to reject events for descendants.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:10 +08:00
faysouтаfaysou 2c63f0eb22 chore(deps): update cookie to 0.18.3 for RUSTSEC-2026-0594 (#5431)
Update the transitive `cookie` dependency from 0.18.2 to 0.18.3. Cargo Deny reports the older release for possible nonce reuse when encrypting private cookies across a fork. The patched crate obtains those nonces from the operating system. [RustSec advisory](https://rustsec.org/advisories/RUSTSEC-2026-0594.html)

Co-authored-by: faysou <[email protected]>
2026-11-23 20:01:00 +08:00
faysouтаfaysou ed1730f273 fix(vcs): preserve the index timestamp when preparing a commit selection (#5383)
A commit preview or a commit of selected changes can omit a same-size edit made on the same filesystem clock tick as the Git index. Git uses the index timestamp to decide when it must inspect the file contents. The temporary copy now preserves that timestamp so Git detects the edit.

Co-authored-by: faysou <[email protected]>
2026-11-23 20:00:51 +08:00
akshathayadav378-boopтаakshathayadav378-boop d6d0cc7926 fix(vcs): use the Project view selection for Git file actions while it is the context (#5428)
Show History (and Add to VCS / the ignore actions) took the editor's file when the shortcut ran right after clicking a Project view row: the row publishes its selection on mousedown, but tree focus is a separate DOM event, so projectViewFocus was still false. File actions now use the Project view selection while the tree owns the context (its lead is set and the editor has no focus), the same rule External Tools use (shared projectViewContextLead helper).

Co-authored-by: akshathayadav378-boop <[email protected]>
2026-11-23 20:00:11 +08:00
l0ng-ai a21de32077 fix(editor): give the top and bottom breadcrumbs distinct keys (#5463)
The top and bottom breadcrumb bars are keyed separately, so Markdown and HTML tabs no longer log React's duplicate key error.
2026-11-23 19:38:19 +08:00
Bert Verhelstтаbertyhell 546ff9f314 fix(run): resolve External Tools file macros against the Project view selection (#5415)
External Tools expanded $FilePath$ and the other file macros from the editor's file even while the Project view was the user's context. They now take the Project view's selected file while it is the context (no editor focus, not a virtual document); caret macros apply only when the editor shows that same file.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 19:35:44 +08:00
l0ng-ai a144208170 fix(debugger): keep a rerun session's tab in place while its adapter starts (#5460)
Rerun keeps the finished tab in place and selected until the new session appears, which then takes its slot and the selection at once.
2026-11-23 19:33:10 +08:00
l0ng-ai fda2d2ff69 fix(run): scroll configuration choosers to their last item in short windows (#5457)
The configuration choosers' list fills the viewport left by a window-capped popup, so its last items scroll into view in short windows.
2026-11-23 19:28:33 +08:00
l0ng-ai 0fdf37f1bf fix(vcs): list every repository's branches and tags in Go to Hash/Branch/Tag (#5455)
Go to Hash/Branch/Tag reads refs from the repositories it searches (shown log tab, else the filtered ones, else every root) instead of an empty Repository filter, which offered only HEAD.
2026-11-23 19:24:50 +08:00
l0ng-ai 5c592bbc86 fix(editor): move a whole switch case in languages with flat case labels (#5453)
Move Statement on a case label in Go, JavaScript and Java moves the whole branch (stacked labels through its last line) past the neighbouring branch instead of only the label line.
2026-11-23 19:22:35 +08:00
l0ng-ai 819ccb8bb5 docs: refresh WeChat group QR code 2026-11-23 19:18:28 +08:00
l0ng-ai ae893f059f fix(agents): keep unrelated chat rows stable during text selection (#5438) 2026-11-23 18:56:34 +08:00
l0ng-ai fb2f567d5b fix(agents): hide Jump to Latest when the reply end is visible (#5442) 2026-11-23 18:51:44 +08:00
81 змінених файлів з 2844 додано та 212 видалено

No files matched your search

Бінарний файл не відображається.

До

Ширина:  |  Висота:  |  Розмір: 160 KiB

Після

Ширина:  |  Висота:  |  Розмір: 138 KiB

Створено
+2 -2
Переглянути файл
@@ -1104,9 +1104,9 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
[[package]]
name = "cookie"
version = "0.18.2"
version = "0.18.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a"
dependencies = [
"time",
"version_check",
+3
Переглянути файл
@@ -536,6 +536,9 @@ pub enum AgentEntry {
kind: String,
status: AgentToolStatus,
locations: Vec<IpcPath>,
/// Images returned by the tool, kept separately from its truncated text.
#[serde(default)]
images: Vec<AgentImage>,
/// Text the tool reported (command output…), truncated.
output: Option<String>,
diffs: Vec<AgentToolDiff>,
+30
Переглянути файл
@@ -1007,11 +1007,16 @@ impl Session {
let mut updates = Vec::new();
let mut finished = None;
let mut read_title = false;
let mut refresh_usage = false;
{
let mut st = self.st.lock();
let st = &mut *st;
match kind {
"system" => match msg.get("subtype").and_then(Value::as_str) {
Some("compact_boundary") => {
refresh_usage = msg.pointer("/compact_metadata/post_tokens").is_none_or(Value::is_null);
updates.extend(st.tr.on_message(&msg));
}
Some("init") => {
st.terminal_only = strings(msg.get("terminal_slash_commands"));
}
@@ -1115,6 +1120,31 @@ impl Session {
if read_title {
self.read_title();
}
if refresh_usage {
self.refresh_usage();
}
}
/// Sends what the context holds after a compaction that didn't report it, as Claude Code
/// counts it (`get_context_usage`); until then the meter would show the count from before.
fn refresh_usage(self: &Arc<Self>) {
let me = self.clone();
tokio::spawn(async move {
let Some(proc) = me.st.lock().proc.clone() else { return };
let usage = match proc.control(json!({ "subtype": "get_context_usage" })).await {
Ok(usage) => usage,
Err(e) => {
tracing::debug!("reading claude context usage after compaction: {e}");
return;
}
};
let n = |k: &str| usage.get(k).and_then(Value::as_u64);
let (Some(used), Some(size)) = (n("totalTokens"), n("maxTokens").filter(|m| *m > 0)) else { return };
let update = me.st.lock().tr.on_context_usage(used, size);
if let Some(shim) = me.shim() {
shim.notify(vec![update]);
}
});
}
/// Sends the session's title once it has one: the one in its transcript, or else one
+50
Переглянути файл
@@ -531,6 +531,38 @@ async fn sessions_without_a_title_get_one_generated() {
assert_eq!(request["request"]["persist"], true);
}
/// A compaction that doesn't report what the context holds now (no `post_tokens`): the
/// driver asks Claude Code, and the meter shows that instead of the count from before.
#[tokio::test(flavor = "multi_thread")]
async fn a_compaction_without_its_token_count_reads_the_context_usage() {
let mut processes = load_fixture("simple");
processes[0].extend([
Frame::Cli(json!({"type": "system", "subtype": "compact_boundary",
"compact_metadata": {"trigger": "manual", "pre_tokens": 120000}})),
Frame::Shim(json!({"type": "control_request", "request_id": "req_3",
"request": {"subtype": "get_context_usage"}})),
Frame::Cli(json!({"type": "control_response", "response": {"subtype": "success", "request_id": "req_3",
"response": {"categories": [], "totalTokens": 4200, "maxTokens": 200000, "model": "claude"}}})),
]);
let cli = replay_cli(processes);
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
let h =
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
let session = h.new_session().await;
h.prompt(&session, "Reply with exactly: hello there").await.unwrap();
let mut usage = Vec::new();
for _ in 0..100 {
usage = h.updates(&session, "usage_update");
if usage.last().is_some_and(|u| u["used"] == 4200) {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert!(cli.errors.lock().is_empty(), "{:?}", cli.errors.lock());
assert_eq!(usage.last().map(|u| (u["used"].clone(), u["size"].clone())), Some((json!(4200), json!(200000))));
}
#[tokio::test(flavor = "multi_thread")]
async fn replay_multi_turn() {
let r = replay("multi_turn").await;
@@ -1098,6 +1130,24 @@ fn streamed_text_is_not_sent_twice() {
assert_eq!(usage[0].update, json!({"sessionUpdate": "usage_update", "used": 15, "size": 1000}));
}
#[test]
fn a_compaction_replaces_the_context_usage() {
let mut t = Translator::new("s", PathBuf::from("/w"), true);
let assistant = json!({"type": "assistant", "parent_tool_use_id": null,
"message": {"id": "m1", "model": "x", "content": [], "usage": {"input_tokens": 900, "output_tokens": 50}}});
t.on_message(&assistant);
let result = json!({"modelUsage": {"x": {"contextWindow": 1000}}});
assert_eq!(t.on_result(&result)[0].update["used"], 950);
let boundary = |meta: Value| json!({"type": "system", "subtype": "compact_boundary", "compact_metadata": meta});
let out = t.on_message(&boundary(json!({"trigger": "manual", "pre_tokens": 950, "post_tokens": 120})));
assert_eq!(out[0].update, json!({"sessionUpdate": "usage_update", "used": 120, "size": 1000}));
// The `/compact` turn's result reports what compaction left, not the count from before.
assert_eq!(t.on_result(&result)[0].update["used"], 120);
// Without `post_tokens` nothing is known yet (the driver asks): the stale count stays out.
assert!(t.on_message(&boundary(json!({"trigger": "auto", "pre_tokens": 950}))).is_empty());
assert!(t.on_result(&result).is_empty());
}
#[test]
fn rate_limits_and_cost() {
let mut t = Translator::new("s", PathBuf::from("/w"), false);
+53
Переглянути файл
@@ -144,6 +144,22 @@ pub(super) fn result_fields(name: &str, input: &Value, block: &Value, structured
content.push(text(&t));
}
}
if let Some(blocks) = block.get("content").and_then(Value::as_array) {
for block in blocks {
if block.get("type").and_then(Value::as_str) != Some("image") {
continue;
}
let Some(source) = block.get("source") else { continue };
if source.get("type").and_then(Value::as_str) != Some("base64") {
continue;
}
let data = source.get("data").and_then(Value::as_str).unwrap_or_default();
let mime = source.get("media_type").and_then(Value::as_str).unwrap_or_default();
if !data.is_empty() && mime.starts_with("image/") {
content.push(json!({"type": "content", "content": {"type": "image", "mimeType": mime, "data": data}}));
}
}
}
let mut out = json!({ "status": if failed { "failed" } else { "completed" } });
if !content.is_empty() {
out["content"] = Value::Array(content);
@@ -230,6 +246,43 @@ mod tests {
assert_eq!(call_fields("WebSearch", &json!({"query": "q"}), cwd)["kind"], "fetch");
}
#[test]
fn image_tool_results_keep_text_and_inline_images() {
let result = result_fields(
"Read",
&json!({"file_path": "/w/preview.png"}),
&json!({"content": [
{"type": "text", "text": "Preview ready"},
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
]}),
None,
);
assert_eq!(result["status"], "completed");
assert_eq!(
result["content"],
json!([
text("Preview ready"),
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": "aW1hZ2U="}}
])
);
}
#[test]
fn failed_shell_tool_images_keep_fallback_error_text() {
let result = result_fields(
"Bash",
&json!({}),
&json!({"is_error": true, "content": [
{"type": "text", "text": "Preview command failed"},
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
]}),
Some(&json!({"stdout": "", "stderr": ""})),
);
assert_eq!(result["status"], "failed");
assert_eq!(result["content"][0], text("Preview command failed"));
assert_eq!(result["content"][1]["content"]["type"], "image");
}
#[test]
fn results() {
let input = json!({"file_path": "/w/n.txt", "content": "two"});
+17
Переглянути файл
@@ -458,6 +458,13 @@ impl Translator {
let last = self.children.get(&tool_use).map(|c| c.last_text.clone()).filter(|t| !t.is_empty());
self.finish_child(&tool_use, stop, last.or(summary))
}
// Compaction replaced the conversation with its summary: the context now holds
// `post_tokens`. Without it the stale count must not come back with the result;
// the driver asks Claude Code instead (`Session::refresh_usage`).
Some("compact_boundary") => {
self.used = msg.pointer("/compact_metadata/post_tokens").and_then(Value::as_u64);
self.usage_update().into_iter().collect()
}
// A turn's background tasks (`run_in_background`) outlive it: the task keeps
// the list and stays up while it isn't empty (see `Task::release_when_idle`).
Some("background_tasks_changed") => {
@@ -561,6 +568,16 @@ impl Translator {
self.usage_update().into_iter().collect()
}
/// The context usage Claude Code reports (`get_context_usage`), as a usage update.
pub fn on_context_usage(&mut self, used: u64, size: u64) -> Update {
self.used = Some(used);
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
if let Some(amount) = self.cost_usd {
update["cost"] = json!({ "amount": amount, "currency": "USD" });
}
Update { session: self.root.clone(), update }
}
fn usage_update(&self) -> Option<Update> {
let used = self.used?;
let size = self
+42 -3
Переглянути файл
@@ -1,6 +1,6 @@
//! Folds ACP `session/update` notifications into a task's entries.
use crate::model::{AgentEntry, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
use crate::model::{AgentEntry, AgentImage, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
use ide_core::IpcPath;
use serde_json::Value;
use std::collections::HashMap;
@@ -84,6 +84,7 @@ impl Timeline {
status: tool_status(update.get("status")).unwrap_or(AgentToolStatus::Pending),
locations: locations(update.get("locations")),
output: None,
images: Vec::new(),
diffs: Vec::new(),
started_ms: Some(crate::now_ms()),
ended_ms: None,
@@ -150,7 +151,7 @@ impl Timeline {
}
fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, ended_ms, .. } =
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
&mut self.entries[index]
else {
return;
@@ -173,10 +174,20 @@ impl Timeline {
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
let mut text = String::new();
let mut new_diffs = Vec::new();
let mut new_images = Vec::new();
for item in content {
match item.get("type").and_then(Value::as_str) {
Some("content") => {
if let Some(t) = content_text(item.get("content")) {
let content = item.get("content");
if let Some(image) = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image"))
&& let (Some(data), Some(mime)) =
(image.get("data").and_then(Value::as_str), image.get("mimeType").and_then(Value::as_str))
&& !data.is_empty()
&& mime.starts_with("image/")
{
new_images.push(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
}
if let Some(t) = content_text(content) {
if !text.is_empty() {
text.push('\n');
}
@@ -203,6 +214,9 @@ impl Timeline {
if !new_diffs.is_empty() {
*diffs = new_diffs;
}
if !new_images.is_empty() {
*images = new_images;
}
}
/// Adds or updates the card of subagent `id` from its `subagent_update`; returns the
@@ -439,6 +453,31 @@ mod tests {
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
}
#[test]
fn tool_images_survive_updates_text_truncation_and_serialization() {
use base64::Engine;
let mut t = Timeline::default();
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "preview", "title": "Render", "kind": "execute"}));
let mut old = serde_json::to_value(&t.entries[0]).unwrap();
old.as_object_mut().unwrap().remove("images");
let legacy: AgentEntry = serde_json::from_value(old).unwrap();
assert!(matches!(legacy, AgentEntry::Tool { images, .. } if images.is_empty()));
let data = base64::engine::general_purpose::STANDARD.encode(vec![0; MAX_OUTPUT]);
let update = json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "content": [
{"type": "content", "content": {"type": "text", "text": "x".repeat(MAX_OUTPUT + 100)}},
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": data}}
]});
t.apply(&update);
t.apply(&update);
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
assert_eq!(*status, AgentToolStatus::Completed);
let saved = serde_json::to_string(&t.entries[0]).unwrap();
assert_eq!(serde_json::from_str::<AgentEntry>(&saved).unwrap(), t.entries[0]);
}
#[test]
fn chunks_merge_into_one_message_until_another_entry_comes() {
let mut t = Timeline::default();
+2
Переглянути файл
@@ -1587,11 +1587,13 @@ mod tests {
}
/// A pipe stand-in that counts the bytes taken from it.
#[cfg(unix)]
struct Counted<R> {
inner: R,
taken: Arc<AtomicUsize>,
}
#[cfg(unix)]
impl<R: Read> Read for Counted<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = self.inner.read(buf)?;
+15 -5
Переглянути файл
@@ -478,12 +478,11 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
all.request = None;
all.stop_at = None;
let repo = r.gix()?;
let decorations = decorations(&repo)?;
let (decorations, generation) = r.ref_decorations(&repo)?;
let shallow_vec =
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect::<Vec<_>>()).unwrap_or_default();
let shallow: HashSet<ObjectId> = shallow_vec.iter().copied().collect();
let refs = r.log_refs()?;
let key = format!("{}:{refs:?}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
let key = format!("{}:{generation}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
let cached = index.views.get(&key).cloned();
let view = if let Some(cached) = cached {
cached
@@ -646,7 +645,7 @@ fn log_indexed(
let repo = r.gix()?;
let shallow: HashSet<ObjectId> =
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect()).unwrap_or_default();
let decorations = decorations(&repo)?;
let (decorations, _) = r.ref_decorations(&repo)?;
let range = q.range.as_deref().map(str::trim).filter(|s| !s.is_empty());
let revs: Vec<&str> = q.branch.iter().chain(&q.branches).map(|b| b.trim()).filter(|b| !b.is_empty()).collect();
let ranges: Vec<_> = q.ranges.iter().map(|s| s.trim()).filter(|s| !s.is_empty()).collect();
@@ -741,7 +740,7 @@ fn log_indexed_rows(
if tips.is_empty() && range.is_none() && ranges.is_empty() {
return Ok(Vec::new());
}
let decorations = decorations(&repo)?;
let (decorations, _) = r.ref_decorations(&repo)?;
let paths: Vec<String> = q
.path
.iter()
@@ -1406,8 +1405,19 @@ fn tips(repo: &gix::Repository, revs: &[&str]) -> IdeResult<Vec<ObjectId>> {
Ok(tips)
}
#[cfg(test)]
thread_local!(static DECORATION_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) });
/// How many times this thread listed all refs.
#[cfg(test)]
pub(crate) fn decorations_scans() -> usize {
DECORATION_SCANS.get()
}
/// Commit id → decoration labels.
pub(crate) fn decorations(repo: &gix::Repository) -> IdeResult<HashMap<ObjectId, Vec<String>>> {
#[cfg(test)]
DECORATION_SCANS.set(DECORATION_SCANS.get() + 1);
let mut map: HashMap<ObjectId, Vec<String>> = HashMap::new();
if let Ok(id) = repo.head_id() {
map.entry(id.detach()).or_default().push("HEAD".to_string());
+5 -5
Переглянути файл
@@ -939,6 +939,7 @@ mod preserve;
mod push_preview;
mod push_report;
mod rebase_editor;
mod ref_decorations;
mod worktree_config;
pub use ops::UNSTAGED_CHANGES_PREVENT_REBASE;
mod incoming;
@@ -1078,6 +1079,7 @@ pub struct Repo {
cli_status: std::sync::atomic::AtomicBool,
automatic_shelf: std::sync::RwLock<Option<shelf::AutomaticShelf>>,
log_index: std::sync::Mutex<log_index::LogIndex>,
ref_decorations: std::sync::Mutex<ref_decorations::RefDecorations>,
log_signatures: std::sync::Mutex<history::LogSignatureCache>,
conflict_mutation: std::sync::Mutex<()>,
amend_recovery: std::sync::Mutex<Option<commit_rewrite::PendingAmend>>,
@@ -1137,11 +1139,9 @@ impl Repo {
/// dirty-scope refresh after a watcher batch. An empty list is the full status.
pub fn status_paths(&self, paths: &[PathBuf]) -> IdeResult<Vec<FileStatus>> {
let _scope = self.execution_scope();
// Restricted Mode starts no program of the repository, and the scoped read is `git status`
// with a pathspec: answer with the full gitoxide status instead.
if !self.execution_allowed.load(std::sync::atomic::Ordering::Acquire) {
return status::status(self);
}
// Restricted Mode reads this through git too: `cli::command` strips what the repository's
// config could run, and the status call empties its clean/process filters. The full
// gitoxide status it used to answer with walked the whole tree for one changed file.
if paths.is_empty() {
return status::status_paths(self, &[]);
}
+264
Переглянути файл
@@ -0,0 +1,264 @@
//! Ref decorations of the history, reused while git's ref storage has not changed.
//!
//! Listing and peeling every ref costs about 25 µs each, which a history page paid in full
//! even for a one-row page. A page now stats `HEAD`, `packed-refs` and the directories under
//! `refs/` instead: git replaces a loose ref by renaming a lock file over it, which changes
//! the modification time of the ref's directory, and rewrites `packed-refs` the same way.
use crate::Repo;
use crate::repo::absolute;
use gix::ObjectId;
use ide_core::IdeResult;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
/// A timestamp this close to the time it was read cannot tell two writes apart: a later write
/// may leave the same value (coarse file systems, FAT's 2 s). Such a snapshot is never reused.
const RACY_WINDOW: Duration = Duration::from_secs(2);
type Stat = Option<(SystemTime, u64)>;
pub(crate) type Decorations = Arc<HashMap<ObjectId, Vec<String>>>;
#[derive(Default)]
pub(crate) struct RefDecorations {
snapshot: Option<Snapshot>,
/// Changes when the decorations do, so cached views of them can be keyed by it.
generation: u64,
}
struct Snapshot {
map: Decorations,
stamp: Vec<(PathBuf, Stat)>,
reusable: bool,
}
fn stat(path: &Path) -> Stat {
let metadata = std::fs::metadata(path).ok()?;
Some((metadata.modified().ok()?, metadata.len()))
}
/// `HEAD`, `packed-refs` and every directory under `refs/`.
fn stamp(git_dir: &Path, common_dir: &Path) -> Vec<(PathBuf, Stat)> {
let mut paths = vec![git_dir.join("HEAD"), common_dir.join("packed-refs")];
let mut pending = vec![common_dir.join("refs")];
while let Some(dir) = pending.pop() {
if let Ok(entries) = std::fs::read_dir(&dir) {
pending.extend(entries.flatten().filter(|e| e.file_type().is_ok_and(|t| t.is_dir())).map(|e| e.path()));
}
paths.push(dir);
}
paths.into_iter().map(|path| (path.clone(), stat(&path))).collect()
}
impl RefDecorations {
fn get(&mut self, repo: &gix::Repository, git_dir: &Path, common_dir: &Path) -> IdeResult<(Decorations, u64)> {
if let Some(snapshot) = &self.snapshot
&& snapshot.reusable
&& snapshot.stamp.iter().all(|(path, before)| stat(path) == *before)
{
return Ok((snapshot.map.clone(), self.generation));
}
// Stamped before the refs are read, so a write after the stamp shows in the next one.
let taken = SystemTime::now();
let stamp = stamp(git_dir, common_dir);
let map = crate::history::decorations(repo)?;
let reusable = stamp.iter().all(|(_, stat)| stat.is_none_or(|(modified, _)| modified + RACY_WINDOW <= taken));
let unchanged = self.snapshot.as_ref().is_some_and(|old| *old.map == map);
let map = match &self.snapshot {
Some(old) if unchanged => old.map.clone(),
_ => {
self.generation += 1;
Arc::new(map)
}
};
self.snapshot = Some(Snapshot { map: map.clone(), stamp, reusable });
Ok((map, self.generation))
}
}
impl Repo {
/// Commit id → decoration labels, and a number that changes whenever they do.
pub(crate) fn ref_decorations(&self, repo: &gix::Repository) -> IdeResult<(Decorations, u64)> {
let common_dir = absolute(repo.common_dir())?;
self.ref_decorations.lock().unwrap_or_else(|p| p.into_inner()).get(repo, &self.git_dir, &common_dir)
}
}
#[cfg(test)]
mod tests {
use crate::history::decorations_scans;
use crate::{LogOrder, LogQuery, Repo};
use std::path::Path;
use std::time::{Duration, SystemTime};
fn git(dir: &Path, args: &[&str]) -> String {
let out = std::process::Command::new("git")
.current_dir(dir)
.args(["-c", "init.defaultBranch=main", "-c", "user.name=T", "-c", "[email protected]"])
.args(["-c", "commit.gpgsign=false"])
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
fn commit(dir: &Path, message: &str) -> String {
std::fs::write(dir.join("f"), message).unwrap();
git(dir, &["add", "-A"]);
git(dir, &["commit", "-qm", message]);
git(dir, &["rev-parse", "HEAD"])
}
/// Sets the modification time of `HEAD`, `packed-refs` and every directory under `refs/`.
fn set_ref_times(repo: &Repo, time: SystemTime) {
let git = repo.git_dir.clone();
let mut paths = vec![git.join("HEAD"), git.join("packed-refs")];
let mut pending = vec![git.join("refs")];
while let Some(dir) = pending.pop() {
pending.extend(std::fs::read_dir(&dir).unwrap().flatten().filter(|e| e.path().is_dir()).map(|e| e.path()));
paths.push(dir);
}
let mut options = std::fs::File::options();
options.read(true);
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
const FILE_WRITE_ATTRIBUTES: u32 = 0x100;
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
options.access_mode(FILE_WRITE_ATTRIBUTES).custom_flags(FILE_FLAG_BACKUP_SEMANTICS);
}
for path in paths.into_iter().filter(|p| p.exists()) {
options.open(path).unwrap().set_modified(time).unwrap();
}
}
/// As if the refs were written long ago, then reads the history once so the decorations
/// are cached; a second read must not list the refs again.
fn settle(repo: &Repo) {
set_ref_times(repo, SystemTime::now() - Duration::from_secs(3600));
page(repo, 0, 1);
let scans = decorations_scans();
page(repo, 0, 1);
assert_eq!(decorations_scans(), scans, "the decorations were not reusable");
}
fn page(repo: &Repo, skip: u32, limit: u32) -> Vec<crate::Commit> {
repo.log(&LogQuery { skip, limit, summary_only: true, order: LogOrder::Topo, ..Default::default() }).unwrap()
}
fn labels(repo: &Repo, id: &str) -> Vec<String> {
let all = page(repo, 0, 0);
all.into_iter().find(|c| c.id == id).unwrap().refs
}
#[test]
fn warm_pages_do_not_list_the_refs() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
for i in 0..30 {
commit(dir, &format!("c{i}"));
}
for i in 0..20 {
git(dir, &["branch", &format!("b{i}")]);
}
let repo = Repo::discover(dir).unwrap().unwrap();
settle(&repo);
let after_first = decorations_scans();
for skip in [10, 20, 0, 5] {
assert_eq!(page(&repo, skip, 1).len(), 1);
assert_eq!(page(&repo, skip, 10).len(), 10);
}
assert_eq!(decorations_scans(), after_first, "a warm page listed the refs again");
}
#[test]
fn fresh_ref_timestamps_are_not_trusted() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let first = commit(dir, "first");
let repo = Repo::discover(dir).unwrap().unwrap();
set_ref_times(&repo, SystemTime::now());
page(&repo, 0, 10);
let scans = decorations_scans();
// A write within the timestamp's resolution would leave it unchanged: rescan every time.
page(&repo, 0, 10);
assert!(decorations_scans() > scans);
assert!(labels(&repo, &first).contains(&"main".to_string()));
}
#[test]
fn decorations_follow_every_kind_of_ref_change() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let first = commit(dir, "first");
let repo = Repo::discover(dir).unwrap().unwrap();
settle(&repo);
let first_labels = labels(&repo, &first);
assert!(first_labels.contains(&"HEAD".to_string()) && first_labels.contains(&"main".to_string()));
// A new commit moves HEAD and the branch.
settle(&repo);
let second = commit(dir, "second");
assert_eq!(labels(&repo, &first), Vec::<String>::new());
assert!(labels(&repo, &second).contains(&"main".to_string()));
// A new tag, then an annotated one, in a directory that did not exist before.
settle(&repo);
git(dir, &["tag", "v1", &first]);
assert_eq!(labels(&repo, &first), ["tag: v1"]);
settle(&repo);
git(dir, &["tag", "-a", "-m", "m", "rel/v2", &first]);
assert_eq!(labels(&repo, &first), ["tag: rel/v2", "tag: v1"]);
// A new branch, one moved to another commit, and one deleted.
settle(&repo);
git(dir, &["branch", "side", &first]);
assert!(labels(&repo, &first).contains(&"side".to_string()));
settle(&repo);
git(dir, &["branch", "-f", "side", &second]);
assert!(!labels(&repo, &first).contains(&"side".to_string()));
assert!(labels(&repo, &second).contains(&"side".to_string()));
settle(&repo);
git(dir, &["branch", "-D", "side"]);
assert!(!labels(&repo, &second).contains(&"side".to_string()));
// Refs in packed-refs: packing changes nothing visible, deleting one rewrites the file.
git(dir, &["branch", "packed", &first]);
git(dir, &["pack-refs", "--all"]);
settle(&repo);
assert!(labels(&repo, &first).contains(&"packed".to_string()));
git(dir, &["branch", "-D", "packed"]);
assert!(!labels(&repo, &first).contains(&"packed".to_string()));
// A detached HEAD and a tag deleted again.
settle(&repo);
git(dir, &["checkout", "-q", "--detach", &first]);
assert!(labels(&repo, &first).contains(&"HEAD".to_string()));
assert!(!labels(&repo, &second).contains(&"HEAD".to_string()));
settle(&repo);
git(dir, &["tag", "-d", "v1"]);
assert_eq!(labels(&repo, &first), ["HEAD", "tag: rel/v2"]);
}
#[test]
fn a_ref_change_between_pages_replaces_the_cached_view() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
git(dir, &["init", "-q"]);
let first = commit(dir, "first");
commit(dir, "second");
let repo = Repo::discover(dir).unwrap().unwrap();
settle(&repo);
page(&repo, 0, 10);
settle(&repo);
git(dir, &["tag", "v1", &first]);
let rows = page(&repo, 0, 10);
assert_eq!(rows.iter().find(|c| c.id == first).unwrap().refs, ["tag: v1"]);
}
}
+1
Переглянути файл
@@ -88,6 +88,7 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
cli_status: Default::default(),
automatic_shelf: Default::default(),
log_index: Default::default(),
ref_decorations: Default::default(),
log_signatures: Default::default(),
conflict_mutation: Default::default(),
amend_recovery: Default::default(),
+56
Переглянути файл
@@ -583,4 +583,60 @@ mod tests {
cli_status(&repo, &IgnoredNames::default()).unwrap();
assert!(marker.exists(), "control: git status did not run the filter");
}
fn committed_repo(dir: &Path) {
git(dir, &["init", "-q"]);
git(dir, &["config", "user.name", "Test User"]);
git(dir, &["config", "user.email", "[email protected]"]);
git(dir, &["config", "commit.gpgsign", "false"]);
std::fs::write(dir.join("a.txt"), "same\n").unwrap();
std::fs::write(dir.join("b.txt"), "same\n").unwrap();
commit_all(dir, "base");
}
/// The dirty-scope refresh in Restricted Mode reads the named paths only: it used to answer
/// with the full status, which walks the whole tree for one saved file.
#[test]
fn restricted_status_paths_reads_only_the_named_paths() {
let temp = tempfile::tempdir().unwrap();
let dir = temp.path();
committed_repo(dir);
std::fs::write(dir.join("a.txt"), "changed\n").unwrap();
std::fs::write(dir.join("b.txt"), "changed\n").unwrap();
let repo = Repo::discover(dir).unwrap().expect("repository found");
let one = repo.status_paths(&[repo.root().join("a.txt")]).unwrap();
assert_eq!(one.iter().map(|s| s.rel_path.as_str()).collect::<Vec<_>>(), ["a.txt"]);
assert_eq!(repo.status().unwrap().len(), 2, "the full status still lists both");
}
/// The scoped read is `git status`, which applies the repository's clean filters to compare
/// content: Restricted Mode must empty them there as it does for the full read.
#[cfg(unix)]
#[test]
fn restricted_status_paths_does_not_run_repository_filters() {
use std::os::unix::fs::PermissionsExt;
let temp = tempfile::tempdir().unwrap();
let dir = temp.path();
committed_repo(dir);
let marker = dir.join(".git/executed");
let script = dir.join(".git/marker.sh");
std::fs::write(&script, format!("#!/bin/sh\ntouch '{}'\ncat\n", marker.display())).unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
git(dir, &["config", "filter.marker.clean", script.to_str().unwrap()]);
std::fs::write(dir.join(".gitattributes"), "*.txt filter=marker\n").unwrap();
// Same size, new mtime: git has to read (and clean) the file to tell whether it changed.
std::thread::sleep(std::time::Duration::from_millis(1100));
std::fs::write(dir.join("a.txt"), "diff\n").unwrap();
let repo = Repo::discover(dir).unwrap().expect("repository found");
let paths = [repo.root().join("a.txt")];
let listed = repo.status_paths(&paths).unwrap();
assert_eq!(listed.len(), 1, "the change is still listed");
assert!(!marker.exists(), "Restricted Mode ran the repository's clean filter");
// Control: a trusted run does use the filter, so the fixture is live.
repo.set_execution_allowed(true);
repo.status_paths(&paths).unwrap();
assert!(marker.exists(), "control: git status did not run the filter");
}
}
+11 -2
Переглянути файл
@@ -591,8 +591,17 @@ fn select_into(
encoding: &dyn Fn(&Path) -> IdeResult<TextEncoding>,
) -> IdeResult<Vec<String>> {
let index = r.git_dir.join("index");
if index.exists() {
std::fs::copy(&index, &tmp.0)?;
match std::fs::File::open(index) {
Ok(mut source) => {
let metadata = source.metadata()?;
let mut copy = std::fs::File::create(&tmp.0)?;
copy.set_permissions(metadata.permissions())?;
std::io::copy(&mut source, &mut copy)?;
// Git uses the index timestamp to decide which same-size files need a content check.
copy.set_modified(metadata.modified()?)?;
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
let env = [("GIT_INDEX_FILE", tmp.0.as_os_str())];
fill_commit_index(r, &env, options, encoding)
+9
Переглянути файл
@@ -2017,11 +2017,17 @@ fn partial_commit_of_chosen_hunks_leaves_worktree_and_index_alone() {
#[test]
fn pending_changes_show_what_the_commit_would_hold_without_touching_the_index() {
let fx = Fixture::new();
fx.git(&["config", "core.checkStat", "minimal"]);
fx.git(&["config", "core.trustctime", "false"]);
let same_tick = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
let set_mtime =
|path| std::fs::File::options().write(true).open(fx.path(path)).unwrap().set_modified(same_tick).unwrap();
let base = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\n";
fx.write("f.txt", base);
fx.write("staged.txt", "s\n");
fx.write("old.txt", "moved\nfile\nwith\nlines\n");
fx.write("bin.dat", "\0\x01");
set_mtime("bin.dat");
fx.commit_all("base");
let repo = fx.repo();
let utf8 = |_: &Path| -> ide_core::IdeResult<&encoding_rs::Encoding> { Ok(encoding_rs::UTF_8) };
@@ -2032,6 +2038,9 @@ fn pending_changes_show_what_the_commit_would_hold_without_touching_the_index()
fx.git(&["add", "staged.txt"]);
fx.git(&["mv", "old.txt", "new.txt"]);
fx.write("bin.dat", "\0\x02");
// Git must recheck a same-size edit made on the same clock tick as the index.
set_mtime("bin.dat");
set_mtime(".git/index");
fx.write("added.txt", "new\n");
let index_before = std::fs::read(fx.dir.join(".git/index")).unwrap();
+2 -1
Переглянути файл
@@ -1753,7 +1753,8 @@ mod tests {
std::fs::write(root.join("src/a/after.rs"), "x").unwrap();
assert!(wait_for(&batches, |b| all_paths(b).contains(&root.join("src/a/after.rs"))));
let paths = all_paths(&batches.lock());
assert!(!paths.iter().any(|p| p.starts_with(root.join("node_modules"))), "{paths:?}");
let excluded = root.join("node_modules");
assert!(!paths.iter().any(|p| p != &excluded && p.starts_with(&excluded)), "{paths:?}");
assert!(!paths.contains(&root.join("lib/out/o.txt")));
// Un-ignoring lib/out keeps its existing filename watch.
+57
Переглянути файл
@@ -131,3 +131,60 @@ for (const home of [false, true]) {
}
}
}
test("short prompts fit before and after a completed agent exchange", async ({ workbench: page }) => {
await prepare(page, true, false);
const box = page.getByRole("textbox", { name: "Message", exact: true }).filter({ visible: true });
const scroller = page.locator(".cm-scroller").filter({ has: box });
const overflow = () =>
scroller.evaluate((el) => ({
x: el.scrollWidth - el.clientWidth,
y: el.scrollHeight - el.clientHeight,
}));
await expect(box.locator(".cm-placeholder")).toBeVisible();
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await box.fill("Reply with OK.");
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await page.getByRole("button", { name: "Start", exact: true }).click();
await expect(page.locator("html")).toHaveAttribute("data-submitted-prompt", /Reply with OK/);
await page.evaluate(() => document.dispatchEvent(new Event("test:agent-ack")));
await expect(page.getByRole("tab", { name: task.title })).toBeVisible();
await page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
const { useAgents } = await import(storePath);
useAgents.setState({
entries: new Map([
[
id,
[
{ type: "user", text: "Reply with OK.", attachments: [] },
{ type: "agent", text: "OK" },
],
],
]),
});
}, task.id);
await expect(page.getByText("OK", { exact: true })).toBeVisible();
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await page.getByRole("button", { name: "Agents", exact: true }).click();
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
await expect(box.locator(".cm-placeholder")).toBeVisible();
await expect(scroller).toHaveCSS("overflow-x", "hidden");
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await box.fill("Short draft");
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await box.fill("word".repeat(2000));
await expect(scroller).toHaveCSS("overflow-y", "auto");
await expect
.poll(async () => {
const { x, y } = await overflow();
return x === 0 && y > 0;
})
.toBe(true);
await box.fill("");
await expect(box.locator(".cm-placeholder")).toBeVisible();
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
});
+111
Переглянути файл
@@ -0,0 +1,111 @@
import { Buffer } from "node:buffer";
import type { AgentEntry, AgentTask } from "../src/bindings";
import { expect, test } from "./fixtures";
const task: AgentTask = {
id: "tool-images",
title: "Render preview",
provider: "claude",
model: null,
status: "ready",
isolation: "local",
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="900" height="220" viewBox="0 0 900 220">
<rect width="900" height="220" fill="#f1f5f9"/>
<g fill="#0f766e"><circle cx="150" cy="92" r="48"/><rect x="103" y="137" width="94" height="42" rx="8"/></g>
<g fill="#2563eb"><ellipse cx="450" cy="92" rx="28" ry="48"/><rect x="420" y="137" width="60" height="42" rx="8"/></g>
<g fill="#b45309"><circle cx="750" cy="92" r="48"/><rect x="703" y="137" width="94" height="42" rx="8"/></g>
<g fill="#0f172a" font-size="20" font-family="sans-serif" text-anchor="middle"><text x="150" y="208">Front</text><text x="450" y="208">Side</text><text x="750" y="208">Back</text></g></svg>`;
const image = { mimeType: "image/svg+xml", data: Buffer.from(svg).toString("base64"), name: null };
const entries: AgentEntry[] = [
{
type: "user",
text: "Render three views of the sample model.",
attachments: [],
sentMs: 1000,
doneMs: 2000,
steered: false,
},
{ type: "thought", text: "Rendering the sample views." },
{
type: "tool",
id: "render",
title: "Render preview",
kind: "read",
status: "completed",
locations: [],
output: null,
diffs: [],
images: [image],
},
{
type: "tool",
id: "inspect",
title: "Read preview metadata",
kind: "read",
status: "completed",
locations: [],
output: "Preview generated successfully.",
diffs: [],
},
{ type: "agent", text: "The preview is ready: front, side and back." },
];
for (const foldTurns of [true, false]) {
test(`tool images remain visible and open a full preview with turn folding=${foldTurns}`, async ({
workbench: page,
}) => {
if (!foldTurns) await page.setViewportSize({ width: 700, height: 750 });
await page.evaluate(
async ({ task, entries, foldTurns }) => {
const storePath = "/src/features/agents/store.ts";
const projectPath = "/src/platform/project.ts";
const ipcPath = "/src/platform/ipc.ts";
const store = await import(storePath);
const { useProject } = await import(projectPath);
const { commands } = await import(ipcPath);
commands.agentEntries = async () => ({ status: "ok", data: entries });
useProject.setState({ settings: { agents: { foldTurns, toolCalls: "grouped" } } });
store.useAgents.setState({
loaded: true,
error: null,
tasks: new Map([[task.id, task]]),
entries: new Map([[task.id, entries]]),
unread: new Set(),
});
store.openTaskInEditorLocation(task.id);
},
{ task, entries, foldTurns },
);
await expect(page.getByText("The preview is ready: front, side and back.", { exact: true })).toBeVisible();
const preview = page.getByRole("img", { name: "Image", exact: true });
await expect(preview).toBeVisible();
await expect(preview).toHaveJSProperty("naturalWidth", 900);
expect(await preview.evaluate((img) => img.closest("details") === null)).toBe(true);
const box = (await preview.boundingBox())!;
expect(box.x).toBeGreaterThanOrEqual(0);
expect(box.x + box.width).toBeLessThanOrEqual(page.viewportSize()!.width);
const fold = page.locator("details").first();
await expect(fold).not.toHaveAttribute("open");
await preview.click();
const dialog = page.getByRole("dialog", { name: "Image", exact: true });
await expect(dialog.getByRole("img")).toHaveJSProperty("naturalWidth", 900);
await dialog.getByText("Close", { exact: true }).click();
await expect(dialog).toHaveCount(0);
await fold.locator("summary").first().click();
await expect(preview).toHaveCount(1);
await fold.locator("summary").first().click();
await expect(preview).toBeVisible();
});
}
+1
Переглянути файл
@@ -274,6 +274,7 @@ test("completion clips long parameters before the suggestion name and return typ
});
await expect(row.locator(".cm-lsp-type")).toHaveText(returnType);
await page.setViewportSize({ width: 820, height: 760 });
await page.evaluate(() => document.fonts.ready);
await expect
.poll(() =>
row.evaluate((el) => {
+52
Переглянути файл
@@ -0,0 +1,52 @@
import type { Locator, Page } from "@playwright/test";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
/** Opens the sample with the server's lenses `titles` above its first line, at editor font `fontSize`. */
async function lensRow(page: Page, fontSize: number, titles: string[]): Promise<{ editor: Locator; row: Locator }> {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate(
async ({ fontSize, titles }) => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const settings = useProject.getState().settings;
useProject.setState({ settings: { ...settings, editor: { ...settings?.editor, fontSize } } });
const at = { line: 0, col: 0 };
window.__ipc.handlers.lsp_code_lens = () =>
titles.map((title) => ({ range: { start: at, end: at }, command: { title, command: "noop", arguments: [] } }));
},
{ fontSize, titles },
);
// An edit asks the server for its lenses again.
await editor.locator(".cm-line").first().click();
await page.keyboard.press("End");
await page.keyboard.type(" ");
const row = editor.locator(".cm-openidea-lens");
await expect(row).toContainText(titles[0]!);
return { editor, row };
}
test("a Code Vision row fits CJK hints at a large editor font", async ({ workbench: page }) => {
const { editor, row } = await lensRow(page, 20, ["10 个用法", "无用法"]);
const overflow = await row.evaluate((el) => {
const box = el.getBoundingClientRect();
return [...el.querySelectorAll(".cm-openidea-lensItem")].map((item) => {
const range = document.createRange();
range.selectNodeContents(item);
const text = range.getBoundingClientRect();
return Math.max(box.top - text.top, text.bottom - box.bottom);
});
});
expect(overflow).toHaveLength(2);
for (const px of overflow) expect(px).toBeLessThanOrEqual(0);
// The editor measured the taller row: the lines below it still sit beside their numbers.
const line = editor.locator(".cm-line", { hasText: "class OrderController" });
const number = editor.locator(".cm-lineNumbers .cm-gutterElement", { hasText: /^8$/ });
const [lineTop, numberTop] = [(await line.boundingBox())!.y, (await number.boundingBox())!.y];
expect(Math.abs(lineTop - numberTop)).toBeLessThanOrEqual(1);
});
test("a Code Vision row keeps its height at the default editor font", async ({ workbench: page }) => {
const { row } = await lensRow(page, 13, ["3 usages"]);
expect((await row.boundingBox())!.height).toBe(16);
});
+52
Переглянути файл
@@ -0,0 +1,52 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
// #5402: an External Tool run from Find Action resolves $FilePath$ against the focused component,
// the Project view's selected file while the tree has focus, else the editor's file.
test("External Tools take $FilePath$ from the Project view selection, else the editor", async ({ workbench: page }) => {
await page.getByRole("treeitem", { name: "README.md", exact: true }).dblclick();
const editor = page.locator(".cm-content");
await expect(editor).toBeFocused();
await stubDesktop(page);
await page.evaluate(async () => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const tool = { id: "echo", name: "Echo File Path", program: "echo", arguments: "$FilePath$ $FileName$" };
useProject.setState({ settings: { externalTools: [{ ...tool, openConsole: false, synchronizeAfter: false }] } });
let id = 0;
window.__ipc.handlers.run_start = ({ config }) => {
id++;
// Exits at once, so the next run of the same tool doesn't ask to stop this one.
window.__ipc.emit({ type: "runExited", run: id, code: 0 });
return {
id,
configId: (config as { id: string }).id,
name: (config as { name: string }).name,
pid: 4242,
running: true,
pty: false,
};
};
});
const runTool = async () => {
await page.keyboard.press("Meta+Shift+A");
const search = page.getByRole("dialog", { name: "Search Everywhere", exact: true });
await search.getByRole("combobox").fill("Echo File Path");
await expect(search.getByRole("option", { name: /Echo File Path/ })).toBeVisible();
await search.getByRole("combobox").press("Enter");
await expect(search).toBeHidden();
};
const startedArgs = async () =>
(await ipcCalls(page, "run_start")).map((c) => (c as { config: { args: string[] } }).config.args);
await page.getByRole("treeitem", { name: "build.gradle.kts", exact: true }).click();
await runTool();
await expect.poll(startedArgs).toEqual([["/dev/acme-api/build.gradle.kts", "build.gradle.kts"]]);
await editor.click();
await runTool();
await expect.poll(startedArgs).toEqual([
["/dev/acme-api/build.gradle.kts", "build.gradle.kts"],
["/dev/acme-api/README.md", "README.md"],
]);
});
+51
Переглянути файл
@@ -0,0 +1,51 @@
import type { Page } from "@playwright/test";
import { expect, stubDesktop, test } from "./fixtures";
async function stubProjectTypes(page: Page, types: string[]) {
await stubDesktop(page);
await page.evaluate((types) => {
const h = window.__ipc.handlers;
h.index_file_extensions = () => types.map((extension, i) => ({ extension, files: 100 - i }));
h.languages = () => types.map((extension) => ({ id: extension, name: extension, extensions: [extension] }));
h.search_validate = () => null;
}, types);
}
async function openMaskMenu(page: Page) {
await page.keyboard.press("Meta+Shift+f");
const dialog = page.getByRole("dialog", { name: "Find in Files" });
await dialog.getByRole("button", { name: "Recent file masks" }).click();
const menu = page.getByRole("menu").last();
await expect(menu).toBeVisible();
return menu;
}
test("the file mask menu offers every known file type in the project", async ({ workbench: page }) => {
await stubProjectTypes(page, ["rs", "md", "json", "toml", "yml", "properties"]);
const menu = await openMaskMenu(page);
await expect(menu.getByRole("menuitem")).toHaveText(["*.rs", "*.md", "*.json", "*.toml", "*.yml", "*.properties"]);
await menu.getByRole("menuitem", { name: "*.properties" }).click();
await expect(page.getByRole("textbox", { name: "File mask" })).toHaveValue("*.properties");
});
test("a long file mask menu stays inside the window and scrolls to its last type", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1040, height: 520 });
const types = Array.from({ length: 40 }, (_, i) => `type${String(i).padStart(2, "0")}`);
await stubProjectTypes(page, types);
const menu = await openMaskMenu(page);
const popup = menu.locator("..");
await expect(menu.getByRole("menuitem")).toHaveCount(40);
await expect
.poll(async () => {
const { y, height } = (await popup.boundingBox())!;
return y >= 0 && y + height <= 520;
})
.toBe(true);
await menu.getByRole("menuitem").first().focus();
await page.keyboard.press("End");
const last = menu.getByRole("menuitem", { name: "*.type39" });
await expect(last).toBeFocused();
await expect(last).toBeInViewport();
await expect.poll(async () => popup.evaluate((node) => node.scrollTop)).toBeGreaterThan(0);
});
+39 -6
Переглянути файл
@@ -5,14 +5,29 @@ test.use({ video: "on" });
test("offers file templates for the selected workspace member", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const markers: Record<string, string> = {
"/work/api": "go.mod",
"/work/web": "pom.xml",
"/work/library": "pom.xml",
const markers: Record<string, string[]> = {
"/work/api": ["go.mod"],
"/work/web": ["pom.xml"],
"/work/library": ["pom.xml"],
"/work/tutor": ["package.json", "vite.config.ts"],
};
window.__ipc.handlers.fs_read_dir = ({ path }) => {
const name = markers[String(path)];
return name ? [{ name, path: `${path}/${name}`, kind: "file", size: 0, mtimeMs: 0 }] : [];
const files = (markers[String(path)] ?? []).map((name) => ({
name,
path: `${path}/${name}`,
kind: "file",
size: 0,
mtimeMs: 0,
}));
return path === "/work/tutor"
? [...files, { name: "src", path: "/work/tutor/src", kind: "dir", size: 0, mtimeMs: 0 }]
: files;
};
const backend = "/src/editor/core/backend.ts";
const { docBackend } = await import(/* @vite-ignore */ backend);
window.__ipc.handlers.fs_create_file = ({ path }) => {
docBackend().files.set(String(path), "");
return null;
};
window.__ipc.handlers.run_configs = () => [
{
@@ -54,6 +69,7 @@ test("offers file templates for the selected workspace member", async ({ workben
await expect(page.getByRole("menuitem", { name: "Go Module", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "JSON File", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "Java Class", exact: true })).toHaveCount(0);
await expect(page.getByRole("menuitem", { name: "Svelte Component", exact: true })).toHaveCount(0);
await expect(page.getByRole("menuitem", { name: "Tomcat Context Descriptor", exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
@@ -73,6 +89,23 @@ test("offers file templates for the selected workspace member", async ({ workben
await expect(popup.getByText("Java Class", { exact: true })).toBeVisible();
await expect(popup.getByText("Tomcat Context Descriptor", { exact: true })).toHaveCount(0);
await expect(popup.getByText("Go File", { exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
const tutor = page.getByRole("treeitem", { name: "tutor /work/tutor", exact: true });
if ((await tutor.getAttribute("aria-expanded")) !== "true") await tutor.locator("[data-tree-toggle]").click();
await newMenu("/work/tutor/src");
const component = page.getByRole("menuitem", { name: "Svelte Component", exact: true });
await expect(component).toBeVisible();
await page.screenshot({ path: test.info().outputPath("svelte-new-menu.png"), animations: "disabled" });
await component.click();
const svelte = page.getByRole("dialog", { name: "New Svelte Component", exact: true });
const name = svelte.getByRole("textbox", { name: "Name", exact: true });
await name.fill("+page.svelte");
await name.press("Enter");
await expect(svelte).toBeHidden();
expect(await ipcCalls(page, "fs_create_file")).toEqual([{ path: "/work/tutor/src/+page.svelte" }]);
await expect(page.getByRole("tab", { name: "+page.svelte" })).toHaveAttribute("aria-selected", "true");
await expect(page.locator(".cm-content")).toContainText("<script>");
});
test("uses the single project's type in the keyboard New popup", async ({ workbench: page }) => {
+6 -2
Переглянути файл
@@ -90,6 +90,7 @@ test("Git ignore submenu offers shared and local destinations for files and fold
});
test("keeps New open on a slow diagonal path across sibling items", async ({ workbench: page }) => {
await page.clock.install();
await page.getByRole("treeitem", { name: "README.md", exact: true }).click({ button: "right" });
const parent = page.getByRole("menuitem", { name: "New", exact: true });
const box = (await parent.boundingBox())!;
@@ -101,13 +102,16 @@ test("keeps New open on a slow diagonal path across sibling items", async ({ wor
.filter({ has: page.getByRole("menuitem", { name: "Directory", exact: true }) });
const target = (await submenu.getByRole("menuitem").last().boundingBox())!;
const end = { x: target.x + 20, y: target.y + target.height / 2 };
// Keep the gesture cadence independent of the runner's input and assertion round trips.
await page.clock.pauseAt(new Date(Date.now() + 1000));
for (let step = 1; step <= 10; step++) {
await page.mouse.move(start.x + ((end.x - start.x) * step) / 10, start.y + ((end.y - start.y) * step) / 10);
await page.waitForTimeout(75);
await page.clock.runFor(75);
await expect(parent).toHaveAttribute("aria-expanded", "true");
}
await page.waitForTimeout(350);
await page.clock.runFor(350);
await expect(parent).toHaveAttribute("aria-expanded", "true");
await page.clock.resume();
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
});
+1 -1
Переглянути файл
@@ -14,7 +14,7 @@ test("double Shift opens Search Everywhere with its tabs; Escape closes it", asy
});
test("Search Everywhere finds and runs an action", async ({ workbench: page }) => {
await doubleShift(page);
await page.locator("header").getByRole("button", { name: "Search Everywhere", exact: true }).click();
const dialog = page.getByRole("dialog", { name: "Search Everywhere" });
await dialog.getByRole("combobox").fill("Language Servers");
const option = dialog.getByRole("option", { name: /Language Servers/ }).first();
+73 -7
Переглянути файл
@@ -155,6 +155,23 @@ fn flash_taskbar_unless_focused(app: &AppHandle) {
});
}
/// Sends `event` to `peers` (failures ignored: a window may be closing) and then to `owner`,
/// whose result is returned. The event is serialised once; `send` gets each window's copy of the
/// JSON, which Tauri's `emit_to` would otherwise re-serialise per window (large for
/// diagnostics of a big file).
fn fan_out<T: serde::Serialize>(
event: &T,
peers: &[String],
owner: &str,
mut send: impl FnMut(&str, String) -> tauri::Result<()>,
) -> tauri::Result<()> {
let json = serde_json::to_string(event)?;
for peer in peers {
let _ = send(peer, json.clone());
}
send(owner, json)
}
impl EventSink for TauriSink {
fn emit(&self, event: IdeEvent) {
if matches!(
@@ -180,13 +197,12 @@ impl EventSink for TauriSink {
}
let result = match &self.window {
Some(label) => {
for target in crate::windows::document_windows(&self.app, label)
.into_iter()
.filter(|_| !matches!(&event, IdeEvent::McpRequest { .. } | IdeEvent::McpRequestClosed { .. }))
{
let _ = self.app.emit_to(target.as_str(), IDE_EVENT, &event);
}
self.app.emit_to(label.as_str(), IDE_EVENT, &event)
let peers = if matches!(&event, IdeEvent::McpRequest { .. } | IdeEvent::McpRequestClosed { .. }) {
Vec::new()
} else {
crate::windows::document_windows(&self.app, label)
};
fan_out(&event, &peers, label, |window, json| self.app.emit_str_to(window, IDE_EVENT, json))
}
None => self.app.emit(IDE_EVENT, &event),
};
@@ -240,6 +256,56 @@ mod tests {
}
}
/// Counts how often it is serialised.
struct CountingEvent<'a> {
event: &'a IdeEvent,
serialised: AtomicUsize,
}
impl serde::Serialize for CountingEvent<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.serialised.fetch_add(1, Ordering::Relaxed);
self.event.serialize(serializer)
}
}
#[test]
fn fan_out_serialises_once_for_every_window() {
let event = diagnostics("/p/a.rs", "rust-analyzer", "unused");
let counting = CountingEvent { event: &event, serialised: AtomicUsize::new(0) };
let peers: Vec<String> = (1..=7).map(|n| format!("comparison-project-1-{n}")).collect();
let mut sent = Vec::new();
fan_out(&counting, &peers, "project-1", |window, json| {
sent.push((window.to_owned(), json));
Ok(())
})
.unwrap();
assert_eq!(counting.serialised.load(Ordering::Relaxed), 1);
let expected = serde_json::to_string(&event).unwrap();
let windows: Vec<&str> = sent.iter().map(|(window, _)| window.as_str()).collect();
assert_eq!(windows.len(), 8);
assert_eq!(windows.last(), Some(&"project-1"));
assert_eq!(windows[..7], peers.iter().map(String::as_str).collect::<Vec<_>>()[..]);
assert!(sent.iter().all(|(_, json)| json == &expected));
}
#[test]
fn fan_out_ignores_peer_failures_and_returns_the_owners_result() {
let event = task("indexing", false);
let peers = vec!["comparison-project-1-1".to_owned(), "comparison-project-1-2".to_owned()];
let mut reached = Vec::new();
let result = fan_out(&event, &peers, "project-1", |window, _| {
reached.push(window.to_owned());
if window == "project-1" { Err(tauri::Error::WebviewNotFound) } else { Err(tauri::Error::WindowNotFound) }
});
assert!(matches!(result, Err(tauri::Error::WebviewNotFound)));
assert_eq!(reached, ["comparison-project-1-1", "comparison-project-1-2", "project-1"]);
}
#[tokio::test]
async fn coalesces_diagnostics_by_path_and_source() {
let (sink, events) = setup();
+2
Переглянути файл
@@ -2529,6 +2529,8 @@ chosen: string | null } | { type: "thought"; text: string;
startedMs?: number | null } | { type: "tool"; id: string; title: string;
/** ACP tool kind: `read`, `edit`, `execute`, `search`, `fetch`, `think`… */
kind: string; status: AgentToolStatus; locations: IpcPath[];
/** Images returned by the tool, kept separately from its truncated text. */
images?: AgentImage[];
/** Text the tool reported (command output…), truncated. */
output: string | null; diffs: AgentToolDiff[];
/** When the call started and ended (ms since the epoch); `None` in tasks saved before. */
+10 -2
Переглянути файл
@@ -238,11 +238,13 @@ function buildDecorations(state: EditorState): DecorationSet {
const lensTheme = EditorView.theme({
// IDEA paints code vision with the colour scheme's Inline hints attribute.
// At least 16px, and taller when the hint font needs it: the row grows with its items, so a
// large editor font or a fallback font that inks below the baseline (CJK) is never cut off.
".cm-openidea-lens": {
display: "flex",
alignItems: "center",
gap: "12px",
height: "16px",
minHeight: "16px",
color: "var(--fg-inlay, var(--fg-muted))",
WebkitUserSelect: "none",
userSelect: "none",
@@ -276,7 +278,10 @@ const lensTheme = EditorView.theme({
// Pinned to the line, the hint may run past the editor's edge (IDEA clips it there); cap it so a
// long one cannot stretch across the whole window first.
maxWidth: "min(60ch, 50vw)",
overflow: "hidden",
// The box is 1em tall (the anchor's `lineHeight: 1`): clip only past the side, so a glyph that
// inks above or below its em box (CJK fallback fonts) still shows whole.
overflowX: "clip",
overflowY: "visible",
pointerEvents: "auto",
},
".cm-openidea-lensItem": {
@@ -293,6 +298,9 @@ const lensTheme = EditorView.theme({
fontFamily: "var(--font-ui)",
fontSize: "calc(1em - 1px)",
},
// The row's items size to the fonts their text is drawn with (fallback fonts included), not to the
// editor's line height, which `font: inherit` brings along.
".cm-openidea-lens > .cm-openidea-lensItem": { lineHeight: "normal" },
".cm-openidea-lensAction": { cursor: "pointer" },
".cm-openidea-lensAction:hover": { color: "var(--accent)", textDecoration: "underline" },
".cm-openidea-lensIcon-run": { color: "var(--success)" },
+74
Переглянути файл
@@ -417,6 +417,79 @@ function leadingCommentStart(state: EditorState, a: number): number {
export type StatementMove = { spec: TransactionSpec } | "noop" | "line";
/** A `case` / `default` label whose branch body follows as its siblings (Go, JavaScript, Java). */
const CASE_LABEL = /^(Case|CaseLabel|DefaultLabel|SwitchLabel)$/;
/**
* Move Statement on a `case` label of a switch whose branches are flat
* (label, then the body as siblings): the branch, from its first stacked
* label to its last non-blank line, swaps with the neighbouring branch, as
* IDEA's case block mover does. `noop` at the first / last branch.
*/
function planCaseMove(state: EditorState, label: Node, up: boolean): StatementMove {
const doc = state.doc;
const block = label.parent!;
const close = doc.lineAt(block.to).number;
const isLabel = (l: number) => {
const n = statementStartingAt(state, l);
return !!n && CASE_LABEL.test(n.type.name) && n.parent?.from === block.from && n.parent.to === block.to;
};
const start = (l: number) => {
while (l > 1 && isLabel(l - 1)) l--;
return l;
};
// The line where the branch starting at `l` ends: its last non-blank line before the next branch or the closing brace.
const end = (l: number) => {
let k = l + 1;
while (k < close && isLabel(k)) k++;
while (k < close && !isLabel(k)) k++;
k--;
while (k > l && firstToken(state, k) === null) k--;
return k;
};
const a = start(doc.lineAt(label.from).number);
const b = end(a);
let s: number;
let e: number;
if (up) {
let p = a - 1;
while (p > 0 && doc.line(p).from > block.from && !isLabel(p)) p--;
if (p < 1 || doc.line(p).from <= block.from || !isLabel(p)) return "noop";
s = start(p);
e = end(s);
} else {
let n = b + 1;
while (n < close && !isLabel(n)) n++;
if (n >= close) return "noop";
s = n;
e = end(n);
}
const [first, second] = up
? [
{ s, e },
{ s: a, e: b },
]
: [
{ s: a, e: b },
{ s, e },
];
const from = doc.line(first.s).from;
const to = doc.line(second.e).to;
const textFirst = state.sliceDoc(from, doc.line(first.e).to);
const textSecond = state.sliceDoc(doc.line(second.s).from, to);
const between = state.sliceDoc(doc.line(first.e).to, doc.line(second.s).from);
const head = state.selection.main.head;
const movedFrom = up ? from : from + textSecond.length + between.length;
return {
spec: {
changes: { from, to, insert: textSecond + between + textFirst },
selection: EditorSelection.cursor(movedFrom + (head - doc.line(a).from)),
scrollIntoView: true,
userEvent: "move.line",
},
};
}
/**
* Move Statement as in IDEA: the statement around the caret (whole lines)
* moves past the next statement; into a block when the neighbour is a block
@@ -429,6 +502,7 @@ export function planStatementMove(state: EditorState, up: boolean): StatementMov
const head = state.selection.main.head;
const cur = statementAround(state, head);
if (!cur) return "line";
if (CASE_LABEL.test(cur.type.name) && cur.parent) return planCaseMove(state, cur, up);
const doc = state.doc;
if (/^[{}]$/.test(cur.type.name)) {
for (let g: Node | null = cur.parent; g; g = g.parent)
+29
Переглянути файл
@@ -67,6 +67,7 @@ function show(view: EditorView): string {
const javascript = await languages.find((l) => l.name === "JavaScript")!.load();
const yaml = await languages.find((l) => l.name === "YAML")!.load();
const goLang = await languages.find((l) => l.name === "Go")!.load();
describe("Move Statement", () => {
it("moves a multi-line statement as a whole, never one of its lines", () => {
@@ -94,6 +95,34 @@ describe("Move Statement", () => {
expect(v.state.doc.toString()).toBe("function f() {\n a();\n}\nb();");
});
it("moves a Go switch case with its whole body past the neighbouring case", () => {
const go = make(
"func f(n int) int {\n\tswitch n {\n\tcase 0:\n\t\treturn 0\n\tca|se 1:\n\t\tv := 1\n\t\treturn v\n\tdefault:\n\t\treturn -1\n\t}\n}",
goLang,
);
moveStatementUp(go);
expect(show(go)).toBe(
"func f(n int) int {\n\tswitch n {\n\tca|se 1:\n\t\tv := 1\n\t\treturn v\n\tcase 0:\n\t\treturn 0\n\tdefault:\n\t\treturn -1\n\t}\n}",
);
moveStatementUp(go);
expect(go.state.doc.toString()).toContain("switch n {\n\tcase 1:\n\t\tv := 1");
moveStatementDown(go);
moveStatementDown(go);
expect(show(go)).toBe(
"func f(n int) int {\n\tswitch n {\n\tcase 0:\n\t\treturn 0\n\tdefault:\n\t\treturn -1\n\tca|se 1:\n\t\tv := 1\n\t\treturn v\n\t}\n}",
);
moveStatementDown(go);
expect(go.state.doc.toString()).toContain("\t\treturn v\n\t}\n}");
});
it("moves a JavaScript case with its stacked labels and blank line kept between branches", () => {
const v = make("switch (x) {\n case 1:\n a();\n break;\n\n case 2:\n |case 3:\n b();\n}", javascript);
moveStatementUp(v);
expect(v.state.doc.toString()).toBe(
"switch (x) {\n case 2:\n case 3:\n b();\n\n case 1:\n a();\n break;\n}",
);
});
it("passes a neighbouring function as a whole", () => {
const v = make("|a();\nfunction f() {\n b();\n}", javascript);
moveStatementDown(v);
+113 -5
Переглянути файл
@@ -68,18 +68,30 @@ function type(view: EditorView, text: string) {
);
}
/** One Backspace before every caret. */
/** One Backspace at every caret, or over every selection. */
function backspace(view: EditorView) {
const { state } = view;
view.dispatch(
state.changeByRange((r) => ({
changes: { from: Math.max(0, r.head - 1), to: r.head },
range: EditorSelection.cursor(Math.max(0, r.head - 1)),
})),
state.changeByRange((r) => {
const from = r.empty ? Math.max(0, r.head - 1) : r.from;
return { changes: { from, to: r.to }, range: EditorSelection.cursor(from) };
}),
{ userEvent: "delete.backward" },
);
}
/** One Delete after every caret. */
function deleteForward(view: EditorView) {
const { state } = view;
view.dispatch(
state.changeByRange((r) => ({
changes: { from: r.head, to: Math.min(state.doc.length, r.head + 1) },
range: EditorSelection.cursor(r.head),
})),
{ userEvent: "delete.forward" },
);
}
describe("linked html tags", () => {
it("renames the closing tag while the opening one is typed", () => {
const v = make('<div| class="container">\n Content\n</div>');
@@ -192,6 +204,84 @@ describe("linked html tags", () => {
expect(closing.state.doc.toString()).toBe("<div>content</di>v>");
});
// #5314: removing a tag piece by piece is a deletion, not a rename. Once its `>` (or `</`)
// is gone the tag is incomplete, and the name edits after that must not follow.
describe("deleting a whole tag", () => {
it("leaves the opening tag alone while the closing tag is backspaced away", () => {
const v = make("<div>x</div>|");
for (let i = 0; i < "</div>".length; i++) backspace(v);
expect(show(v)).toBe("<div>x|");
});
it("leaves the closing tag alone while the opening tag is backspaced away", () => {
const v = make("<div>|x</div>");
for (let i = 0; i < "<div>".length; i++) backspace(v);
expect(show(v)).toBe("|x</div>");
});
it("leaves the opening tag alone when the closing tag is deleted forwards", () => {
const v = make("<div>x|</div>\n<p>y</p>");
for (let i = 0; i < "</div>".length; i++) deleteForward(v);
expect(v.state.doc.toString()).toBe("<div>x\n<p>y</p>");
});
it("leaves the closing tag alone while an opening tag followed by children is backspaced away", () => {
const v = make("<div>|\n <span>y</span>\n</div>");
for (let i = 0; i < "<div>".length; i++) backspace(v);
expect(show(v)).toBe("|\n <span>y</span>\n</div>");
const inline = make("<div>|<span>y</span></div>");
for (let i = 0; i < "<div>".length; i++) backspace(inline);
expect(show(inline)).toBe("|<span>y</span></div>");
});
it("leaves the other tag alone when a selection covering a tag is deleted", () => {
const v = make("<div>x[</div>]");
backspace(v);
expect(show(v)).toBe("<div>x|");
const open = make("[<div>]x</div>");
backspace(open);
expect(show(open)).toBe("|x</div>");
});
it("leaves the other tag alone when a cut runs from inside the name past the tag", () => {
const v = make("<div>x</d[iv>\n]<p>y</p>");
backspace(v);
expect(v.state.doc.toString()).toBe("<div>x</d<p>y</p>");
});
it("does not rename into or out of a tag that lost its `>`", () => {
const v = make("<div|>x</div");
type(v, "s");
expect(v.state.doc.toString()).toBe("<divs>x</div");
const open = make("<div\n x</di|v>");
backspace(open);
expect(open.state.doc.toString()).toBe("<div\n x</dv>");
});
it("deletes the closing tags at every caret, leaving the opening tags alone", () => {
const v = make("<p>a</p>|\n<b>c</b>|");
for (let i = 0; i < "</p>".length; i++) backspace(v);
expect(show(v)).toBe("<p>a|\n<b>c|");
});
it("undo brings back the deleted closing tag and keeps the opening one", () => {
const v = make("<div>x[</div>]", history());
backspace(v);
expect(v.state.doc.toString()).toBe("<div>x");
expect(undo(v)).toBe(true);
expect(v.state.doc.toString()).toBe("<div>x</div>");
});
it("still renames after the `>` is typed back", () => {
const v = make("<div>x</div|");
type(v, ">");
expect(v.state.doc.toString()).toBe("<div>x</div>");
v.dispatch({ selection: { anchor: "<div".length } });
type(v, "s");
expect(v.state.doc.toString()).toBe("<divs>x</divs>");
});
});
it("undoes the pair as one step and redoes it", () => {
const v = make("<div|></div>", history());
type(v, "x");
@@ -219,6 +309,12 @@ describe("linked html tags", () => {
type(v, "s");
expect(v.state.doc.toString()).toBe('<divs class="a">x</divs>');
});
it(`leaves the opening tag alone while the closing tag is backspaced away in ${name}`, () => {
const v = makeWith([language(), linkedTags], '<div class="a">x</div>|');
for (let i = 0; i < "</div>".length; i++) backspace(v);
expect(v.state.doc.toString()).toBe('<div class="a">x');
});
}
});
@@ -261,6 +357,18 @@ describe("linked html tags", () => {
expect(f.state.doc.toString()).toBe("const a = <p>x</>;");
});
it("leaves the other tag alone while a tag is backspaced away", () => {
const v = tsx("const a = <div>x</div>|;");
for (let i = 0; i < "</div>".length; i++) backspace(v);
expect(v.state.doc.toString()).toBe("const a = <div>x;");
const m = tsx("const a = (\n <div>|\n <span>y</span>\n </div>\n);");
for (let i = 0; i < "<div>".length; i++) backspace(m);
expect(m.state.doc.toString()).toBe("const a = (\n \n <span>y</span>\n </div>\n);");
const w = tsx("const a = <Foo>|x</Foo>;");
for (let i = 0; i < "<Foo>".length; i++) backspace(w);
expect(w.state.doc.toString()).toBe("const a = x</Foo>;");
});
it("undoes both tags in one step", () => {
const v = tsx("const a = <div|></div>;");
type(v, "x");
+17 -7
Переглянути файл
@@ -10,9 +10,9 @@
* A transaction whose change lies inside one tag's name is extended with
* the same edit at the same offset in the counterpart's name — one
* transaction, so undo takes both back together. Without a matching tag (void
* and self-closing tags, unclosed elements, a stray close tag) or with the two
* names already different (malformed markup) nothing follows: the tags stay as
* they are.
* and self-closing tags, unclosed elements, a stray close tag), with either tag
* missing its `>` (a tag being deleted piece by piece), or with the two names
* already different (malformed markup) nothing follows: the tags stay as they are.
*/
import { EditorState, type Extension, type Transaction } from "@codemirror/state";
import { syntaxTree } from "@codemirror/language";
@@ -39,21 +39,31 @@ function tagNameAround(tree: Tree, from: number, to: number): SyntaxNode | null
return null;
}
/** The matching tag's name of the same element, or null without one. */
/**
* Whether a tag still ends in its `>`. A tag that lost it — `</div` while Backspace
* works through `</div>` — is being deleted, not renamed.
*/
function isComplete(tag: SyntaxNode | null): tag is SyntaxNode {
const last = tag?.lastChild?.name;
return last === "EndTag" || last === "JSXEndTag";
}
/** The matching tag's name of the same element, or null without one or while either tag is incomplete. */
function counterpartName(name: SyntaxNode): SyntaxNode | null {
const tag = name.parent;
const element = tag?.parent;
if (!tag || !element) return null;
if (!isComplete(tag) || !element) return null;
if (element.name === "JSXElement") {
const other = element.getChild(tag.name === "JSXOpenTag" ? "JSXCloseTag" : "JSXOpenTag");
for (let c = other?.firstChild; c; c = c.nextSibling) if (JSX_NAMES.has(c.name)) return c;
if (!isComplete(other)) return null;
for (let c = other.firstChild; c; c = c.nextSibling) if (JSX_NAMES.has(c.name)) return c;
return null;
}
if (element.name !== "Element") return null;
const other = element.getChild(
/^Open/.test(tag.name) ? tag.name.replace("Open", "Close") : tag.name.replace("Close", "Open"),
);
return other?.getChild("TagName") ?? null;
return isComplete(other) ? other.getChild("TagName") : null;
}
/** Insertions at a name's edge must extend the name; structural characters end it. */
+8 -2
Переглянути файл
@@ -507,7 +507,13 @@ function PaneContent({ paneId, tab, tabsVisible }: { paneId: string; tab: Tab; t
)}
<FindBar paneId={paneId} />
{crumbs && (
<PaneBreadcrumbs key={wrapper?.id} wrapper={wrapper} path={tab.input.path!} tabId={tab.id} position="top" />
<PaneBreadcrumbs
key={`top:${wrapper?.id}`}
wrapper={wrapper}
path={tab.input.path!}
tabId={tab.id}
position="top"
/>
)}
{wrapper ? (
<wrapper.component
@@ -523,7 +529,7 @@ function PaneContent({ paneId, tab, tabsVisible }: { paneId: string; tab: Tab; t
)}
{crumbs && (
<PaneBreadcrumbs
key={wrapper?.id}
key={`bottom:${wrapper?.id}`}
wrapper={wrapper}
path={tab.input.path!}
tabId={tab.id}
-1
Переглянути файл
@@ -201,7 +201,6 @@ export const lspTheme = EditorView.theme({
flex: "0 1 auto",
minWidth: "0",
marginLeft: "auto",
paddingLeft: "16px",
textAlign: "right",
color: "var(--fg-subtle)",
overflow: "hidden",
+2
Переглянути файл
@@ -36,7 +36,9 @@
outline: none;
}
.field :global(.cm-scroller) {
height: auto;
max-height: 280px;
overflow-x: hidden;
overflow-y: auto;
font-family: inherit;
line-height: 1.5;
+40
Переглянути файл
@@ -0,0 +1,40 @@
import { useState } from "react";
import type { AgentImage } from "@/bindings";
import { useTx } from "@/platform/i18n";
import { IconButton } from "@/ui";
import { ImagePreview, imageSrc } from "./ImagePreview";
import styles from "./Session.module.css";
/** Image thumbnails; a click opens the full image, `onRemove` adds a remove button to each. */
export function ImageStrip({ images, onRemove }: { images: AgentImage[]; onRemove?: (index: number) => void }) {
const tx = useTx();
const [open, setOpen] = useState<AgentImage | null>(null);
if (images.length === 0) return null;
return (
<div className={styles.images}>
{images.map((img, i) => (
<span key={i} className={styles.imageItem}>
<button
type="button"
className={styles.imageButton}
title={img.name ?? undefined}
onClick={() => setOpen(img)}
>
<img className={styles.image} src={imageSrc(img)} alt={img.name ?? tx("Image")} />
</button>
{onRemove && (
<IconButton
type="button"
className={styles.removeImage}
aria-label={tx("Remove Image")}
onClick={() => onRemove(i)}
icon="close"
size="small"
/>
)}
</span>
))}
<ImagePreview image={open} onClose={() => setOpen(null)} />
</div>
);
}
+10 -1
Переглянути файл
@@ -231,7 +231,7 @@
content-visibility: auto;
}
/* WebKit leaves a stale selection highlight on rows that skipped rendering (`useOffscreenRows`). */
.stream[data-selection] > .conversationRow[data-measured] {
.conversationRow[data-measured][data-selection] {
content-visibility: visible;
}
/* Keep turns distinct and the work within a turn close to its author. Not `* + *`: a
@@ -1197,6 +1197,15 @@
border: 1px solid var(--border);
border-radius: var(--radius-small);
}
.toolImages,
.toolImages .imageItem,
.toolImages .imageButton {
max-width: 100%;
}
.toolImages .image {
max-width: min(100%, 640px);
max-height: 320px;
}
.removeImage {
position: absolute;
top: 4px;
+58 -30
Переглянути файл
@@ -1,4 +1,4 @@
import type { AgentEntry, AgentTask } from "@/bindings";
import type { AgentEntry, AgentImage, AgentTask } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import {
@@ -27,6 +27,7 @@ import {
type RefObject,
} from "react";
import { useAgentSettings } from "../agentSettings";
import { ImageStrip } from "../ImageStrip";
import {
entriesKey,
isBusy,
@@ -147,7 +148,14 @@ function useOffscreenRows(
}, [ref, visible, enabled, fitWindowWidth, fontZoom]);
// Keep independent of `visible`: when a kept-alive tab hides, `data-selection` must stay until
// the selection leaves and WebKit clears off-screen rows' highlights before skipping again.
useSelectionVisibility(ref, enabled);
useSelectionVisibility(ref, enabled, `.${styles.conversationRow}`);
}
/** Images remain visible beside the work's folded summary, without duplicating them when it opens. */
function toolImages(row: ConversationRow): AgentImage[] {
if (row.kind === "turn") return row.rows.flatMap(toolImages);
const entries = row.kind === "process" ? row.entries.map(({ entry }) => entry) : [row.entry];
return entries.flatMap((entry) => (entry.type === "tool" ? (entry.images ?? []) : []));
}
interface StreamProps {
@@ -215,7 +223,7 @@ export function Stream({
const restored = useRef(false);
const previousLength = useRef(entries?.length ?? 0);
/** Scrolled away from the end: offer one click back to the latest message. */
const [away, setAway] = useState(() => positions.get(key)?.stick === false);
const [away, setAway] = useState(false);
// Opened at the end, the last entries come first and the earlier ones follow in batches:
// reopening a long conversation paints at once. A kept offset needs them all.
const [shown, setShown] = useState(() => (positions.get(key)?.stick === false ? Infinity : ENTRY_BATCH));
@@ -244,10 +252,17 @@ export function Stream({
if (!position.current.stick) return;
position.current = { top: el.scrollTop, stick: false };
positions.set(key, position.current);
setAway(true);
},
[key, positions],
);
const updateJumpVisibility = useCallback((el: HTMLElement) => {
// An upward gesture releases following before anything moves. Only offer a jump
// when there is actual content below the viewport, excluding the fold spacer.
setAway(
!position.current.stick &&
el.scrollHeight - el.clientHeight - el.scrollTop > (parseFloat(getComputedStyle(el).paddingBottom) || 0) + 1,
);
}, []);
// Earlier entries are prepended above the view: remember where the first painted row is
// so the content stays put and the scrollbar doesn't jump under the pointer.
const anchor = useRef<{ el: Element; top: number } | null>(null);
@@ -322,8 +337,10 @@ export function Stream({
/** A diagram that drew after the last streamed chunk grows the conversation: keep following. */
const onDiagramDrawn = useCallback(() => {
const el = ref.current;
if (el && position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
}, []);
if (!el) return;
if (position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
updateJumpVisibility(el);
}, [updateJumpVisibility]);
useLayoutEffect(() => {
const el = ref.current;
if (!el || entries === null || !visible) return;
@@ -353,6 +370,7 @@ export function Stream({
if (!dragging.current) el.scrollTop = el.scrollHeight;
} else if (!restored.current) el.scrollTop = position.current.top;
restored.current = true;
updateJumpVisibility(el);
});
useLayoutEffect(() => {
// Prepending earlier entries moved the first painted row down: follow it, so the same
@@ -363,6 +381,7 @@ export function Stream({
anchor.current = null;
if (position.current.stick || !from.el.isConnected) return;
scroller.scrollTop += from.el.getBoundingClientRect().top - from.top;
updateJumpVisibility(scroller);
});
useLayoutEffect(() => {
const el = ref.current;
@@ -370,13 +389,14 @@ export function Stream({
const observer = new ResizeObserver(() => {
trimSlack();
if (position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
updateJumpVisibility(el);
});
observer.observe(el);
return () => {
observer.disconnect();
if (restored.current) positions.set(key, { ...position.current, top: el.scrollTop });
};
}, [key, positions, trimSlack]);
}, [key, positions, trimSlack, updateJumpVisibility]);
/**
* The wheel scrolls the innermost container under the pointer, and only that one: a run of
* calls from its headers, a tool output from its text, the conversation elsewhere. A container
@@ -431,10 +451,10 @@ export function Stream({
if (position.current.stick && el.scrollHeight - el.scrollTop - el.clientHeight >= 1) {
position.current = { top: el.scrollTop, stick: false };
positions.set(key, position.current);
setAway(true);
}
updateJumpVisibility(el);
},
[key, positions, setSlack, trimSlack],
[key, positions, setSlack, trimSlack, updateJumpVisibility],
);
/** Back to the end of the stream; following resumes from there. */
const jumpToLatest = useCallback(() => {
@@ -569,7 +589,7 @@ export function Stream({
if (stick && !atEnd && !dragging.current) el.scrollTop = el.scrollHeight;
position.current = { top: el.scrollTop, stick };
positions.set(key, position.current);
setAway(!position.current.stick);
updateJumpVisibility(el);
// Reached the top of what is painted: fetch the earlier entries, but only
// once the drag has settled.
if (loadTimer.current !== null) window.clearTimeout(loadTimer.current);
@@ -616,27 +636,35 @@ export function Stream({
) : entries.length === 0 && !busy && !loadError ? (
<EmptyState title="No conversation history" />
) : (
rows.map((row) => (
<div
key={row.index}
className={styles.conversationRow}
data-message={
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
}
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
data-author={authorHeaders.has(row.index) || undefined}
>
{authorHeaders.has(row.index) && (
<div className={styles.agentAuthor}>
<div className={styles.role}>
<Icon name={providerIcon(task.provider)} size={13} />
<span>{providerName(task.provider)}</span>
rows.map((row) => {
const images = toolImages(row);
return (
<div
key={row.index}
className={styles.conversationRow}
data-message={
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
}
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
data-author={authorHeaders.has(row.index) || undefined}
>
{authorHeaders.has(row.index) && (
<div className={styles.agentAuthor}>
<div className={styles.role}>
<Icon name={providerIcon(task.provider)} size={13} />
<span>{providerName(task.provider)}</span>
</div>
</div>
</div>
)}
{renderConversationRow(row)}
</div>
))
)}
{renderConversationRow(row)}
{images.length > 0 && (
<div className={styles.toolImages}>
<ImageStrip images={images} />
</div>
)}
</div>
);
})
)}
<WorkingRow task={task} entries={entries} subagent={subagent} />
</div>
+1 -35
Переглянути файл
@@ -7,7 +7,7 @@ import { notifications } from "@/workbench/contributions";
import clsx from "clsx";
import { memo, useLayoutEffect, useRef, useState, type RefObject } from "react";
import { AgentReply, MessageActions, ReplyActions } from "../AgentReply";
import { ImagePreview, imageSrc } from "../ImagePreview";
import { ImageStrip } from "../ImageStrip";
import { ReferencedText } from "../ReferenceChip";
import styles from "../Session.module.css";
import { SubmitButton } from "../SubmitButton";
@@ -425,37 +425,3 @@ function MessageEditor({
</div>
);
}
/** Image thumbnails; a click opens the full image, `onRemove` adds a remove button to each. */
function ImageStrip({ images, onRemove }: { images: AgentImage[]; onRemove?: (index: number) => void }) {
const tx = useTx();
const [open, setOpen] = useState<AgentImage | null>(null);
if (images.length === 0) return null;
return (
<div className={styles.images}>
{images.map((img, i) => (
<span key={i} className={styles.imageItem}>
<button
type="button"
className={styles.imageButton}
title={img.name ?? undefined}
onClick={() => setOpen(img)}
>
<img className={styles.image} src={imageSrc(img)} alt={img.name ?? tx("Image")} />
</button>
{onRemove && (
<IconButton
type="button"
className={styles.removeImage}
aria-label={tx("Remove Image")}
onClick={() => onRemove(i)}
icon="close"
size="small"
/>
)}
</span>
))}
<ImagePreview image={open} onClose={() => setOpen(null)} />
</div>
);
}
+56
Переглянути файл
@@ -459,6 +459,37 @@ describe("process folding", () => {
});
});
describe("tool result images", () => {
it.each([
["grouped", true],
["grouped", false],
["each", true],
["each", false],
] as const)("keeps tool images visible with %s tools and folded turns=%s", async (toolCalls, foldTurns) => {
useProject.setState({ settings: { agents: { toolCalls, foldTurns } } as never });
const image = { mimeType: "image/png", data: "aW1hZ2U=", name: null };
backend.entries.set("A", [
{ type: "user", text: "Render a preview", attachments: [], steered: false, sentMs: 1000, doneMs: 2000 },
{ type: "thought", text: "Rendering" },
tool("preview", { images: [image] }),
tool("inspect", { output: "Preview ready" }),
{ type: "agent", text: "Here is the result." },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Here is the result.");
const preview = screen.getByRole("img", { name: "Image" });
expect(preview).toHaveAttribute("src", "data:image/png;base64,aW1hZ2U=");
expect(preview.closest("details")).toBeNull();
fireEvent.click(preview.closest("button")!);
const dialog = await screen.findByRole("dialog", { name: "Image" });
expect(within(dialog).getByRole("img")).toHaveAttribute("src", "data:image/png;base64,aW1hZ2U=");
fireEvent.click(within(dialog).getByText("Close", { selector: "button" }));
expect(screen.queryByRole("dialog")).toBeNull();
expect(screen.getAllByRole("img", { name: "Image" })).toHaveLength(1);
});
});
describe("turn folding", () => {
it("folds a finished turn's work under its message and keeps the reply", async () => {
backend.entries.set("A", [
@@ -738,6 +769,31 @@ describe("the conversation selection", () => {
});
describe("scrolling", () => {
it("hides Jump to Latest while the end is visible even when following has stopped", async () => {
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const el = stream();
let height = 1000;
Object.defineProperty(el, "scrollHeight", { configurable: true, get: () => height });
Object.defineProperty(el, "clientHeight", { configurable: true, value: 400 });
el.style.paddingBottom = "12px";
el.scrollTop = 599.75;
fireEvent.scroll(el);
fireEvent.wheel(el, { deltaY: -2 });
const jump = () => screen.queryByRole("button", { name: "Jump to Latest" });
expect(jump()).toBeNull();
el.scrollTop = 594;
fireEvent.scroll(el);
expect(jump()).toBeNull();
el.scrollTop = 580;
fireEvent.scroll(el);
expect(jump()).toBeInTheDocument();
// The end moves into view when content shrinks, without a downward gesture.
height = 980;
fireEvent.scroll(el);
expect(jump()).toBeNull();
});
it("returns to the end when the user sends a message while scrolled up", async () => {
const reply = { type: "agent", text: "Initial reply" } as AgentEntry;
useAgents.setState({ entries: new Map([["A", [reply]]]) });
+1 -1
Переглянути файл
@@ -78,7 +78,7 @@
}
.row {
display: grid;
grid-template-columns: min(34%, 176px) 5ch minmax(0, 1fr);
grid-template-columns: min(38%, 176px) 5ch minmax(0, 1fr);
align-items: center;
gap: var(--space-2);
min-width: 0;
+26
Переглянути файл
@@ -365,3 +365,29 @@ it("prefers the same configuration over another selected tab with the same name"
expect(tabIds()).toEqual([1, 3]);
expect(useDebug.getState().sessions[3]?.runConfig?.id).toBe("b");
});
it("keeps a rerun tab in place and selected while its adapter starts", async () => {
ipc.debugStart.mockResolvedValueOnce({ status: "ok", data: 1 }).mockResolvedValueOnce({ status: "ok", data: 2 });
await startSession({ ...config("launch"), name: "main.c" });
await startSession({ ...config("launch"), name: "layout.c" });
useDebug.setState({ active: 1 });
let respond!: (r: { status: "ok"; data: number }) => void;
ipc.debugStart.mockImplementationOnce(() => new Promise((resolve) => (respond = resolve)) as never);
const rerun = rerunSession(1);
await vi.advanceTimersByTimeAsync(0);
handleDebugEvent(1, { kind: "terminated" });
// Stopped, the old tab still holds its place and the selection.
expect(tabIds()).toEqual([1, 2]);
expect(useDebug.getState().active).toBe(1);
// The adapter announces the new session before `debugStart` returns: it takes the tab at once.
handleDebugEvent(3, { kind: "started", name: "main.c", adapter: "lldb", parent: null } as never);
expect(tabIds()).toEqual([3, 2]);
expect(useDebug.getState().active).toBe(3);
respond({ status: "ok", data: 3 });
await rerun;
expect(tabIds()).toEqual([3, 2]);
expect(useDebug.getState().active).toBe(3);
});
+48 -9
Переглянути файл
@@ -348,7 +348,19 @@ function ownSession(id: DebugSessionId, event: DebugEvent): DebugSession | null
}
if (pendingStarts === 0) return null;
provisional.add(id);
return event.kind === "started" ? adoptSession(id, { name: event.name, adapter: event.adapter }) : adoptSession(id);
// The new root session takes the tab it replaces now, not once `debugStart` returns.
const replaced = pendingReplacements[0];
const slot = replaced ? { tabOrder: replaced.tabOrder, pinned: replaced.pinned } : {};
const s =
event.kind === "started"
? adoptSession(id, { name: event.name, adapter: event.adapter, ...slot })
: adoptSession(id, slot);
if (replaced) {
takeReplacement(replaced);
useDebug.setState({ active: id });
publishContext();
}
return s;
}
/**
@@ -380,10 +392,26 @@ function settleStart(id: DebugSessionId | null, discard = false) {
/** The session being rerun: its tab is the one the new session takes, pinned or not. */
let rerunOf: DebugSessionId | null = null;
/** Sessions whose Rerun is in progress: their tab stays selected when they terminate. */
const rerunning = new Set<DebugSessionId>();
interface ReplacedTab {
pinned?: boolean;
tabOrder?: number;
/** The finished tab, kept until the new session takes its place (`defer`). */
session?: DebugSessionId;
}
/** Finished tabs whose starting replacements have no session yet, oldest start first. */
const pendingReplacements: ReplacedTab[] = [];
/** The new session is shown: the finished tab it replaces gives way. */
function takeReplacement(r: ReplacedTab | undefined) {
if (!r) return;
const i = pendingReplacements.indexOf(r);
if (i >= 0) pendingReplacements.splice(i, 1);
if (r.session != null && useDebug.getState().sessions[r.session]) removeSession(r.session);
r.session = undefined;
}
/**
@@ -392,17 +420,20 @@ interface ReplacedTab {
* then the selected one; other finished tabs stay. The returned slot lets the new backend
* session keep the tab where the replaced one was.
*/
function replaceFinished(name: string, configId?: string): ReplacedTab {
function replaceFinished(name: string, configId?: string, defer = false): ReplacedTab {
const { sessions, active } = useDebug.getState();
const own = rerunOf != null ? sessions[rerunOf] : undefined;
rerunOf = null;
// Rerun's Stop waits for the adapter, even if this window has not handled its terminated event yet.
if (own) {
const tabOrder = tabOrderOf(own);
if (defer) return { pinned: own.pinned, tabOrder, session: own.id };
removeSession(own.id);
return { pinned: own.pinned, tabOrder };
}
const finished = sessionsInTabOrder(sessions).filter((s) => s.parent == null && !isLive(s) && !s.pinned);
const finished = sessionsInTabOrder(sessions).filter(
(s) => s.parent == null && !isLive(s) && !s.pinned && !pendingReplacements.some((r) => r.session === s.id),
);
const selected = active != null ? sessions[active] : undefined;
const ordered =
selected && finished.includes(selected) ? [selected, ...finished.filter((s) => s !== selected)] : finished;
@@ -413,6 +444,7 @@ function replaceFinished(name: string, configId?: string): ReplacedTab {
const pinned = workflowSettings().run.pinTabs || undefined;
if (!reused) return { pinned };
const tabOrder = tabOrderOf(reused);
if (defer) return { pinned, tabOrder, session: reused.id };
removeSession(reused.id);
return { pinned, tabOrder };
}
@@ -856,7 +888,10 @@ 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;
let replaced = !afterDetach && !options.preparation ? replaceFinished(launch.name, options.runConfig?.id) : undefined;
// The finished tab stays in place until the new session appears there.
let replaced =
!afterDetach && !options.preparation ? replaceFinished(launch.name, options.runConfig?.id, true) : undefined;
if (replaced?.session != null) pendingReplacements.push(replaced);
try {
if (options.show !== false && workflowSettings().run.showOnStart) toolWindowService().show("debug");
} catch {
@@ -879,6 +914,7 @@ export async function startSession(
return null;
}
flushConsoleOutput();
takeReplacement(replaced);
const preparation = options.preparation && useDebug.getState().sessions[options.preparation.id];
useDebug.setState((s) => {
const cur = s.sessions[id] ?? blank(id, { status: "running" });
@@ -922,6 +958,7 @@ export async function startSession(
void syncSpecial();
return id;
} catch (e) {
takeReplacement(replaced);
settleStart(null, afterDetach);
if (afterDetach) {
// The JVM that announced the port ended as its previous debugger detached.
@@ -1077,16 +1114,18 @@ export async function rerunSession(id: DebugSessionId, options: { show?: boolean
const root = rootOf(s);
const launch = root.launch;
if (!root.runConfig && !launch) return;
if (isLive(root)) await stopSession(root.id);
rerunOf = root.id;
// A session debugged in place from Services reruns there too.
const show = options.show ?? (root.inPlace ? false : undefined);
rerunning.add(root.id);
try {
if (isLive(root)) await stopSession(root.id);
rerunOf = root.id;
// A session debugged in place from Services reruns there too.
const show = options.show ?? (root.inPlace ? false : undefined);
if (root.runConfig)
await executeAction("run.debugConfig", show === false ? { config: root.runConfig, show: false } : root.runConfig);
else await startSession(launch!, { show });
} finally {
rerunOf = null;
rerunning.delete(root.id);
}
}
@@ -1135,7 +1174,7 @@ function markTerminated(id: DebugSessionId) {
if (serverPages.delete(id) && page != null) void stopSession(page);
patch(id, { status: "terminated", endedAt: Date.now(), frames: [], selectedFrame: null, stoppedThread: null });
const st = useDebug.getState();
if (st.active === id) {
if (st.active === id && !rerunning.has(id)) {
// Prefer another live session (e.g. the parent of a finished child).
const other = sessionsInTabOrder(st.sessions).find(isLive);
if (other) useDebug.setState({ active: other.id });
+36
Переглянути файл
@@ -222,6 +222,42 @@ describe("ProjectView", () => {
}
});
it("pastes a copied keyword into the tree's speed search instead of pasting files", async () => {
dispatchViaKeymap();
// Explorer holds a file, and the user wants to paste a word they copied from somewhere else
// into the search they just opened with ⌘F.
fs.nodes.set("/elsewhere/Photo.png", { kind: "file", size: 3 });
setOsClipboardForTests({
files: async () => ["/elsewhere/Photo.png"],
hasFiles: async () => true,
setFiles: async () => false,
});
try {
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("src"));
tree.focus();
fireEvent.keyDown(tree, { key: "f", code: "KeyF", metaKey: true });
fireEvent.paste(tree, {
clipboardData: { getData: () => "Read" },
} as unknown as ClipboardEventInit);
expect(within(tree.parentElement!).getByRole("status")).toHaveTextContent("Read");
// The file Paste never ran: give a wrong one the time to land, then check the project.
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 50));
});
expect([...fs.nodes.keys()].filter((p) => p.startsWith("/w/acme/") && p.endsWith("Photo.png"))).toEqual([]);
// Closed, ⌘V is the view's file Paste again.
fireEvent.keyDown(tree, { key: "Escape", code: "Escape" });
fireEvent.keyDown(tree, { key: "v", code: "KeyV", metaKey: true });
await waitFor(() =>
expect([...fs.nodes.keys()].some((p) => p.startsWith("/w/acme/") && p.endsWith("Photo.png"))).toBe(true),
);
} finally {
setOsClipboardForTests(null);
}
});
it("clears cut dimming and disables Paste on focus after the OS clipboard becomes text", async () => {
dispatchViaKeymap();
let files: string[] = [];
+8
Переглянути файл
@@ -487,9 +487,17 @@
padding: 6px 8px;
border-bottom: 1px solid var(--border-popup);
}
/* The list fills what is left of the viewport once the popup is capped by the window, not its full height. */
.chooserViewport {
display: flex;
flex-direction: column;
min-height: 0;
}
.chooserViewport > .chooserList {
flex: 1 1 auto;
min-height: 0;
height: auto;
}
.chooserList {
height: 100%;
overflow-x: hidden;
+84
Переглянути файл
@@ -0,0 +1,84 @@
import { EditorSelection, EditorState } from "@codemirror/state";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { setContext } from "@/platform/context";
import { useProject } from "@/platform/project";
import { DEFAULT_EXTERNAL_TOOL } from "@/platform/workflowSettings";
import { clearProjectViewLead, setProjectViewLead } from "@/workbench/contributions";
import { externalToolConfig } from "./externalTools";
const editor = vi.hoisted(() => ({ current: null as unknown }));
vi.mock("@/editor/api", () => ({ activeEditor: () => editor.current }));
// Editor on A.java, caret on line 2 with "two" selected.
function openA() {
const doc = "one\ntwo\n";
const state = EditorState.create({ doc, selection: EditorSelection.single(4, 7) });
editor.current = { ctx: { path: "/p/src/A.java" }, view: { state } };
}
const tool = {
...DEFAULT_EXTERNAL_TOOL,
id: "t",
name: "Echo",
program: "echo",
arguments:
"$FilePath$ $FileDir$ $FileName$ $FileNameWithoutExtension$ $FileExt$ $FileRelativePath$ " +
"$FileDirRelativeToProjectRoot$ L$LineNumber$ C$ColumnNumber$ S$SelectedText$",
};
const argsFor = async () => (await externalToolConfig(tool))?.args;
describe("external tool macros", () => {
beforeEach(() => {
useProject.setState({ project: { root: "/p", name: "demo" } as never });
setContext("editorFocus", false);
openA();
});
afterEach(() => {
clearProjectViewLead();
editor.current = null;
useProject.setState({ project: null });
});
it("uses the file selected in the Project view over the open editor (#5402)", async () => {
setProjectViewLead({ path: "/p/lib/B.kt", dir: false });
expect(await argsFor()).toEqual(["/p/lib/B.kt", "/p/lib", "B.kt", "B", "kt", "lib/B.kt", "lib", "L", "C", "S"]);
});
it("uses the editor's file and caret when the editor is the context", async () => {
expect(await argsFor()).toEqual([
"/p/src/A.java",
"/p/src",
"A.java",
"A",
"java",
"src/A.java",
"src",
"L2",
"C4",
"Stwo",
]);
});
it("keeps the caret macros when the Project view selects the editor's file", async () => {
setProjectViewLead({ path: "/p/src/A.java", dir: false });
expect((await argsFor())?.slice(-3)).toEqual(["L2", "C4", "Stwo"]);
});
it("falls back to the editor for a selected directory", async () => {
setProjectViewLead({ path: "/p/lib", dir: true });
expect((await argsFor())?.[0]).toBe("/p/src/A.java");
});
it("lets the focused editor win over a stale tree selection", async () => {
setProjectViewLead({ path: "/p/lib/B.kt", dir: false });
setContext("editorFocus", true);
expect((await argsFor())?.[0]).toBe("/p/src/A.java");
});
it("uses the tree selection with no editor open", async () => {
editor.current = null;
setProjectViewLead({ path: "/p/lib/B.kt", dir: false });
expect((await argsFor())?.[0]).toBe("/p/lib/B.kt");
});
});
+17 -3
Переглянути файл
@@ -9,7 +9,8 @@ import { splitCommandLine } from "@/platform/commandLine";
import type { RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { onWorkflowSettingsChange, workflowSettings, type ExternalToolValid } from "@/platform/workflowSettings";
import { notifications } from "@/workbench/contributions";
import { isVirtualUri } from "@/platform/virtualDocs";
import { notifications, projectViewContextLead } from "@/workbench/contributions";
import { promptValue } from "./dialogs";
import { startRun, useRun } from "./store";
@@ -73,14 +74,27 @@ export function expandMacros(text: string, ctx: MacroContext, prompt = ""): stri
return text.replace(MACRO_RE, (all, name: string) => (name === "Prompt" ? prompt : (macroValue(name, ctx) ?? all)));
}
/**
* The file macros resolve against, as IDEA's data context: the Project view's file while the
* tree is the user's context (it hands the context back on editor focus or a tab switch), else
* the editor's file.
*/
function contextFile(editorPath: string | null): string | null {
const lead = projectViewContextLead();
if (lead && !lead.dir && !isVirtualUri(lead.path)) return lead.path;
return editorPath;
}
function currentContext(): MacroContext | null {
const project = useProject.getState().project;
if (!project) return null;
const ed = activeEditor();
const filePath = contextFile(ed?.ctx.path ?? null);
let line: number | null = null;
let column: number | null = null;
let selectedText = "";
if (ed) {
// The caret macros describe the editor, so only when it shows the file the macros use.
if (ed && ed.ctx.path === filePath) {
const state = ed.view.state;
const sel = state.selection.main;
const l = state.doc.lineAt(sel.head);
@@ -91,7 +105,7 @@ function currentContext(): MacroContext | null {
return {
projectRoot: project.root,
projectName: project.name,
filePath: ed?.ctx.path ?? null,
filePath,
line,
column,
selectedText,
+20 -4
Переглянути файл
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const extensions = [
const projectExtensions = [
{ extension: "rs", files: 40 },
{ extension: "md", files: 12 },
{ extension: "lock", files: 9 },
@@ -10,6 +10,7 @@ const extensions = [
{ extension: "yml", files: 2 },
{ extension: "sh", files: 1 },
];
let extensions = projectExtensions;
const languages = [
{ id: "rust", extensions: ["rs"] },
{ id: "markdown", extensions: ["md", "markdown"] },
@@ -17,6 +18,7 @@ const languages = [
{ id: "json", extensions: ["json"] },
{ id: "yaml", extensions: ["yml", "yaml"] },
{ id: "shell", extensions: ["sh"] },
{ id: "properties", extensions: ["properties", "prefs"] },
];
vi.mock("@/platform/ipc", async (orig) => ({
@@ -31,16 +33,30 @@ vi.mock("@/platform/ipc", async (orig) => ({
const { recentMasks, refreshProjectMasks, rememberMask, useProjectMasks } = await import("../find/store");
beforeEach(() => {
extensions = projectExtensions;
localStorage.clear();
useProjectMasks.setState({ masks: [] });
});
describe("file mask suggestions", () => {
it("are the project's most common language file types, recent masks first", async () => {
it("are every language file type in the project, most common first, recent masks first", async () => {
await refreshProjectMasks();
expect(useProjectMasks.getState().masks).toEqual(["*.rs", "*.md", "*.toml", "*.json", "*.yml"]);
expect(useProjectMasks.getState().masks).toEqual(["*.rs", "*.md", "*.toml", "*.json", "*.yml", "*.sh"]);
rememberMask("*.toml");
rememberMask("!*Test*");
expect(recentMasks()).toEqual(["!*Test*", "*.toml", "*.rs", "*.md", "*.json", "*.yml"]);
expect(recentMasks()).toEqual(["!*Test*", "*.toml", "*.rs", "*.md", "*.json", "*.yml", "*.sh"]);
});
it("keep the least common of six file types (#5398)", async () => {
extensions = [
{ extension: "rs", files: 120 },
{ extension: "md", files: 30 },
{ extension: "json", files: 12 },
{ extension: "toml", files: 8 },
{ extension: "yml", files: 4 },
{ extension: "properties", files: 1 },
];
await refreshProjectMasks();
expect(recentMasks()).toEqual(["*.rs", "*.md", "*.json", "*.toml", "*.yml", "*.properties"]);
});
});
+3 -7
Переглянути файл
@@ -164,11 +164,10 @@ export function hideFindPopup() {
}
const MASKS_KEY = "openidea.search.fileMasks.v1";
const PROJECT_MASKS = 5;
/**
* `*.ext` masks of the project's most common language file types. IDEA seeds its
* mask list with the IDE's languages; a multi-language IDE takes the project's.
* `*.ext` masks of every language file type in the project, most common first. IDEA
* seeds its mask list with the IDE's languages; a multi-language IDE takes the project's.
*/
export const useProjectMasks = create<{ masks: string[] }>(() => ({ masks: [] }));
@@ -176,10 +175,7 @@ export async function refreshProjectMasks() {
try {
const [counts, languages] = await Promise.all([call(commands.indexFileExtensions()), commands.languages()]);
const known = new Set(languages.flatMap((l) => l.extensions.map((e) => e.toLowerCase())));
const masks = counts
.filter((c) => known.has(c.extension))
.slice(0, PROJECT_MASKS)
.map((c) => `*.${c.extension}`);
const masks = counts.filter((c) => known.has(c.extension)).map((c) => `*.${c.extension}`);
useProjectMasks.setState({ masks });
} catch {
/* no project index (welcome screen, tests) */
+8
Переглянути файл
@@ -153,6 +153,14 @@ export const BUILTIN_FILE_TEMPLATES: readonly FileTemplate[] = [
},
],
},
{
id: "svelte",
name: "Svelte Component",
icon: "file-svelte",
extension: "svelte",
nameStyle: "asis",
kinds: [{ id: "component", label: "Svelte Component", body: "<script>\n $END$\n</script>\n" }],
},
{
id: "javascript",
name: "JavaScript File",
+3 -2
Переглянути файл
@@ -93,9 +93,10 @@ function newFileAction(t: FileTemplate): Action {
};
}
// Generic templates and user or plugin templates have no project type restriction; nor do the web
// ones (JavaScript, TypeScript), which IntelliJ IDEA Ultimate offers in every project.
// Generic templates (including JavaScript and TypeScript) and user or plugin templates
// have no project type restriction.
const templateProjectTypes: Partial<Record<string, readonly ProjectType[]>> = {
svelte: ["vite", "node"],
rust: ["cargo"],
python: ["python"],
jupyter: ["python"],
+291
Переглянути файл
@@ -0,0 +1,291 @@
// @vitest-environment jsdom
import { describe, expect, it } from "vitest";
import type { Terminal } from "@xterm/xterm";
import { installImeAnchor } from "./imeAnchor";
/** jsdom has no layout: the pieces the anchor reads report their own boxes. */
function rect(left: number, top: number, width = 8, height = 18): DOMRect {
return {
left,
top,
width,
height,
right: left + width,
bottom: top + height,
x: left,
y: top,
toJSON: () => ({}),
} as DOMRect;
}
interface Fake {
host: HTMLElement;
textarea: HTMLTextAreaElement;
term: Terminal;
/** Runs every listener xterm's render and cursor-move events would fire. */
tick(): void;
/** Moves the terminal cursor, as the program's next frame would. */
cursor(x: number, y: number): void;
}
function fake({
cursorX = 0,
cursorY = 0,
cols = 80,
rows = 20,
showCursor = false,
viewportY = 0,
baseY = 0,
} = {}): Fake {
const host = document.createElement("div");
const screen = document.createElement("div");
screen.className = "xterm-screen";
// 80 columns × 20 rows of 8 × 18 px cells.
screen.getBoundingClientRect = () => rect(40, 40, 640, 360);
const rowList = document.createElement("div");
rowList.className = "xterm-rows";
screen.append(rowList);
const textarea = document.createElement("textarea");
textarea.className = "xterm-helper-textarea";
textarea.style.width = "8px";
textarea.style.height = "18px";
host.append(screen, textarea);
const listeners: (() => void)[] = [];
const active = { cursorX, cursorY, viewportY, baseY };
const term = {
textarea,
cols,
rows,
buffer: { active },
modes: { showCursor },
onRender: (fn: () => void) => {
listeners.push(fn);
return { dispose: () => listeners.splice(listeners.indexOf(fn), 1) };
},
onCursorMove: (fn: () => void) => {
listeners.push(fn);
return { dispose: () => listeners.splice(listeners.indexOf(fn), 1) };
},
} as unknown as Terminal;
return {
host,
textarea,
term,
tick: () => listeners.forEach((fn) => fn()),
cursor: (x: number, y: number) => {
active.cursorX = x;
active.cursorY = y;
},
};
}
/** A reverse-video cell at `left`/`top`, on `row` of the rendered grid. */
function addCaret(f: Fake, left: number, top: number, row = 0) {
const rowList = f.host.querySelector(".xterm-rows")!;
while (rowList.children.length <= row) rowList.append(document.createElement("div"));
const span = document.createElement("span");
span.className = "xterm-bg-257";
span.textContent = " ";
span.getBoundingClientRect = () => rect(left, top);
rowList.children[row]!.append(span);
}
/** Lets the `style` observer run, which is a microtask. */
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
describe("installImeAnchor", () => {
it("puts the IME anchor on the caret a program drew for itself", () => {
const f = fake({ cursorX: 79, cursorY: 3 });
// The caret cell sits 60px right of and 50px below the screen's origin.
addCaret(f, 100, 90, 3);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("60px");
expect(f.textarea.style.top).toBe("50px");
});
it("keeps the anchor inside the terminal, where the input method reads the caret", () => {
const f = fake({ cursorX: 79 });
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
// A position outside the screen's box makes Windows put the candidate window in a corner.
const left = Number.parseFloat(f.textarea.style.left);
const top = Number.parseFloat(f.textarea.style.top);
expect(left).toBeGreaterThanOrEqual(0);
expect(top).toBeGreaterThanOrEqual(0);
expect(left).toBeLessThan(640);
expect(top).toBeLessThan(360);
});
it("leaves xterm's own anchor alone while the cursor is inside the screen", () => {
const f = fake({ cursorX: 12 });
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("");
expect(f.textarea.style.top).toBe("");
});
it.each([
["the terminal cursor is visible", { showCursor: true }],
["the terminal is showing scrollback", { baseY: 30, viewportY: 15 }],
] as const)("ignores reverse video when %s", (_scenario, options) => {
const f = fake({ cursorX: 79, ...options });
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("");
expect(f.textarea.style.top).toBe("");
});
it("ignores xterm's own cursor cell and takes the program's caret", () => {
const f = fake({ cursorX: 79 });
// The terminal cursor's own cell: column 79 (screen origin 40,40; 8x18 cells).
addCaret(f, 40 + 79 * 8, 40);
// The caret the program drew.
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("60px");
});
it("still anchors when xterm clamps the cursor a cell or two short of the edge", () => {
// Measured in pi: the clamped cursor ends up at cols-2 (and one past the row), never always
// at the last cell.
for (const cursorX of [78, 79, 80]) {
const f = fake({ cursorX });
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("60px");
}
});
it("prefers the caret on the terminal cursor's row", () => {
const f = fake({ cursorX: 79, cursorY: 5 });
addCaret(f, 300, 40, 0); // some other reverse-video cell, e.g. a highlighted row
addCaret(f, 100, 150, 5);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("60px");
expect(f.textarea.style.top).toBe("110px");
});
it("takes a single caret from another row when the program's cursor drifted", () => {
// pi scrolls its input box but keeps asking for the last column of the row its hardware cursor
// landed on, three rows below the caret: the only reverse-video cell is still the caret.
const f = fake({ cursorX: 79, cursorY: 27 });
addCaret(f, 100, 90, 24);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("60px");
expect(f.textarea.style.top).toBe("50px");
});
it("gives up when the cells elsewhere are not the cursor and there is more than one", () => {
const f = fake({ cursorX: 79, cursorY: 5 });
addCaret(f, 100, 40, 0);
addCaret(f, 300, 40, 1);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("");
});
it("leaves xterm's own anchor alone when two cells are not the cursor", () => {
const f = fake({ cursorX: 79 });
addCaret(f, 100, 90);
addCaret(f, 300, 90); // a selection or a highlighted row, not a caret
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("");
});
it("puts the anchor back when xterm re-places it on the cursor", async () => {
const f = fake({ cursorX: 79 });
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
// What xterm's composition helper writes on `compositionstart` and every update.
f.textarea.style.left = "616.8px";
f.textarea.style.top = "0px";
await settle();
expect(f.textarea.style.left).toBe("60px");
expect(f.textarea.style.top).toBe("50px");
});
it("keeps the caret offset through a frame that misses it", async () => {
const f = fake({ cursorX: 79 });
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("60px");
// The program redraws without its caret for a moment: the composition opening now must not
// fall back to the far end of the row.
f.host.querySelector(".xterm-rows")!.replaceChildren();
f.tick();
await settle();
expect(f.textarea.style.left).toBe("60px");
expect(f.textarea.style.top).toBe("50px");
});
it("hands the position back to xterm when the cursor leaves the last column", async () => {
const f = fake({ cursorX: 79 });
addCaret(f, 100, 90);
installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(f.textarea.style.left).toBe("60px");
// A program that puts its hardware cursor on the caret needs no anchor at all.
f.cursor(12, 0);
f.tick();
await settle();
expect(f.textarea.style.left).toBe("96px");
expect(f.textarea.style.top).toBe("0px");
});
it("moves the composition view too, and stops once disposed", async () => {
const f = fake({ cursorX: 79 });
addCaret(f, 100, 90);
const view = document.createElement("div");
view.className = "composition-view";
f.host.querySelector(".xterm-screen")!.append(view);
const dispose = installImeAnchor({ host: f.host, term: f.term });
f.tick();
expect(view.style.left).toBe("60px");
expect(view.hasAttribute("data-openidea-ime-anchor")).toBe(true);
dispose();
expect(view.style.left).toBe("632px");
expect(view.hasAttribute("data-openidea-ime-anchor")).toBe(false);
// xterm owns the position again: nothing moves it away any more.
f.textarea.style.left = "640px";
await settle();
expect(f.textarea.style.left).toBe("640px");
});
});
+195
Переглянути файл
@@ -0,0 +1,195 @@
/**
* Points the IME at the caret a full-screen program draws itself.
*
* xterm anchors the IME candidate window on its hidden helper textarea, which it keeps on the
* terminal cursor: on every render, on `compositionstart`, and again on each `compositionupdate`.
* A TUI that paints its own cursor hides the terminal's and leaves it wherever the frame's last
* write ended — pi asks for a column past the right edge of its input box (`ESC[21;411H` in a
* 206-column terminal, which xterm clamps to the last column) while it draws the caret itself at
* column 5. The candidate window then opens at the far right of the input box, and every
* composition started there keeps it there, because xterm re-places the textarea as the input
* method opens.
*
* Nothing in the protocol reports where such a caret is, but the program draws it: a caret painted
* with reverse video is an inverted cell, which xterm marks `xterm-bg-257`. While the hidden cursor
* sits at the right edge (`EDGE_COLUMNS`) in the live viewport and one such cell stands out, that
* cell is taken as the caret: one on the cursor's row wins, and a single one anywhere keeps working
* when the program's own row tracking drifts. Anything else is a selection or a highlighted row.
*
* The textarea is moved with `left`/`top`, i.e. inside the terminal's box: Chromium reports that
* rectangle to the input method, and a rectangle outside the window makes Windows open the
* candidate window in the window's corner. xterm rewrites those properties from the cursor on its
* own schedule, so the position is restored after every render, cursor move and composition event,
* and again from a `style` observer, which lands in the microtask right after xterm's write.
*/
import type { Terminal } from "@xterm/xterm";
/** xterm's class for a cell drawn in `INVERTED_DEFAULT_COLOR` (reverse video). */
const INVERTED = "xterm-bg-257";
/**
* How close to the right edge the terminal cursor has to be for the anchor to apply.
*
* Such a program asks for a column past the edge, and xterm clamps that to the last cell — but the
* cursor it ends up with is not always the last cell: a wrapped pending cell (`cursorX` one past
* the row) and requests clamped a cell or two short both showed up while typing in pi, and every
* one of them has to count as "the program cannot place its own cursor".
*/
const EDGE_COLUMNS = 3;
export interface ImeAnchorOptions {
/** The xterm host inside the pane, where `.xterm-screen` lives. */
host: HTMLElement;
term: Terminal;
}
/** One cell of the grid, in CSS pixels. */
interface Cell {
width: number;
height: number;
}
/** Where the helper textarea belongs, in the screen's own coordinates. */
interface Spot {
left: number;
top: number;
}
/**
* The cell a program drew its caret in.
*
* Every inverted cell is a candidate — xterm draws the terminal's own cursor cell inverted too —
* so the one sitting on the terminal cursor is dropped. The caret cell is normally on the cursor's
* row, which is where a hardware cursor request clamped by column leaves it, but that row can drift:
* pi ends up a few rows below its input box once the viewport scrolls. So a single candidate on the
* cursor's row wins, a single candidate anywhere on screen is taken as well, and anything else is a
* selection or a highlighted row, not a caret.
*/
function ownCaret(term: Terminal, host: HTMLElement, cell: Cell): Spot | undefined {
const screen = host.querySelector<HTMLElement>(".xterm-screen");
if (!screen || cell.width <= 0 || cell.height <= 0) return undefined;
const cursor = term.buffer.active;
const screenRect = screen.getBoundingClientRect();
const cursorCol = Math.min(cursor.cursorX, term.cols - 1);
const candidates: { rect: DOMRect; row: number }[] = [];
for (const [row, element] of [...host.querySelectorAll<HTMLElement>(".xterm-rows > div")].entries()) {
for (const span of element.children) {
if (!span.classList.contains(INVERTED)) continue;
const rect = span.getBoundingClientRect();
// The terminal's own cursor: xterm renders its cell inverted as well.
if (row === cursor.cursorY && Math.round((rect.left - screenRect.left) / cell.width) === cursorCol) continue;
if (rect.width > screenRect.width / 2) continue;
candidates.push({ rect, row });
}
}
const onCursorRow = candidates.filter((c) => c.row === cursor.cursorY);
const found = onCursorRow.length === 1 ? onCursorRow[0] : candidates.length === 1 ? candidates[0] : undefined;
if (!found) return undefined;
return { left: found.rect.left - screenRect.left, top: found.rect.top - screenRect.top };
}
/**
* Keeps the IME anchor on the caret such a program draws. Returns a disposer.
*
* Runs after every render rather than on `compositionstart` alone: an input method asks the
* focused element for its caret rectangle as it opens, and a reposition made from that event races
* xterm's own handling of the same event, which puts the textarea back on the terminal cursor.
*/
export function installImeAnchor({ host, term }: ImeAnchorOptions): () => void {
const textarea = term.textarea;
if (!textarea) return () => {};
const preedit = host.querySelector<HTMLElement>(".composition-view");
const elements = preedit ? [textarea, preedit] : [textarea];
/** The caret cell, or `null` while xterm's own placement is the right one. */
let target: Spot | null = null;
/** Whether the anchor currently holds a position of ours that xterm would undo. */
let moved = false;
/**
* The last caret seen, as an offset from the terminal cursor's cell. A frame can miss it — the
* program may be mid-redraw, or two cells of its caret may be on screen for a moment — and the
* composition that opens in such a frame must not fall back to the far end of the row.
*/
let caretFromCursor: Spot | null = null;
const write = (spot: Spot | undefined) => {
if (!spot) return;
const left = `${spot.left}px`;
const top = `${spot.top}px`;
for (const { style } of elements) {
if (style.left !== left) style.left = left;
if (style.top !== top) style.top = top;
}
};
/** What xterm itself writes: the cursor cell, clamped to the last column. */
const cursorSpot = (): Spot | undefined => {
const cols = term.cols;
const screen = host.querySelector<HTMLElement>(".xterm-screen");
if (!screen || cols <= 0) return undefined;
const screenRect = screen.getBoundingClientRect();
const cell = { width: screenRect.width / cols, height: term.rows > 0 ? screenRect.height / term.rows : 0 };
if (cell.width <= 0 || cell.height <= 0) return undefined;
const cursor = term.buffer.active;
return { left: Math.min(cursor.cursorX, cols - 1) * cell.width, top: cursor.cursorY * cell.height };
};
const place = () => {
const cols = term.cols;
const screen = host.querySelector<HTMLElement>(".xterm-screen");
const buffer = term.buffer.active;
target = null;
const cursor = cursorSpot();
if (
screen &&
cursor &&
!term.modes.showCursor &&
buffer.viewportY === buffer.baseY &&
buffer.cursorX >= cols - EDGE_COLUMNS
) {
const screenRect = screen.getBoundingClientRect();
const cell = { width: screenRect.width / cols, height: term.rows > 0 ? screenRect.height / term.rows : 0 };
const anchor = ownCaret(term, host, cell);
if (anchor) caretFromCursor = { left: anchor.left - cursor.left, top: anchor.top - cursor.top };
target =
anchor ??
(caretFromCursor && { left: cursor.left + caretFromCursor.left, top: cursor.top + caretFromCursor.top });
} else {
caretFromCursor = null;
}
if (target) {
if (!moved) preedit?.setAttribute("data-openidea-ime-anchor", "");
moved = true;
write(target);
} else if (moved) {
// The drawn caret is gone: hand the position back to xterm.
moved = false;
preedit?.removeAttribute("data-openidea-ime-anchor");
write(cursorSpot());
}
};
// Registered after `open()`, so these run after xterm's own render and cursor handlers have
// put the textarea back on the terminal cursor.
const render = term.onRender(() => place());
const cursorMove = term.onCursorMove(() => place());
// xterm re-places the textarea as the input method opens and on every update; the observer lands
// in the microtask after that write, before the browser asks for the caret rectangle.
const observer = new MutationObserver(() => {
if (target) write(target);
});
for (const element of elements) observer.observe(element, { attributes: true, attributeFilter: ["style"] });
return () => {
render.dispose();
cursorMove.dispose();
observer.disconnect();
target = null;
if (moved) {
moved = false;
preedit?.removeAttribute("data-openidea-ime-anchor");
write(cursorSpot());
}
};
}
+2
Переглянути файл
@@ -24,6 +24,7 @@ import { installSelectionHighlights, type SelectionHighlightController } from ".
import { installLinkHighlights, xtermLink, type LinkHighlightController } from "./linkHighlights";
import { installTerminalPaste, pasteIntoTerminal, pasteTerminalClipboard } from "./paste";
import { ImeCommitGate } from "./imeCommit";
import { installImeAnchor } from "./imeAnchor";
import { ownTerminalInput } from "./imeInput";
import { findTerminalLinks, resolvePath, type TerminalLink } from "./links";
import { parseShellCommand } from "@/platform/commandLine";
@@ -681,6 +682,7 @@ export class TerminalSession {
this.opts.onFocus(this.key);
});
this.watchImeCommit();
this.disposables.push({ dispose: installImeAnchor({ host: this.host, term: this.term }) });
if (this.pendingFocus) {
this.pendingFocus = false;
if (this.focusStayedHere()) this.focus();
+10 -2
Переглянути файл
@@ -412,11 +412,12 @@ describe("terminalFont", () => {
it("prefers the terminal's fallback over the editor's", () => {
const font = terminalFont(
{ ...t, fallbackFontFamily: "Sarasa Mono SC" },
{ ...editor, fallbackFont: "PingFang SC" },
{ ...editor, fallbackFont: "Source Code Pro" },
BASE,
);
expect(font.family).toContain('"Sarasa Mono SC"');
expect(font.family).not.toContain("PingFang SC");
// The CJK faces are always named (see the test below), so the editor's pick must not be one.
expect(font.family).not.toContain("Source Code Pro");
});
it("follows the editor's Typography Settings weights with Use editor font", () => {
@@ -446,6 +447,13 @@ describe("terminalFont", () => {
expect(terminalFont({ ...t, useEditorFont: false }, editor, BASE).letterSpacing).toBe(0);
expect(terminalFont({ ...t, useEditorFont: false, columnWidth: 1.5 }, editor, BASE).letterSpacing).toBe(3);
});
it("names CJK faces after the icon fonts so a wide character keeps two cells", () => {
const { family } = terminalFont(t, editor, BASE);
// After the icon fonts: they must win their own glyphs, and only CJK falls through to these.
expect(family.indexOf('"Microsoft YaHei"')).toBeGreaterThan(family.indexOf('"Symbols Nerd Font"'));
expect(family).toContain('"PingFang SC", "Noto Sans CJK SC", "Noto Sans SC", "Source Han Sans SC"');
expect(family.endsWith(', "Source Han Sans SC", monospace')).toBe(true);
});
});
describe("terminal tab titles", () => {
+15 -3
Переглянути файл
@@ -6,7 +6,14 @@
*/
import type { ITheme, Terminal } from "@xterm/xterm";
import { fontWeightOf } from "@/platform/editorSettings";
import { fontsLoaded, monoStack, nerdFontFaces, resolveMonoFont } from "@/platform/fonts";
import {
CJK_FALLBACK_FACES,
fontsLoaded,
monoStack,
nerdFontFaces,
quoteFontFamily,
resolveMonoFont,
} from "@/platform/fonts";
import { computedTokenColor, parseColor, type Rgba } from "@/platform/cssColor";
export { parseColor, type Rgba };
@@ -178,9 +185,14 @@ export interface TerminalFont {
boldWeight: number;
}
/** Nerd Fonts before the generic family, so per-glyph fallback finds prompt icons. */
/**
* Nerd Fonts before the generic family, so per-glyph fallback finds prompt icons, then the CJK
* faces: a wide character xterm only finds through the webview's own fallback measures one way and
* draws another (see `CJK_FALLBACK_FACES`), which drifts any row that mixes CJK with a background.
*/
function withNerdFonts(family: string): string {
return `${family.replace(/,\s*monospace\s*$/i, "")}, ${nerdFontFaces().join(", ")}, monospace`;
const cjk = CJK_FALLBACK_FACES.map(quoteFontFamily).join(", ");
return `${family.replace(/,\s*monospace\s*$/i, "")}, ${nerdFontFaces().join(", ")}, ${cjk}, monospace`;
}
/**
+9
Переглянути файл
@@ -17,6 +17,15 @@
overflow: clip;
}
/* During a composition xterm clips its composition view to the space between the cursor and the
right edge, and sizes the helper textarea from that view. A program that leaves the cursor in the
last column therefore leaves one cell of room, and the pre-edit text is painted almost invisibly.
The view is drawn on the caret instead (imeAnchor), so the width that matters is the space from
that caret to the edge — which `.xterm` clips anyway. */
.xterm .composition-view[data-openidea-ime-anchor] {
max-width: none !important;
}
/* An icon or fallback symbol wider than its cell stays over the next cell's background
(domRowCache), while selected spans keep xterm's `.xterm-decoration-top` z-index (2). */
.xterm .xterm-rows .openidea-terminal-icon:not(.xterm-decoration-top) {
+1 -1
Переглянути файл
@@ -32,7 +32,7 @@ export interface ChooseRevisionOptions {
tags?: boolean;
branchesOnly?: boolean;
placeholder?: string;
repositories?: string[];
repositories?: (string | null)[];
commonOnly?: boolean;
}
+49
Переглянути файл
@@ -115,6 +115,55 @@ describe("pruneFilteredEdges", () => {
const commits = [c("m", "b", "f"), c("f", "a"), c("b", "a"), c("a")];
expect(pruneFilteredEdges(commits)).toEqual(commits);
});
it("does not fan out connections to filtered ancestors that are not loaded yet", () => {
// The #5345 history under an author filter: the merge's hidden parent projects onto
// every older matching commit, deepest first. Only the first 300 rows are loaded.
const n = 340;
const older = ["root", ...Array.from({ length: n - 1 }, (_, i) => `a${i + 1}`)];
const merge: GraphCommit = {
id: "tip",
parents: [`a${n}`, ...older],
dashed: [false, ...older.map(() => true)],
edgeTypes: ["normal", ...older.map(() => "filtered" as const)],
};
const chain = Array.from({ length: n }, (_, i) => shown(`a${n - i}`, n - i === 1 ? "root" : `a${n - i - 1}`));
const all = [merge, ...chain, c("root")];
expect(all).toHaveLength(342);
const page = pruneFilteredEdges(all.slice(0, 300));
expect(page[0]!.parents).toEqual([`a${n}`]);
expect(computeGraph(page).rows[0]!.width).toBe(1);
expect(pruneFilteredEdges(all)[0]!.parents).toEqual([`a${n}`]);
});
it("keeps one connection leaving the page and restores the rest once they load", () => {
// Sibling side branches: neither reaches the other, but neither is loaded yet.
const all = [filtered("tip", "left", "right"), shown("left", "base"), shown("right", "base"), c("base")];
expect(pruneFilteredEdges(all.slice(0, 1))[0]!.parents).toEqual(["left"]);
// `left` leads further down the log, so `right` still waits for its own row...
expect(pruneFilteredEdges(all.slice(0, 2))[0]!.parents).toEqual(["left"]);
// ...and gets its connection back as soon as it is loaded.
expect(pruneFilteredEdges(all.slice(0, 3))[0]!.parents).toEqual(["left", "right"]);
expect(pruneFilteredEdges(all)[0]!.parents).toEqual(["left", "right"]);
});
it("prefers a real parent over filtered ones when all of them are below the page", () => {
const real = { id: "x", kind: "normal" as const };
const hidden = ["y", "z"].map((id) => ({ id, kind: "filtered" as const }));
for (const order of [
[real, ...hidden],
[...hidden, real],
]) {
const merge: GraphCommit = {
id: "m",
parents: order.map((p) => p.id),
dashed: order.map((p) => p.kind === "filtered"),
edgeTypes: order.map((p) => p.kind),
};
expect(pruneFilteredEdges([merge])[0]!.parents).toEqual(["x"]);
}
});
});
describe("straightenLaneChanges", () => {
+23
Переглянути файл
@@ -60,6 +60,29 @@ describe("graph projections", () => {
expect(rows[0]!.down[0]!.dashed).toBe(true);
});
it("keeps a filtered merge narrow while its older matches are still below the page", () => {
// The first page of an author-filtered log: the merge's hidden parent projects onto
// older matches that are not loaded yet, while its real parent leads there too (#5345).
const row = (id: string, realParents: string[], graphParents: string[], dashed: boolean[]) => ({
...commit(id, realParents),
repo: "/repo",
graphParents,
graphDashed: dashed,
});
const page = [
row("merge", ["a3", "hidden3"], ["a3", "root", "a1", "a2"], [false, true, true, true]),
row("a3", ["a2"], ["a2"], [false]),
];
const { rows, graph } = presentLogGraph(
page,
DEFAULT_LOG_OPTIONS,
{ expanded: new Set(), collapsed: new Set(), merges: new Set() },
new Set(),
);
expect(graph[0]!.parents).toEqual([commitKey({ id: "a3", repo: "/repo" })]);
expect(rows[0]!.width).toBe(1);
});
it("preserves filter dashes even when collapse hides no additional commits", () => {
const c = { ...commit("tip", ["base"]), dashed: [true] };
const collapsed = collapseLinear([c, commit("base")], new Set(["tip"]));
+11 -8
Переглянути файл
@@ -160,24 +160,27 @@ describe("computeGraph lane slots", () => {
});
});
describe("presentLogGraph", () => {
describe.each([true, false])("presentLogGraph (refs: %s)", (withRefs) => {
const optionCombinations: GraphOptions[] = [false, true].flatMap((collapseLinear) =>
[false, true].flatMap((linearizeMerges) =>
[false, true].map((longEdges) => ({ collapseLinear, linearizeMerges, longEdges })),
),
);
it.each([true, false])("keeps every option and fragment combination unchanged (refs: %s)", (withRefs) => {
const commits = history(2400, withRefs);
const head = new Set([commitKey(commits[0]!)]);
const variants = fragmentVariants(commits);
for (const options of optionCombinations)
const commits = history(2400, withRefs);
const head = new Set([commitKey(commits[0]!)]);
const variants = fragmentVariants(commits);
it.each(optionCombinations)(
"keeps fragments equivalent (collapseLinear: $collapseLinear, linearizeMerges: $linearizeMerges, longEdges: $longEdges)",
(options) => {
for (const [name, fragments] of Object.entries(variants)) {
vi.mocked(computeGraph).mockImplementation(real);
const got = presentLogGraph(commits, options, fragments, head);
vi.mocked(computeGraph).mockImplementation(referenceComputeGraph);
const want = presentLogGraph(commits, options, fragments, head);
expect(got, `${JSON.stringify(options)} ${name}`).toEqual(want);
expect(got, name).toEqual(want);
}
});
},
);
});
+12
Переглянути файл
@@ -421,6 +421,18 @@ describe("commit navigation", () => {
expect(useGitLog.getState().selected).toBe(commitKey(commits[2]!));
});
it("loads every filtered connection below the page before offering the parents", async () => {
// Neither side branch is loaded yet, so the graph defers `right` behind `left` (#5345).
const at = (commit: Commit, logPosition: number) => ({ ...commit, logPosition, logTotal: 4 });
const tip = { ...at(c("tip", ["hidden"]), 0), graphParents: ["left", "right"], graphDashed: [true, true] };
useGitLog.setState({ commits: [{ ...tip, repo: "/repo" }], done: false });
api.log
.mockResolvedValueOnce(ok([at(c("left", ["base"]), 1)]))
.mockResolvedValueOnce(ok([at(c("right", ["base"]), 2), at(c("base"), 3)]));
await goToParent(useGitLog.getState().commits[0]!);
expect(api.choose.mock.lastCall?.[0].map((x: Commit) => x.id)).toEqual(["left", "right"]);
});
it("does not navigate after a reference lookup is superseded by a filter change", async () => {
let finish!: (value: ReturnType<typeof ok<Commit[]>>) => void;
api.log.mockImplementationOnce(
+8
Переглянути файл
@@ -17,6 +17,7 @@ import { commitKey, graphCommit, mergeRepoLogs, type RepoCommit } from "../multi
import { buildRepositoryBranchTree } from "../branches";
import {
emptyFilters,
goToRefRepositories,
installGitLog,
loadMore,
openLogTab,
@@ -218,6 +219,13 @@ describe("multi-root Git log", () => {
expect(toggleRepository(["/project/back"], "/project/back")).toEqual([]);
});
it("offers Go to Hash/Branch/Tag every repository when the Repository filter is cleared", () => {
useGitLog.setState({ filters: { ...emptyFilters(), repositories: [] } });
expect(goToRefRepositories()).toEqual(["/project/front", "/project/back"]);
useGitLog.setState({ filters: { ...emptyFilters(), repositories: ["/project/back"] } });
expect(goToRefRepositories()).toEqual(["/project/back"]);
});
it("groups identical local and remote names under distinct repository nodes", () => {
const roots = buildRepositoryBranchTree(
["front", "back"].map((name) => ({
+84
Переглянути файл
@@ -0,0 +1,84 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const openLog = vi.hoisted(() => vi.fn());
vi.mock("@/workbench/contributions", async (importOriginal) => ({
...(await importOriginal<typeof import("@/workbench/contributions")>()),
maybeEditorService: () => ({ activePath: () => "/repo/active.ts" }),
toolWindowService: () => ({ show: () => undefined }),
}));
vi.mock("../logStore", async (importOriginal) => ({
...(await importOriginal<typeof import("../logStore")>()),
openLogTab: openLog,
}));
import { executeAction } from "@/platform/actions";
import { clearContext, setContext } from "@/platform/context";
import { clearProjectViewLead, provideProjectViewSelection, setProjectViewLead } from "@/workbench/contributions";
import { registerVcsActions } from "../actions";
let unregister: () => void;
let disposeSelection: () => void;
let paths: string[];
function selectRoot() {
paths = ["/repo"];
setProjectViewLead({ path: "/repo", dir: true });
}
beforeEach(() => {
openLog.mockClear();
paths = [];
disposeSelection = provideProjectViewSelection(() => paths);
setContext("vcsAvailable", true);
setContext("projectViewFocus", false);
setContext("editorFocus", false);
unregister = registerVcsActions();
});
afterEach(() => {
unregister();
disposeSelection();
clearProjectViewLead();
for (const key of ["vcsAvailable", "projectViewFocus", "editorFocus"]) clearContext(key);
});
describe("Show History for File", () => {
it("uses the selected project root when the tree has the lead without keyboard focus", async () => {
selectRoot();
await executeAction("vcs.showHistory");
expect(openLog).toHaveBeenCalledWith("history", "/repo");
});
it("uses the focused editor even if the tree still has a lead", async () => {
selectRoot();
setContext("editorFocus", true);
await executeAction("vcs.showHistory");
expect(openLog).toHaveBeenCalledWith("history", "/repo/active.ts");
});
it("uses the active file after a tab switch clears the lead while the tree keeps its selection", async () => {
selectRoot();
clearProjectViewLead();
await executeAction("vcs.showHistory");
expect(openLog).toHaveBeenCalledWith("history", "/repo/active.ts");
});
it("uses the selected project root while the tree has keyboard focus without a lead", async () => {
paths = ["/repo"];
setContext("projectViewFocus", true);
await executeAction("vcs.showHistory");
expect(openLog).toHaveBeenCalledWith("history", "/repo");
});
it("keeps an explicit path ahead of the Project view's selection", async () => {
selectRoot();
await executeAction("vcs.showHistory", ["/repo/file.ts"]);
expect(openLog).toHaveBeenCalledWith("history", "/repo/file.ts");
});
it("falls back to the active file without a Project view selection", async () => {
await executeAction("vcs.showHistory");
expect(openLog).toHaveBeenCalledWith("history", "/repo/active.ts");
});
});
+3 -2
Переглянути файл
@@ -13,6 +13,7 @@ import {
editorService,
maybeEditorService,
notifications,
projectViewContextLead,
projectViewSelection,
toolWindowService,
type WorktreeReview,
@@ -282,9 +283,9 @@ function selectedPaths(arg: unknown): string[] {
return project.length ? project : contextPaths(arg);
}
/** Paths a file action targets: the Project view's selection while it has focus, else the open file. */
/** Uses the Project view's selection while the tree has focus or owns the context. */
function focusedPaths(arg: unknown, ctx: { projectViewFocus?: unknown }): string[] {
return ctx.projectViewFocus ? selectedPaths(arg) : contextPaths(arg);
return ctx.projectViewFocus || projectViewContextLead() ? selectedPaths(arg) : contextPaths(arg);
}
/**
+29 -12
Переглянути файл
@@ -356,30 +356,40 @@ export function collapseLinear<
* A filtered log connects a commit to the nearest matching ancestor along every merge
* path. Ancestors that another of the commit's connections already reaches would each
* open a lane of their own without adding one, so their filtered edges are dropped;
* real parents and collapsed-fragment connections stay as they are.
* real parents and collapsed-fragment connections stay as they are. Whether a target
* below the loaded page is reached cannot be told yet: while another connection
* already leads below the page, its filtered edge waits until the target is loaded.
*/
export function pruneFilteredEdges(commits: readonly GraphCommit[]): GraphCommit[] {
const positions = new Map(commits.map((c, i) => [c.id, i]));
const kindOf = (c: GraphCommit, i: number) => c.edgeTypes?.[i] ?? (c.dashed?.[i] ? "filtered" : "normal");
// Rows whose history continues below the page (parents come later in the log).
const leavesPage: boolean[] = [];
for (let at = commits.length - 1; at >= 0; at--) {
leavesPage[at] = commits[at]!.parents.some((p) => {
const pos = positions.get(p);
return pos == null || (pos > at && leavesPage[pos]!);
});
}
return commits.map((c) => {
if (c.parents.length < 2) return c;
if (!c.parents.some((_, i) => kindOf(c, i) === "filtered")) return c;
// Walk the parents shallowest first, tracking the rows the kept connections reach:
// a filtered parent already covered by them adds nothing (and a dropped one was
// covered itself, so its own reach is covered too). Parents only appear later in
// the log, so no walk goes past the deepest parent of the commit.
// Walk the loaded parents shallowest first, tracking the rows the kept connections
// reach: a filtered parent already covered by them adds nothing (and a dropped one
// was covered itself, so its own reach is covered too). Parents only appear later
// in the log, so no walk goes past the deepest parent of the commit.
const limit = Math.max(...c.parents.map((p) => positions.get(p) ?? -1));
const drop = new Set<number>();
const covered = new Set<number>();
for (const i of c.parents
.map((_, i) => i)
.sort((a, b) => (positions.get(c.parents[a]!) ?? Infinity) - (positions.get(c.parents[b]!) ?? Infinity))) {
const pos = positions.get(c.parents[i]!);
if (kindOf(c, i) === "filtered" && pos != null && covered.has(pos)) {
const indices = c.parents.map((_, i) => i);
const loaded = indices.filter((i) => positions.has(c.parents[i]!));
for (const i of loaded.sort((a, b) => positions.get(c.parents[a]!)! - positions.get(c.parents[b]!)!)) {
const pos = positions.get(c.parents[i]!)!;
if (kindOf(c, i) === "filtered" && covered.has(pos)) {
drop.add(i);
continue;
}
for (const stack = pos == null ? [] : [pos]; stack.length;) {
for (const stack = [pos]; stack.length;) {
const at = stack.pop()!;
if (covered.has(at)) continue;
covered.add(at);
@@ -389,8 +399,15 @@ export function pruneFilteredEdges(commits: readonly GraphCommit[]): GraphCommit
}
}
}
// Targets below the page: one connection leading there is enough until they load.
const unloaded = indices.filter((i) => !positions.has(c.parents[i]!));
const filteredBelow = unloaded.filter((i) => kindOf(c, i) === "filtered");
const leads =
unloaded.some((i) => kindOf(c, i) !== "filtered") ||
loaded.some((i) => !drop.has(i) && leavesPage[positions.get(c.parents[i]!)!]);
for (const i of leads ? filteredBelow : filteredBelow.slice(1)) drop.add(i);
if (!drop.size) return c;
const keep = c.parents.map((_, i) => i).filter((i) => !drop.has(i));
const keep = indices.filter((i) => !drop.has(i));
return {
...c,
parents: keep.map((i) => c.parents[i]!),
+2 -1
Переглянути файл
@@ -33,6 +33,7 @@ import {
goToChild,
goToParent,
goToRef,
goToRefRepositories,
openLogTab,
selectedCommits,
toggleCommitBookmark,
@@ -388,7 +389,7 @@ export function registerHistoryActions(): () => void {
const rev = await chooseRevision("Go to Hash/Branch/Tag", {
tags: true,
placeholder: "Enter hash or branch/tag name",
repositories: tab?.repo ? [tab.repo] : log.filters.repositories,
repositories: goToRefRepositories(log),
});
if (rev && !(await goToRef(rev)))
notifications().notify({ group: "vcs", level: "warning", title: `'${rev}' was not found in the log` });
+3 -2
Переглянути файл
@@ -33,10 +33,11 @@ export function presentLogGraph(
? new Set(source.filter((c) => !fragments.merges.has(c.id)).map((c) => c.id))
: fragments.merges;
const linear = options.linearizeMerges ? linearizeMerges(collapsed?.graph ?? source, expanded) : null;
const graph = pruneFilteredEdges(linear?.graph ?? collapsed?.graph ?? source);
const unpruned = linear?.graph ?? collapsed?.graph ?? source;
const graph = pruneFilteredEdges(unpruned);
const byId = new Map(all.map((c) => [commitKey(c), c]));
const commits = graph.map((c) => byId.get(c.id)!);
const laid = computeGraph(graph).rows;
const rows = straightenLaneChanges(compactLanes(options.longEdges ? laid : hideLongEdges(laid)));
return { commits, graph, rows, linear, collapsed };
return { commits, graph, unpruned, rows, linear, collapsed };
}
+23 -19
Переглянути файл
@@ -1336,15 +1336,20 @@ export function displayedLogGraph() {
export async function goToParent(c: Commit) {
const generation = useGitLog.getState().generation;
const find = () => {
const { graph, commits } = displayedLogGraph();
const parents = graph.find((x) => x.id === commitKey(c))?.parents ?? [];
return { parents, candidates: commits.filter((x) => parents.includes(commitKey(x))) };
const { graph, unpruned, commits } = displayedLogGraph();
const key = commitKey(c);
const parents = graph.find((x) => x.id === key)?.parents ?? [];
// A filtered connection below the loaded page is only decided once its target loads.
const pending = unpruned.find((x) => x.id === key)?.parents ?? [];
const loaded = new Set(commits.map(commitKey));
return {
parents,
complete: pending.every((p) => loaded.has(p)),
candidates: commits.filter((x) => parents.includes(commitKey(x))),
};
};
if (!find().parents.length) return;
await pageUntil(() => {
const { parents, candidates } = find();
return candidates.length === parents.length;
});
await pageUntil(() => find().complete);
if (useGitLog.getState().generation !== generation) return;
const { candidates } = find();
const chosen = candidates.length > 1 ? await chooseLogCommit(candidates, "Select Parent Commit") : candidates[0];
@@ -1395,6 +1400,16 @@ export function isMine(c: Commit, user: string | null): boolean {
);
}
/** The repositories Go to Hash/Branch/Tag looks in: the shown log's, else the filtered ones, else every root. */
export function goToRefRepositories(state: LogState = useGitLog.getState()): (string | null)[] {
const logTab = state.logTabs.find((t) => t.id === state.shownLog);
if (logTab?.repositories?.length) return logTab.repositories;
if (logTab?.repo) return [logTab.repo];
if (state.filters.repositories?.length) return state.filters.repositories;
const roots = useVcs.getState().roots;
return roots.length ? roots : [currentRepo()];
}
/**
* Go to Hash/Branch/Tag: selects the commit `rev` names, paging the log until it is
* loaded (and clearing the filters when they hide it). False when there is no such commit.
@@ -1410,18 +1425,7 @@ export async function goToRef(rev: string, repository?: string | null): Promise<
await load;
};
const logTab = state.logTabs.find((t) => t.id === state.shownLog);
const repos =
repository !== undefined
? [repository]
: logTab?.repositories?.length
? logTab.repositories
: logTab?.repo
? [logTab.repo]
: state.filters.repositories?.length
? state.filters.repositories
: useVcs.getState().roots.length
? useVcs.getState().roots
: [currentRepo()];
const repos = repository !== undefined ? [repository] : goToRefRepositories(state);
if (repos.length > 1) {
const candidates = (
await Promise.all(
+18
Переглянути файл
@@ -121,6 +121,24 @@ const NERD_FONTS = [
"Hasklug Nerd Font",
"CaskaydiaCove Nerd Font",
];
/**
* CJK faces, named after the icon fonts on a grid's font stack. Such a renderer measures each
* glyph once to derive its per-cell letter spacing, and when the face drawing wide characters is
* only implicit (the webview's own fallback) that measurement and the rendering can disagree by
* about a pixel per character: every wide character then takes less than its two cells, and rows
* that mix CJK with a full-width background — pi's overlay panel, a boxed CLI — drift left, by up
* to two cells across one panel. Naming the face makes measurement and rendering use the same one,
* whatever its own advance, and two cells stay two cells. The webview skips missing families, so
* one list covers every platform.
*/
export const CJK_FALLBACK_FACES = [
"Microsoft YaHei",
"PingFang SC",
"Noto Sans CJK SC",
"Noto Sans SC",
"Source Han Sans SC",
];
/** In running text the proportional faces give icons their own width instead of one cell's. */
const UI_NERD_FONTS = [
"JetBrainsMono Nerd Font Propo",
+1
Переглянути файл
@@ -2589,6 +2589,7 @@
"Rust File": "Rust File",
"TypeScript File": "TypeScript File",
"React Component": "React Component",
"Svelte Component": "Svelte Component",
"JavaScript File": "JavaScript File",
"Python File": "Python File",
"Go File": "Go File",
+1
Переглянути файл
@@ -8960,6 +8960,7 @@
"Rust File": "Rust 文件",
"TypeScript File": "TypeScript 文件",
"React Component": "React 组件",
"Svelte Component": "Svelte 组件",
"JavaScript File": "JavaScript 文件",
"Python File": "Python 文件",
"Go File": "Go 文件",
+18 -2
Переглянути файл
@@ -5,6 +5,7 @@ import {
type InputHTMLAttributes,
type FocusEvent,
type KeyboardEvent,
type MouseEvent,
type ReactNode,
type Ref,
type TextareaHTMLAttributes,
@@ -12,6 +13,7 @@ import {
import clsx from "clsx";
import { Icon, type IconName } from "./icons";
import { IconButton } from "./Button";
import { startDragAutoscroll } from "./dragAutoscroll";
import styles from "./Input.module.css";
import { setContext } from "@/platform/context";
import { useGivenTx } from "@/platform/i18n";
@@ -37,6 +39,7 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
autoComplete = "off",
placeholder,
onFocus,
onMouseDown,
"aria-label": ariaLabel,
...rest
},
@@ -62,6 +65,10 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
}
onFocus?.(e);
}}
onMouseDown={(e) => {
onMouseDown?.(e);
startDragAutoscroll(e);
}}
className={clsx(styles.input, variant === "bare" ? styles.bare : styles.framed, mono && styles.mono, className)}
{...rest}
/>
@@ -163,7 +170,7 @@ export const SearchField = forwardRef<HTMLInputElement, SearchFieldProps>(functi
commands.current.newLine = multiline ? insertNewLine : undefined;
// oxlint-disable-next-line react/refs
commands.current.history = onHistory;
const { onKeyDown, onFocus, onBlur, ...fieldProps } = rest;
const { onKeyDown, onFocus, onBlur, onMouseDown, ...fieldProps } = rest;
const keyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (multiline && isNewLineKey(e)) {
e.preventDefault();
@@ -186,7 +193,16 @@ export const SearchField = forwardRef<HTMLInputElement, SearchFieldProps>(functi
}
onBlur?.(e);
};
const handlers = { onKeyDown: keyDown, onFocus: focus, onBlur: blur };
const mouseDown = (e: MouseEvent<HTMLInputElement>) => {
onMouseDown?.(e);
startDragAutoscroll(e);
};
const handlers = {
onKeyDown: keyDown,
onFocus: focus,
onBlur: blur,
onMouseDown: mouseDown,
};
// Removing a focused field fires no blur.
useEffect(() => {
const own = commands.current;
+65
Переглянути файл
@@ -319,6 +319,71 @@ describe("Tree speed search", () => {
}
});
it.each([
{ os: "macos", preset: "intellij-macos", binding: "Meta+V", key: "v", modifiers: { metaKey: true } },
{ os: "windows", preset: "intellij-windows", binding: "Ctrl+V", key: "v", modifiers: { ctrlKey: true } },
{
os: "windows",
preset: "intellij-windows",
binding: "Shift+Insert",
key: "Insert",
modifiers: { shiftKey: true },
},
])("$binding routes clipboard text to speed search", ({ os, preset, binding, key, modifiers }) => {
const previousOs = usePlatform.getState().os;
usePlatform.setState({ os });
const pasteFiles = vi.fn();
useKeymap.setState({ preset, overrides: { "test.paste": [binding] } });
const find = os === "macos" ? { metaKey: true } : { ctrlKey: true };
const dispose = [
registerAction({ id: "test.paste", title: "Paste", run: pasteFiles }),
installKeyboardDispatcher(),
];
try {
const view = setup({
defaultExpanded: ["src", "main"],
roots: [...data, { id: "notes v1" }, { id: "notes v1" }],
});
const tree = view.tree;
const paste = (text: string) =>
fireEvent.paste(tree, { clipboardData: { getData: () => text } } as unknown as ClipboardEventInit);
view.key("ArrowDown");
// Find arms the search with an empty query; the clipboard text becomes the query.
view.key("f", find);
expect(screen.getByRole("status").textContent).toBe("");
paste("index.t");
expect(screen.getByRole("status")).toHaveTextContent(/^index\.t$/);
expect(view.lead()).toBe("index.ts");
// A line of pasted text joins the query as typing it would; a wrapped name stays one line.
paste("s");
expect(screen.getByRole("status")).toHaveTextContent(/^index\.ts$/);
// Paste is the query's, not the view's file Paste, while the search is active.
view.key(key, modifiers);
expect(pasteFiles).not.toHaveBeenCalled();
// A blank clipboard changes nothing.
paste(" ");
expect(screen.getByRole("status")).toHaveTextContent(/^index\.ts$/);
// Closed, the view's Paste owns the shortcut again.
view.key("Escape");
view.key(key, modifiers);
expect(pasteFiles).toHaveBeenCalledOnce();
expect(view.tree).toHaveFocus();
// A multi-line clipboard is flattened into the one-line query.
view.key("f", find);
paste("App\n.tsx");
expect(screen.getByRole("status")).toHaveTextContent(/^App \.tsx$/);
view.key("Escape");
view.key("f", find);
paste("notes v1");
expect(screen.getByRole("status").textContent).toBe("notes v1");
expect(view.lead()).toBe("notes v1");
} finally {
dispose.forEach((d) => d());
useKeymap.setState({ overrides: {} });
usePlatform.setState({ os: previousOs });
}
});
it("filter mode hides non-matching rows but keeps ancestors", () => {
const { tree, key } = setup({ defaultExpanded: ["src", "main"], speedSearchMode: "filter" });
key("ArrowDown");
+30 -4
Переглянути файл
@@ -43,6 +43,13 @@ import { useIconRowHeight } from "./iconAppearance";
export type { TreeReorder } from "./treeReorder";
/** The host's native Paste shortcuts. */
const isPasteStroke = (stroke: string) =>
isMacHost() ? stroke === "Meta+V" : stroke === "Ctrl+V" || stroke === "Shift+Insert";
/** Pasted text as one query line: a speed search has no caret and no newlines. */
const queryLine = (text: string) => text.replace(/[\r\n\u2028\u2029]+/g, " ").trim();
export interface TreeRowState {
depth: number;
expanded: boolean;
@@ -398,19 +405,22 @@ export function Tree<T>(props: TreeProps<T>) {
pendingScrollToLead.current = null;
}, [lead, indexOfKey, virtualizer]);
// Speed search owns Escape while active, and ⌫ with any modifier: the query is edited like a
// text field instead of the view's shortcuts running (⌘⌫ is Drop… in the Database view).
// While speed search is active, reserve Backspace and the native Paste shortcuts for the query.
// The view's shortcuts can drop a database object or paste files into the project.
useEffect(() => {
if (!searching) return;
const release = acquirePopup();
const unclaim = registerKeyClaim(
(e) => e.key === "Backspace" && e.target instanceof Node && !!scrollRef.current?.contains(e.target),
(e, stroke) =>
e.target instanceof Node &&
!!scrollRef.current?.contains(e.target) &&
(e.key === "Backspace" || (speedSearch && isPasteStroke(stroke))),
);
return () => {
release();
unclaim();
};
}, [searching]);
}, [searching, speedSearch]);
const setExpanded = (row: Row<T>, open: boolean) => {
if (!row.expandable || row.expanded === open) return;
@@ -545,6 +555,21 @@ export function Tree<T>(props: TreeProps<T>) {
return i;
};
/** The active speed search takes pasted text: its query is edited like a text field. */
const onPaste = (e: React.ClipboardEvent) => {
if (e.defaultPrevented || !speedSearch || !searching) return;
// An inline editor (rename, new value) inside a row keeps the native paste.
if ((e.target as HTMLElement | null)?.closest?.("input, textarea, [contenteditable]")) return;
const text = queryLine(e.clipboardData?.getData("text/plain") ?? "");
if (!text) return;
e.preventDefault();
e.stopPropagation();
const q = query + text;
setQuery(q);
const hit = findMatch(leadIndex, 1, true, q);
if (hit >= 0) selectIndex(hit);
};
const onKeyDown = (e: KeyboardEvent) => {
const row = leadIndex >= 0 ? rows[leadIndex] : undefined;
const pageSize = Math.max(1, Math.floor((scrollRef.current?.clientHeight ?? 300) / rowHeight) - 1);
@@ -728,6 +753,7 @@ export function Tree<T>(props: TreeProps<T>) {
tabIndex={0}
className={styles.tree}
onKeyDown={onKeyDown}
onPaste={onPaste}
onBlur={(e) => {
if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;
endSearch();
+80
Переглянути файл
@@ -0,0 +1,80 @@
import { cleanup, fireEvent, render } from "@testing-library/react";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { Input, SearchField } from "./Input";
const distancePerCharacter = 20;
const fieldWidth = 100;
const value = "字".repeat(30);
beforeEach(() => {
vi.useFakeTimers();
const canvasContext = {
measureText: (text: string) => ({ width: text.length * distancePerCharacter }),
} as CanvasRenderingContext2D;
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(canvasContext);
});
afterEach(() => {
fireEvent.mouseUp(window);
cleanup();
vi.useRealTimers();
vi.restoreAllMocks();
});
function setFieldGeometry(field: HTMLInputElement | HTMLTextAreaElement) {
Object.defineProperties(field, {
clientWidth: { value: fieldWidth },
scrollWidth: { value: value.length * distancePerCharacter },
});
vi.spyOn(field, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, fieldWidth, 20));
}
it.each([
{ edge: "left", pointerX: -1, endpoint: "selectionStart" },
{ edge: "right", pointerX: fieldWidth + 1, endpoint: "selectionEnd" },
] as const)("keeps scrolling past wide characters at the $edge edge", ({ edge, pointerX, endpoint }) => {
const view = render(<SearchField value={value} onChange={() => {}} multiline />);
const field = view.getByRole("textbox") as HTMLTextAreaElement;
setFieldGeometry(field);
field.focus();
field.scrollLeft = 200;
field.setSelectionRange(12, 12);
fireEvent.mouseDown(field, { button: 0, clientX: 42, clientY: 10 });
fireEvent.mouseMove(window, { buttons: 1, clientX: pointerX, clientY: 10 });
for (let i = 0; i < 25; i++) vi.advanceTimersToNextFrame();
if (edge === "left") {
expect(field.scrollLeft).toBeLessThan(200);
expect(field[endpoint]).toBeLessThan(10);
expect(field.selectionEnd).toBe(12);
} else {
expect(field.scrollLeft).toBeGreaterThan(200);
expect(field[endpoint]).toBeGreaterThan(15);
expect(field.selectionStart).toBe(12);
}
fireEvent.mouseUp(window);
const offset = field.scrollLeft;
vi.advanceTimersToNextFrame();
expect(field.scrollLeft).toBe(offset);
});
it.each(["number", "date", "password"])("leaves selection to the browser for %s inputs", (type) => {
const { container } = render(<Input type={type} />);
const field = container.querySelector("input")!;
setFieldGeometry(field);
field.focus();
const selection = vi.spyOn(field, "setSelectionRange").mockImplementation(() => {});
fireEvent.mouseDown(field, { button: 0, clientX: 42, clientY: 10 });
expect(fireEvent.mouseMove(window, { buttons: 1, clientX: 120, clientY: 10 })).toBe(true);
expect(selection).not.toHaveBeenCalled();
});
it("respects a caller that prevents the start of a drag", () => {
const view = render(<Input defaultValue={value} onMouseDown={(e) => e.preventDefault()} />);
const field = view.getByRole("textbox") as HTMLInputElement;
setFieldGeometry(field);
field.focus();
fireEvent.mouseDown(field, { button: 0, clientX: 42, clientY: 10 });
expect(fireEvent.mouseMove(window, { buttons: 1, clientX: 120, clientY: 10 })).toBe(true);
expect(field.scrollLeft).toBe(0);
});
+126
Переглянути файл
@@ -0,0 +1,126 @@
import type { MouseEvent as ReactMouseEvent } from "react";
type TextField = HTMLInputElement | HTMLTextAreaElement;
let canvas: HTMLCanvasElement | null = null;
function textWidth(field: TextField): ((text: string) => number) | null {
canvas ??= document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (!ctx) return null;
const s = getComputedStyle(field);
ctx.font = `${s.fontStyle} ${s.fontWeight} ${s.fontSize} ${s.fontFamily}`;
return (text) => ctx.measureText(text).width;
}
/** Column of `line` whose left edge is nearest to `x` (px from the line start). */
function columnAt(line: string, x: number, width: (text: string) => number): number {
let lo = 0;
let hi = line.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (width(line.slice(0, mid + 1)) < x) lo = mid + 1;
else hi = mid;
}
if (lo < line.length && width(line.slice(0, lo + 1)) - x < x - width(line.slice(0, lo))) lo++;
return lo;
}
/**
* WebKitGTK extends a text field's selection while the mouse is dragged past
* its left or right edge, but never scrolls the text along. While the pointer
* is outside, move the selection focus and the scroll position ourselves, faster
* the further out the pointer is, like IDEA's text fields.
*/
export function startDragAutoscroll(e: ReactMouseEvent<TextField>) {
const field = e.currentTarget;
if (e.defaultPrevented || e.button !== 0 || e.detail > 1 || field.selectionStart === null) return;
// The canvas measures the real value, while the browser draws masking characters.
if (field instanceof HTMLInputElement && field.type === "password") return;
if (field.scrollWidth <= field.clientWidth || getComputedStyle(field).direction === "rtl") return;
const width = textWidth(field);
if (!width) return;
let pointerX = e.clientX;
let pointerY = e.clientY;
let frame = 0;
let anchor: number | null = null;
let focus = 0;
const edges = () => {
const s = getComputedStyle(field);
const rect = field.getBoundingClientRect();
const left = rect.left + field.clientLeft;
const start = left + parseFloat(s.paddingLeft);
return {
start,
end: left + field.clientWidth - parseFloat(s.paddingRight),
top: rect.top,
bottom: rect.bottom,
};
};
const overshoot = () => {
const { start, end, top, bottom } = edges();
if (field instanceof HTMLTextAreaElement && (pointerY < top || pointerY > bottom)) return 0;
return pointerX < start ? pointerX - start : pointerX > end ? pointerX - end : 0;
};
const tick = () => {
frame = 0;
if (!field.isConnected || field.selectionStart === null) return stop();
const over = overshoot();
if (!over) {
anchor = null;
return;
}
if (anchor === null) {
const backward = field.selectionDirection === "backward";
anchor = (backward ? field.selectionEnd : field.selectionStart) ?? 0;
focus = (backward ? field.selectionStart : field.selectionEnd) ?? 0;
}
const value = field.value;
const lineStart = focus > 0 ? value.lastIndexOf("\n", focus - 1) + 1 : 0;
const newline = value.indexOf("\n", focus);
const line = value.slice(lineStart, newline < 0 ? value.length : newline);
const { start, end } = edges();
const visible = end - start;
const step = Math.sign(over) * Math.min(Math.max(Math.abs(over) / 2, 2), 40);
// Scroll by pixels even when the next caret position is more than one step away.
const previous = field.scrollLeft;
field.scrollLeft = previous + step;
const scrolled = field.scrollLeft;
focus = lineStart + columnAt(line, scrolled + (over < 0 ? 0 : visible), width);
field.setSelectionRange(Math.min(anchor, focus), Math.max(anchor, focus), focus < anchor ? "backward" : "forward");
field.scrollLeft = scrolled;
if (scrolled !== previous) frame = requestAnimationFrame(tick);
};
const move = (ev: MouseEvent) => {
if (!(ev.buttons & 1)) return stop();
if (!field.isConnected) return stop();
pointerX = ev.clientX;
pointerY = ev.clientY;
if (!overshoot()) {
cancelAnimationFrame(frame);
frame = 0;
anchor = null;
return;
}
// Our focus wins over WebKit's, which jumps to the line's start or end.
ev.preventDefault();
if (!frame) tick();
};
const stop = () => {
cancelAnimationFrame(frame);
frame = 0;
window.removeEventListener("mousemove", move, true);
window.removeEventListener("mouseup", stop, true);
window.removeEventListener("blur", stop);
field.removeEventListener("blur", stop);
field.removeEventListener("dragstart", stop);
};
window.addEventListener("mousemove", move, true);
window.addEventListener("mouseup", stop, true);
window.addEventListener("blur", stop);
field.addEventListener("blur", stop);
field.addEventListener("dragstart", stop);
}
+22 -2
Переглянути файл
@@ -146,12 +146,14 @@ it("ends Select All in the pane's last selectable text, not on its edge before t
expect(window.getSelection()!.toString()).not.toContain("Reply to the agent");
});
function TrackedVisibilityPane() {
function TrackedVisibilityPane({ rows = false }: { rows?: boolean }) {
const ref = useRef<HTMLDivElement>(null);
useSelectionVisibility(ref);
useSelectionVisibility(ref, true, rows ? "p" : undefined);
return (
<div ref={ref} data-testid="tracked">
<p>Tracked line</p>
<p>Second line</p>
<p>Third line</p>
</div>
);
}
@@ -194,3 +196,21 @@ it("keeps data-selection for one rendered frame after the selection leaves", ()
window.cancelAnimationFrame = prevCancel;
}
});
it("keeps only the selected conversation rows visible and releases rows the selection leaves", async () => {
const view = render(<TrackedVisibilityPane rows />);
const tracked = view.getByTestId("tracked");
const [first, second, third] = [...tracked.children];
const select = (start: Element, end: Element) => {
window.getSelection()!.setBaseAndExtent(start.firstChild!, 0, end.firstChild!, 1);
document.dispatchEvent(new Event("selectionchange"));
};
const marked = () => [...tracked.querySelectorAll("[data-selection]")];
select(first!, second!);
expect(marked()).toEqual([first, second]);
select(third!, third!);
expect(marked()).toEqual([first, second, third]);
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
expect(marked()).toEqual([third]);
expect(tracked).not.toHaveAttribute("data-selection");
});
+28 -11
Переглянути файл
@@ -111,32 +111,49 @@ function textEdge(root: HTMLElement, side: "start" | "end"): { node: Node; offse
}
/**
* Marks `ref` with `data-selection` while the document's selection intersects it, and keeps the
* Marks the pane or its intersecting rows with `data-selection` while the document's selection intersects it, and keeps the
* mark until the frame after the selection leaves. WebKit never clears the selection highlight of
* a subtree that skips rendering (`content-visibility: auto` or `hidden`); pairing `[data-selection]`
* with `content-visibility: visible` lets WebKit apply the deselection before skipping again.
*/
export function useSelectionVisibility(ref: RefObject<HTMLElement | null>, enabled = true): void {
export function useSelectionVisibility(ref: RefObject<HTMLElement | null>, enabled = true, rowSelector?: string): void {
useEffect(() => {
const el = ref.current;
if (!el || !enabled) return;
const doc = el.ownerDocument;
const win = doc.defaultView ?? window;
let frame = 0;
const selected = () => {
const marked = new Set<Element>();
const selectionRange = () => {
const sel = doc.getSelection();
return !!sel && !sel.isCollapsed && sel.rangeCount > 0 && sel.getRangeAt(0).intersectsNode(el);
return sel && !sel.isCollapsed && sel.rangeCount ? sel.getRangeAt(0) : null;
};
const update = () => {
win.cancelAnimationFrame(frame);
if (selected()) {
el.setAttribute("data-selection", "");
return;
const range = selectionRange();
if (range?.intersectsNode(el)) {
// Keep unrelated history at its remembered size while selecting visible text.
let targets: Iterable<Element> = [el];
if (rowSelector) {
const node = range.commonAncestorContainer;
const row = (node instanceof Element ? node : node.parentElement)?.closest(rowSelector);
targets = row?.parentElement === el ? [row] : el.querySelectorAll(`:scope > ${rowSelector}`);
}
for (const target of targets) {
if (!range.intersectsNode(target) || marked.has(target)) continue;
marked.add(target);
target.setAttribute("data-selection", "");
}
}
if (!el.hasAttribute("data-selection")) return;
if (![...marked].some((target) => !range?.intersectsNode(target))) return;
frame = win.requestAnimationFrame(() => {
frame = win.requestAnimationFrame(() => {
if (!selected()) el.removeAttribute("data-selection");
const current = selectionRange();
for (const target of marked) {
if (current?.intersectsNode(target)) continue;
target.removeAttribute("data-selection");
marked.delete(target);
}
});
});
};
@@ -145,9 +162,9 @@ export function useSelectionVisibility(ref: RefObject<HTMLElement | null>, enabl
return () => {
win.cancelAnimationFrame(frame);
doc.removeEventListener("selectionchange", update);
el.removeAttribute("data-selection");
for (const target of marked) target.removeAttribute("data-selection");
};
}, [ref, enabled]);
}, [ref, enabled, rowSelector]);
}
/**
+6
Переглянути файл
@@ -27,6 +27,7 @@ import type {
RunId,
SymbolKind,
} from "@/bindings";
import { getContext } from "@/platform/context";
import { notifyEach } from "@/platform/listeners";
import type { ProjectType } from "@/ui/projectType";
import type { MenuItem } from "@/ui/Menu";
@@ -1568,6 +1569,11 @@ export interface ProjectViewLead {
*/
export const useProjectViewLead = create<{ lead: ProjectViewLead | null }>(() => ({ lead: null }));
/** The Project view lead while the editor does not have focus. */
export function projectViewContextLead(): ProjectViewLead | null {
return getContext().editorFocus ? null : useProjectViewLead.getState().lead;
}
export function setProjectViewLead(lead: ProjectViewLead | null) {
const prev = useProjectViewLead.getState().lead;
if (prev?.path === lead?.path && prev?.dir === lead?.dir) return;