дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-25 10:54:44 +02:00
Порівняти коміти
20
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
74ed942f9c | ||
|
|
f9af0e7bff | ||
|
|
6449b68bb0 | ||
|
|
5d2d814610 | ||
|
|
3f18a8a274 | ||
|
|
f8a8ecb662 | ||
|
|
e2b1a2d732 | ||
|
|
db5a306450 | ||
|
|
bad9429e79 | ||
|
|
c942374f8a | ||
|
|
611b27b974 | ||
|
|
71f948cc9f | ||
|
|
79a750362a | ||
|
|
f1c0d098ad | ||
|
|
d9c1a9ff22 | ||
|
|
e86011fc87 | ||
|
|
f80dd0aa49 | ||
|
|
832c397e0b | ||
|
|
0f91aac0d4 | ||
|
|
d4b2ade24d |
No files matched your search
@@ -98,10 +98,10 @@ jobs:
|
||||
# Test fixtures write LF files; keep Git from converting them on checkout.
|
||||
- run: git config --global core.autocrlf false
|
||||
- run: cargo nextest run --workspace --no-fail-fast
|
||||
# nextest ran export_bindings, which rewrites src/bindings.ts.
|
||||
- name: Bindings are up to date
|
||||
# nextest ran export_bindings, which rewrites src/bindings.ts and the command snapshot.
|
||||
- name: Bindings and command snapshot are up to date
|
||||
if: runner.os == 'Linux'
|
||||
run: git diff --exit-code src/bindings.ts
|
||||
run: git diff --exit-code src/bindings.ts src-tauri/tests/commands.snap
|
||||
|
||||
# The remote development server ships as a static Linux binary (release-build.yml):
|
||||
# keep that build working.
|
||||
|
||||
Створено
@@ -4232,6 +4232,7 @@ dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"png 0.18.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-clipboard"
|
||||
description = "The OS clipboard's file list (Explorer <-> project view): Windows CF_HDROP or macOS NSPasteboard file URLs, no window or message loop"
|
||||
description = "The OS clipboard's file list (Explorer <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB or macOS NSPasteboard, no window or message loop"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -9,8 +9,14 @@ license.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2 = { version = "0.6", default-features = false, features = ["std"] }
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSDictionary", "NSEnumerator", "NSObject", "NSString", "NSURL", "NSValue"] }
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSPasteboard"] }
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSData", "NSDictionary", "NSEnumerator", "NSObject", "NSString", "NSURL", "NSValue"] }
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSBitmapImageRep", "NSImageRep", "NSPasteboard"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
png = "0.18"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
gtk = "0.18"
|
||||
|
||||
[dev-dependencies]
|
||||
png = "0.18"
|
||||
@@ -18,6 +18,10 @@
|
||||
//!
|
||||
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
|
||||
//! empty and [`set_files`] fails there.
|
||||
//!
|
||||
//! [`png`] reads an image (a screenshot) for the project view's Paste, which
|
||||
//! saves it as a file: `public.png` or `public.tiff` on macOS, the registered
|
||||
//! `PNG` format or `CF_DIB` on Windows. Linux reads it through GTK in the app.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -34,6 +38,19 @@ pub fn text() -> Option<String> {
|
||||
imp::text()
|
||||
}
|
||||
|
||||
/// The clipboard's image as PNG bytes, None when it holds none. Call on the main
|
||||
/// thread on macOS.
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
pub fn png() -> Option<Vec<u8>> {
|
||||
imp::png()
|
||||
}
|
||||
|
||||
/// Whether the clipboard holds an image, without reading it. Call on the main
|
||||
/// thread on macOS and Linux.
|
||||
pub fn has_image() -> bool {
|
||||
imp::has_image()
|
||||
}
|
||||
|
||||
/// Size of `DROPFILES`: `pFiles`, `pt` (two `LONG`s), `fNC`, `fWide`.
|
||||
const HEADER: usize = 20;
|
||||
|
||||
@@ -134,9 +151,62 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// `BI_RGB` and `BI_BITFIELDS`: uncompressed pixels, the forms screenshots take.
|
||||
#[cfg(any(windows, test))]
|
||||
const BI_RGB: u32 = 0;
|
||||
#[cfg(any(windows, test))]
|
||||
const BI_BITFIELDS: u32 = 3;
|
||||
|
||||
/// A packed DIB (`BITMAPINFOHEADER` or a later header, then the pixels) as PNG.
|
||||
/// Only 24- and 32-bit uncompressed bitmaps, which is what screenshots and
|
||||
/// copied images are; None for anything else. A 32-bit bitmap whose alpha is
|
||||
/// all zero (most writers leave it unset) is opaque.
|
||||
#[cfg(any(windows, test))]
|
||||
fn dib_to_png(dib: &[u8]) -> Option<Vec<u8>> {
|
||||
let u32_at = |at: usize| dib.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
|
||||
let header = u32_at(0)? as usize;
|
||||
let width = u32_at(4)? as i32;
|
||||
let height = u32_at(8)? as i32;
|
||||
let bits = u16::from_le_bytes([*dib.get(14)?, *dib.get(15)?]);
|
||||
let compression = u32_at(16)?;
|
||||
if header < 40 || width <= 0 || height == 0 || !matches!(bits, 24 | 32) {
|
||||
return None;
|
||||
}
|
||||
if compression != BI_RGB && !(compression == BI_BITFIELDS && bits == 32) {
|
||||
return None;
|
||||
}
|
||||
// A `BITMAPINFOHEADER` keeps the three bitfield masks after it; later
|
||||
// headers hold them inside. Masks other than BGRA's are not supported.
|
||||
let masks = if compression == BI_BITFIELDS && header == 40 { 12 } else { 0 };
|
||||
let colors = u32_at(32)? as usize;
|
||||
let (width, rows) = (width as usize, height.unsigned_abs() as usize);
|
||||
let stride = (width * bits as usize).div_ceil(32) * 4;
|
||||
let start = header + masks + colors * 4;
|
||||
let pixels = dib.get(start..start.checked_add(stride.checked_mul(rows)?)?)?;
|
||||
let step = bits as usize / 8;
|
||||
let mut rgba = Vec::with_capacity(width * rows * 4);
|
||||
for row in 0..rows {
|
||||
// A positive height stores the bottom row first.
|
||||
let source = if height > 0 { rows - 1 - row } else { row };
|
||||
let line = &pixels[source * stride..source * stride + width * step];
|
||||
for px in line.chunks_exact(step) {
|
||||
rgba.extend_from_slice(&[px[2], px[1], px[0], if step == 4 { px[3] } else { 255 }]);
|
||||
}
|
||||
}
|
||||
if step == 4 && rgba.as_chunks::<4>().0.iter().all(|px| px[3] == 0) {
|
||||
rgba.as_chunks_mut::<4>().0.iter_mut().for_each(|px| px[3] = 255);
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut encoder = png::Encoder::new(&mut out, width as u32, rows as u32);
|
||||
encoder.set_color(png::ColorType::Rgba);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
encoder.write_header().ok()?.write_image_data(&rgba).ok()?;
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use super::{HEADER, decode, encode, names_text};
|
||||
use super::{HEADER, decode, dib_to_png, encode, names_text};
|
||||
use std::ffi::c_void;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr;
|
||||
@@ -164,6 +234,59 @@ mod imp {
|
||||
fn GetClipboardData(format: u32) -> Handle;
|
||||
fn SetClipboardData(format: u32, memory: Handle) -> Handle;
|
||||
fn IsClipboardFormatAvailable(format: u32) -> i32;
|
||||
fn RegisterClipboardFormatW(name: *const u16) -> u32;
|
||||
}
|
||||
|
||||
/// `CF_DIB`: Windows synthesizes it from `CF_BITMAP` and `CF_DIBV5`, so every
|
||||
/// bitmap on the clipboard reads as one.
|
||||
const CF_DIB: u32 = 8;
|
||||
|
||||
/// The `PNG` format browsers and the Snipping Tool add beside the bitmap; it
|
||||
/// keeps transparency, so it is read first.
|
||||
fn png_format() -> u32 {
|
||||
let name: Vec<u16> = "PNG\0".encode_utf16().collect();
|
||||
unsafe { RegisterClipboardFormatW(name.as_ptr()) }
|
||||
}
|
||||
|
||||
pub fn has_image() -> bool {
|
||||
let png = png_format();
|
||||
(png != 0 && unsafe { IsClipboardFormatAvailable(png) } != 0)
|
||||
|| unsafe { IsClipboardFormatAvailable(CF_DIB) } != 0
|
||||
}
|
||||
|
||||
/// A copy of the clipboard's `format` block. Call with the clipboard open.
|
||||
fn read_block(format: u32) -> Option<Vec<u8>> {
|
||||
// SAFETY: the clipboard keeps the block alive while it is open, and
|
||||
// `GlobalSize` bounds the bytes read from it.
|
||||
unsafe {
|
||||
let memory = GetClipboardData(format);
|
||||
if memory.is_null() {
|
||||
return None;
|
||||
}
|
||||
let data = GlobalLock(memory);
|
||||
if data.is_null() {
|
||||
return None;
|
||||
}
|
||||
let bytes = std::slice::from_raw_parts(data as *const u8, GlobalSize(memory)).to_vec();
|
||||
GlobalUnlock(memory);
|
||||
Some(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn png() -> Option<Vec<u8>> {
|
||||
if !open() {
|
||||
return None;
|
||||
}
|
||||
let png = png_format();
|
||||
let image = if png != 0 && unsafe { IsClipboardFormatAvailable(png) } != 0 {
|
||||
read_block(png)
|
||||
} else if unsafe { IsClipboardFormatAvailable(CF_DIB) } != 0 {
|
||||
read_block(CF_DIB).and_then(|dib| dib_to_png(&dib))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
unsafe { CloseClipboard() };
|
||||
image
|
||||
}
|
||||
|
||||
#[link(name = "kernel32")]
|
||||
@@ -327,8 +450,8 @@ mod imp {
|
||||
use objc2::runtime::{AnyClass, AnyObject, ProtocolObject};
|
||||
use objc2::{ClassType, MainThreadMarker};
|
||||
use objc2_app_kit::{
|
||||
NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypeString, NSPasteboardURLReadingFileURLsOnlyKey,
|
||||
NSPasteboardWriting,
|
||||
NSBitmapImageFileType, NSBitmapImageRep, NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypePNG,
|
||||
NSPasteboardTypeString, NSPasteboardTypeTIFF, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
|
||||
};
|
||||
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
|
||||
use std::path::PathBuf;
|
||||
@@ -380,6 +503,33 @@ mod imp {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn has_image() -> bool {
|
||||
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
|
||||
autoreleasepool(|_| {
|
||||
// SAFETY: the types are AppKit constants, valid for the process' lifetime.
|
||||
let types = NSArray::from_slice(&[unsafe { NSPasteboardTypePNG }, unsafe { NSPasteboardTypeTIFF }]);
|
||||
NSPasteboard::generalPasteboard().availableTypeFromArray(&types).is_some()
|
||||
})
|
||||
}
|
||||
|
||||
/// PNG as copied, else TIFF (what macOS screenshots and most apps write) converted.
|
||||
pub fn png() -> Option<Vec<u8>> {
|
||||
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
|
||||
autoreleasepool(|_| {
|
||||
let board = NSPasteboard::generalPasteboard();
|
||||
// SAFETY: the types are AppKit constants, valid for the process' lifetime.
|
||||
if let Some(png) = board.dataForType(unsafe { NSPasteboardTypePNG }) {
|
||||
return Some(png.to_vec());
|
||||
}
|
||||
let tiff = board.dataForType(unsafe { NSPasteboardTypeTIFF })?;
|
||||
let image = NSBitmapImageRep::imageRepWithData(&tiff)?;
|
||||
// SAFETY: an empty property dictionary is valid for every file type.
|
||||
let png =
|
||||
unsafe { image.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new()) }?;
|
||||
Some(png.to_vec())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn text() -> Option<String> {
|
||||
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
|
||||
autoreleasepool(|_| {
|
||||
@@ -448,6 +598,17 @@ mod imp {
|
||||
false
|
||||
}
|
||||
|
||||
pub fn has_image() -> bool {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).wait_is_image_available()
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn files() -> std::io::Result<Vec<PathBuf>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
@@ -521,4 +682,62 @@ mod tests {
|
||||
bytes.extend_from_slice(b"C:\\a\\b.txt\0C:\\c\0\0");
|
||||
assert_eq!(decode(&bytes), paths(&["C:\\a\\b.txt", "C:\\c"]));
|
||||
}
|
||||
|
||||
/// A `BITMAPINFOHEADER` DIB of `width` × `height` (positive: bottom-up).
|
||||
fn dib(width: i32, height: i32, bits: u16, compression: u32, rows: &[&[u8]]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
out.extend_from_slice(&40u32.to_le_bytes());
|
||||
out.extend_from_slice(&width.to_le_bytes());
|
||||
out.extend_from_slice(&height.to_le_bytes());
|
||||
out.extend_from_slice(&1u16.to_le_bytes());
|
||||
out.extend_from_slice(&bits.to_le_bytes());
|
||||
out.extend_from_slice(&compression.to_le_bytes());
|
||||
out.extend_from_slice(&[0u8; 20]);
|
||||
if compression == super::BI_BITFIELDS {
|
||||
for mask in [0x00ff_0000u32, 0x0000_ff00, 0x0000_00ff] {
|
||||
out.extend_from_slice(&mask.to_le_bytes());
|
||||
}
|
||||
}
|
||||
for row in rows {
|
||||
out.extend_from_slice(row);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn decode_png(png: &[u8]) -> (u32, u32, Vec<u8>) {
|
||||
let mut reader = png::Decoder::new(std::io::Cursor::new(png)).read_info().unwrap();
|
||||
let mut buf = vec![0; reader.output_buffer_size().unwrap()];
|
||||
let info = reader.next_frame(&mut buf).unwrap();
|
||||
buf.truncate(info.buffer_size());
|
||||
(info.width, info.height, buf)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bottom_up_24_bit_bitmap_becomes_an_upright_opaque_png() {
|
||||
// Rows are padded to 4 bytes; the first stored row is the bottom one.
|
||||
let bottom: &[u8] = &[255, 0, 0, 0, 255, 0, 0, 0];
|
||||
let top: &[u8] = &[0, 0, 255, 255, 255, 255, 0, 0];
|
||||
let png = super::dib_to_png(&dib(2, 2, 24, super::BI_RGB, &[bottom, top])).unwrap();
|
||||
let (w, h, rgba) = decode_png(&png);
|
||||
assert_eq!((w, h), (2, 2));
|
||||
assert_eq!(rgba, [255, 0, 0, 255, 255, 255, 255, 255, 0, 0, 255, 255, 0, 255, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_32_bit_bitmap_keeps_its_alpha_unless_none_was_written() {
|
||||
let row: &[u8] = &[10, 20, 30, 0, 40, 50, 60, 0];
|
||||
let (_, _, rgba) = decode_png(&super::dib_to_png(&dib(2, -1, 32, super::BI_BITFIELDS, &[row])).unwrap());
|
||||
assert_eq!(rgba, [30, 20, 10, 255, 60, 50, 40, 255]);
|
||||
let row: &[u8] = &[10, 20, 30, 128, 40, 50, 60, 0];
|
||||
let (_, _, rgba) = decode_png(&super::dib_to_png(&dib(2, -1, 32, super::BI_RGB, &[row])).unwrap());
|
||||
assert_eq!(rgba, [30, 20, 10, 128, 60, 50, 40, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_or_truncated_bitmaps_are_not_images() {
|
||||
let row: &[u8] = &[1, 2, 3, 4];
|
||||
assert!(super::dib_to_png(&dib(4, 1, 8, super::BI_RGB, &[row])).is_none());
|
||||
assert!(super::dib_to_png(&dib(2, 2, 24, super::BI_RGB, &[row])).is_none());
|
||||
assert!(super::dib_to_png(&[0; 10]).is_none());
|
||||
}
|
||||
}
|
||||
@@ -325,6 +325,20 @@ pub fn migrate(data: &Path, local: &Path) {
|
||||
if cfg!(target_os = "windows") && data != local {
|
||||
migrate_entries(data, local);
|
||||
}
|
||||
if cfg!(target_os = "windows") {
|
||||
relative_tool_shims(&local.join("tools"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrappers written before they named their tool relative to themselves hold its absolute
|
||||
/// path, which cmd.exe can't find through a non-ASCII user directory (#3338).
|
||||
fn relative_tool_shims(tools: &Path) {
|
||||
let Ok(entries) = fs::read_dir(tools) else { return };
|
||||
for dir in entries.flatten().map(|e| e.path()).filter(|p| p.is_dir()) {
|
||||
if let Err(error) = relocate_shims(&dir, &dir) {
|
||||
tracing::warn!(%error, ?dir, "cannot make the tool's wrappers relative");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn migrate_entries(data: &Path, local: &Path) {
|
||||
@@ -651,6 +665,22 @@ mod tests {
|
||||
fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_tool_wrappers_become_relative() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let tools = tmp.path().join("tools");
|
||||
let tool = tools.join("taplo");
|
||||
fs::create_dir_all(tool.join("bin")).unwrap();
|
||||
let shim = tool.join("bin/taplo.cmd");
|
||||
fs::write(&shim, format!("@echo off\r\n\"{}\\taplo.exe\" %*\r\n", tool.display())).unwrap();
|
||||
// A wrapper the user re-saved in another encoding is left alone.
|
||||
fs::create_dir_all(tools.join("other/bin")).unwrap();
|
||||
fs::write(tools.join("other/bin/x.cmd"), b"@echo off\r\n\"C:\\\xd5\xc5\" %*\r\n").unwrap();
|
||||
relative_tool_shims(&tools);
|
||||
assert_eq!(fs::read_to_string(&shim).unwrap(), "@echo off\r\n\"%~dp0..\\taplo.exe\" %*\r\n");
|
||||
relative_tool_shims(&tmp.path().join("missing"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrappers_accept_mixed_separators_without_rewriting_neighbor_paths() {
|
||||
let text = "@echo off\r\n\"C:\\old\\tools/demo\\payload.exe\" \"C:\\old\\tools/demo-other\\x\" %*\r\n";
|
||||
|
||||
@@ -296,39 +296,142 @@ impl crate::Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// Commands which only inspect/edit source or operate user-owned application state.
|
||||
/// New execution commands are denied until deliberately classified here.
|
||||
/// Commands allowed in Restricted Mode, by exact name: those which only inspect/edit source or
|
||||
/// operate user-owned application state. A new command is denied until deliberately listed here.
|
||||
pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
if [
|
||||
"fs_",
|
||||
"doc_",
|
||||
"syntax_",
|
||||
"search_",
|
||||
"nav_",
|
||||
"history_",
|
||||
"spell_",
|
||||
"analysis_",
|
||||
"structural_",
|
||||
"refactor_",
|
||||
"bytes_",
|
||||
"window_",
|
||||
"window_group_",
|
||||
"term_",
|
||||
"settings_",
|
||||
"project_trust_",
|
||||
// New Project writes only where the user chose and runs no code of an open project.
|
||||
"scaffold_",
|
||||
"ssh_",
|
||||
"git_credential",
|
||||
]
|
||||
.iter()
|
||||
.any(|p| cmd.starts_with(p))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
matches!(
|
||||
cmd,
|
||||
"app_info"
|
||||
"fs_compare_directories"
|
||||
| "fs_copy"
|
||||
| "fs_copy_merge"
|
||||
| "fs_create_dir"
|
||||
| "fs_create_file"
|
||||
| "fs_create_file_bytes"
|
||||
| "fs_delete"
|
||||
| "fs_entry_kind"
|
||||
| "fs_open_with_system"
|
||||
| "fs_probe"
|
||||
| "fs_read_dir"
|
||||
| "fs_read_image"
|
||||
| "fs_read_range"
|
||||
| "fs_read_text"
|
||||
| "fs_rename"
|
||||
| "fs_resolve_reference"
|
||||
| "fs_set_writable"
|
||||
| "doc_close"
|
||||
| "doc_edit"
|
||||
| "doc_folding"
|
||||
| "doc_highlights"
|
||||
| "doc_open"
|
||||
| "doc_open_untitled"
|
||||
| "doc_open_virtual"
|
||||
| "doc_outline"
|
||||
| "doc_python_facts"
|
||||
| "doc_save"
|
||||
| "doc_save_as"
|
||||
| "doc_save_all"
|
||||
| "doc_selection_ranges"
|
||||
| "doc_set_bom"
|
||||
| "doc_set_encoding"
|
||||
| "doc_set_line_ending"
|
||||
| "doc_snapshot"
|
||||
| "doc_sync_from_disk"
|
||||
| "doc_ui_mode"
|
||||
| "syntax_errors"
|
||||
| "syntax_expression_at"
|
||||
| "syntax_identifiers"
|
||||
| "syntax_identifiers_in_files"
|
||||
| "syntax_locals"
|
||||
| "syntax_node_at"
|
||||
| "syntax_structural_ranges"
|
||||
| "syntax_support"
|
||||
| "search_start"
|
||||
| "search_validate"
|
||||
| "nav_index_definitions"
|
||||
| "nav_inheritance"
|
||||
| "nav_resolve_module"
|
||||
| "history_content"
|
||||
| "history_list"
|
||||
| "history_list_dir"
|
||||
| "history_put_label"
|
||||
| "history_restore"
|
||||
| "spell_check"
|
||||
| "spell_suggest"
|
||||
| "analysis_locate_duplicates"
|
||||
| "structural_languages"
|
||||
| "structural_search"
|
||||
| "structural_validate"
|
||||
| "refactor_can_undo_file_move"
|
||||
| "refactor_file_move_edits"
|
||||
| "refactor_file_move_text_edits"
|
||||
| "refactor_move_files"
|
||||
| "refactor_undo_file_move"
|
||||
| "window_close_context"
|
||||
| "window_complete_launch"
|
||||
| "window_cycle"
|
||||
| "window_flash_taskbar"
|
||||
| "window_group_cancel_close"
|
||||
| "window_group_close"
|
||||
| "window_group_close_tabs"
|
||||
| "window_group_current"
|
||||
| "window_group_detach"
|
||||
| "window_group_merge"
|
||||
| "window_group_reorder"
|
||||
| "window_group_restore"
|
||||
| "window_group_select"
|
||||
| "window_is_fullscreen"
|
||||
| "window_new"
|
||||
| "window_open_comparison"
|
||||
| "window_open_deployment"
|
||||
| "window_open_diff"
|
||||
| "window_open_file_in_new_window"
|
||||
| "window_open_files"
|
||||
| "window_open_project"
|
||||
| "window_open_projects"
|
||||
| "window_open_remote"
|
||||
| "window_open_settings"
|
||||
| "window_set_titlebar_height"
|
||||
| "window_start_drag"
|
||||
| "window_take_launch"
|
||||
| "window_toggle_fullscreen"
|
||||
| "window_toggle_zoom"
|
||||
| "term_available_shells"
|
||||
| "term_default_shell"
|
||||
| "term_is_busy"
|
||||
| "term_kill"
|
||||
| "term_resize"
|
||||
| "term_spawn"
|
||||
| "term_store_image"
|
||||
| "term_write"
|
||||
| "settings_export"
|
||||
| "settings_get"
|
||||
| "settings_get_global"
|
||||
| "settings_import"
|
||||
| "settings_list_jetbrains_ides"
|
||||
| "settings_read_jetbrains"
|
||||
| "settings_set"
|
||||
| "project_trust_add_location"
|
||||
| "project_trust_list"
|
||||
| "project_trust_remove_location"
|
||||
| "project_trust_set"
|
||||
| "project_trust_status"
|
||||
// New Project writes only where the user chose and runs no code of an open project.
|
||||
| "scaffold_catalog"
|
||||
| "scaffold_create"
|
||||
| "scaffold_options"
|
||||
| "scaffold_requirements"
|
||||
| "ssh_askpass_answer"
|
||||
| "ssh_connected"
|
||||
| "ssh_disconnect"
|
||||
| "ssh_needs_secret"
|
||||
| "ssh_open_terminal"
|
||||
| "ssh_password_saved"
|
||||
| "ssh_set_secret"
|
||||
| "ssh_test"
|
||||
| "ssh_trust_host"
|
||||
| "git_credential_forget"
|
||||
| "git_credentials"
|
||||
| "app_info"
|
||||
| "app_build_info"
|
||||
| "app_cli_install"
|
||||
| "app_cli_uninstall"
|
||||
@@ -342,6 +445,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
| "clear_caches"
|
||||
| "clipboard_file_list"
|
||||
| "clipboard_has_files"
|
||||
| "clipboard_has_image"
|
||||
| "clipboard_image"
|
||||
| "clipboard_set_file_list"
|
||||
| "clipboard_write_text"
|
||||
@@ -572,6 +676,14 @@ mod tests {
|
||||
assert!(super::restricted_command_allowed("clipboard_write_text"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restricted_mode_denies_new_commands_whatever_their_name() {
|
||||
for cmd in ["fs_new_command", "term_new_command", "ssh_new_command", "settings_new_command", "git_credential_x"]
|
||||
{
|
||||
assert!(!super::restricted_command_allowed(cmd), "{cmd} is allowed without being listed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_project_decisions_are_kept_on_this_machine() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -46,6 +46,7 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
|
||||
"clear_caches",
|
||||
"clipboard_file_list",
|
||||
"clipboard_has_files",
|
||||
"clipboard_has_image",
|
||||
"clipboard_image",
|
||||
"clipboard_set_file_list",
|
||||
"clipboard_write_text",
|
||||
|
||||
@@ -207,3 +207,22 @@ async fn change_commit_branch_stash_and_merge_a_conflict() {
|
||||
assert!(f.status().await.is_empty());
|
||||
assert_eq!(std::fs::read_to_string(&lib_path).unwrap(), resolved);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn checkout_reports_a_branch_held_by_another_worktree() {
|
||||
let f = Flow::new("rust-app").await;
|
||||
let linked = f._tmp.path().join("linked");
|
||||
git(&f.root, &["worktree", "add", "-q", "-b", "topic", linked.to_str().unwrap()]);
|
||||
|
||||
let outcome = ops::vcs::vcs_checkout(&f.host, WINDOW, None, "topic".into(), false, None).await.unwrap();
|
||||
assert_eq!(
|
||||
outcome,
|
||||
ide_vcs::CheckoutOutcome::CheckedOutInWorktree {
|
||||
branch: "topic".into(),
|
||||
path: dunce::canonicalize(&linked).unwrap()
|
||||
}
|
||||
);
|
||||
// Nothing changed: the project is still on main.
|
||||
let branches = ops::vcs::vcs_branches(&f.host, WINDOW, None).await.unwrap();
|
||||
assert!(branches.iter().any(|b| b.name == "main" && b.current), "{branches:?}");
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
|
||||
let Some(src) = read(&dir.join("build.zig")) else { return };
|
||||
let src = code_only(&src);
|
||||
out.push(config(BUILD_ID, "zig build", "zig", "zig", &["build"]));
|
||||
let roots = test_roots(&src);
|
||||
for step in steps(&src) {
|
||||
// `install` is what plain `zig build` runs.
|
||||
if step == "install" || step == "uninstall" {
|
||||
@@ -20,6 +21,9 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
|
||||
let mut c = config(format!("zig:{step}"), format!("zig build {step}"), "zig", "zig", &["build", &step]);
|
||||
if step == "test" || step.starts_with("test-") || step.starts_with("test_") {
|
||||
c = c.test();
|
||||
if let Some((_, root)) = roots.iter().find(|(name, _)| *name == step) {
|
||||
c.extras.params.insert("testRoot".into(), root.clone());
|
||||
}
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
@@ -161,6 +165,137 @@ fn executables(src: &str) -> Vec<Executable> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The call's argument text: from just after its `(` to the matching `)`.
|
||||
fn call_body(src: &str, start: usize) -> &str {
|
||||
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
|
||||
for (i, c) in src[start..].char_indices() {
|
||||
if in_string {
|
||||
match c {
|
||||
_ if escaped => escaped = false,
|
||||
'\\' => escaped = true,
|
||||
'"' => in_string = false,
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'"' => in_string = true,
|
||||
'(' | '{' | '[' => depth += 1,
|
||||
')' | '}' | ']' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return &src[start..start + i];
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
src
|
||||
}
|
||||
|
||||
/// The first `.root_source_file = <receiver>.path("…")` in `body`.
|
||||
fn root_source_file(body: &str) -> Option<String> {
|
||||
for (i, _) in body.match_indices(".root_source_file") {
|
||||
let Some(v) = body[i + ".root_source_file".len()..].trim_start().strip_prefix('=') else { continue };
|
||||
let v = v.trim_start();
|
||||
if let Some(call) = v.find(".path(")
|
||||
&& v[..call].chars().all(|c| c.is_alphanumeric() || c == '_')
|
||||
{
|
||||
return string_at(&v[call + ".path(".len()..]);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The identifier assigned just before `at`: `const mod = b.addModule(…` → `mod`.
|
||||
fn assigned_var(src: &str, at: usize) -> Option<&str> {
|
||||
let before = src[..at].trim_end();
|
||||
let before = before.strip_suffix('.')?.trim_end();
|
||||
// Drop the receiver (`b`) that sits between the `=` and the call.
|
||||
let receiver =
|
||||
before.char_indices().rev().take_while(|(_, c)| c.is_alphanumeric() || *c == '_').last().map(|(i, _)| i)?;
|
||||
let before = before[..receiver].trim_end();
|
||||
let before = before.strip_suffix('=')?.trim_end();
|
||||
let start =
|
||||
before.char_indices().rev().take_while(|(_, c)| c.is_alphanumeric() || *c == '_').last().map(|(i, _)| i)?;
|
||||
Some(&before[start..])
|
||||
}
|
||||
|
||||
/// The test root behind each test-named step (`zig build <step>`): the step's `dependOn` runs
|
||||
/// an `addTest` artifact — a variable (`const tests = b.addTest(…)`) or an inline call — whose
|
||||
/// module's `root_source_file` this resolves (through `addModule`/`createModule` variables).
|
||||
/// `zig build` forwards no args to the test binary, so rerunning a single failed test goes
|
||||
/// through a standalone `zig test <root> --test-filter …` on the step's own test module.
|
||||
fn test_roots(src: &str) -> Vec<(String, String)> {
|
||||
let mut modules: Vec<(String, String)> = Vec::new();
|
||||
for key in ["addModule(", "createModule("] {
|
||||
for (i, _) in src.match_indices(key) {
|
||||
let Some(root) = root_source_file(call_body(src, i + key.len())) else { continue };
|
||||
if let Some(var) = assigned_var(src, i)
|
||||
&& !modules.iter().any(|(m, _)| *m == var)
|
||||
{
|
||||
modules.push((var.to_owned(), root));
|
||||
}
|
||||
}
|
||||
}
|
||||
let module_root = |body: &str| -> Option<String> {
|
||||
root_source_file(body).or_else(|| {
|
||||
let at = body.find(".root_module")?;
|
||||
let v = body[at + ".root_module".len()..].trim_start().strip_prefix('=')?.trim_start();
|
||||
let var: String = v.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
|
||||
modules.iter().find(|(m, _)| *m == var).map(|(_, root)| root.clone())
|
||||
})
|
||||
};
|
||||
let mut tests: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices("addTest(") {
|
||||
let Some(root) = module_root(call_body(src, i + "addTest(".len())) else { continue };
|
||||
if let Some(var) = assigned_var(src, i)
|
||||
&& !tests.iter().any(|(v, _)| *v == var)
|
||||
{
|
||||
tests.push((var.to_owned(), root));
|
||||
}
|
||||
}
|
||||
let mut steps: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".step(\"") {
|
||||
let Some(name) = string_at(&src[i + ".step(".len()..]) else { continue };
|
||||
// The match includes the dot, so the assignment ends one character earlier.
|
||||
if let Some(var) = assigned_var(src, i + 1) {
|
||||
steps.push((var.to_owned(), name));
|
||||
}
|
||||
}
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".dependOn(&") {
|
||||
let Some(step) = receiver_var(src, i + 1) else { continue };
|
||||
let Some((_, name)) = steps.iter().find(|(v, _)| v == step) else { continue };
|
||||
let after = &src[i + ".dependOn(&".len()..];
|
||||
let artifact = if let Some(at) = after.find("addRunArtifact(") {
|
||||
let v = &after[at + "addRunArtifact(".len()..];
|
||||
let var: String = v.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
|
||||
tests.iter().find(|(v, _)| *v == var).map(|(_, root)| root.clone())
|
||||
} else if let Some(at) = after.find("addTest(") {
|
||||
module_root(call_body(after, at + "addTest(".len()))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(root) = artifact
|
||||
&& name.starts_with("test")
|
||||
&& !out.iter().any(|(n, _)| n == name)
|
||||
{
|
||||
out.push((name.clone(), root));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The identifier a method is called on just before `at`: `test_step.dependOn(…` → `test_step`.
|
||||
fn receiver_var(src: &str, at: usize) -> Option<&str> {
|
||||
let before = src[..at].trim_end();
|
||||
let before = before.strip_suffix('.')?;
|
||||
let start =
|
||||
before.char_indices().rev().take_while(|(_, c)| c.is_alphanumeric() || *c == '_').last().map(|(i, _)| i)?;
|
||||
Some(&before[start..])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -190,7 +325,9 @@ pub fn build(b: *std.Build) void {
|
||||
}) });
|
||||
_ = tool;
|
||||
const run_step = b.step("run", "Run the app");
|
||||
const tests = b.addTest(.{ .root_module = mod });
|
||||
const test_step = b.step("test", "Run tests");
|
||||
test_step.dependOn(&b.addRunArtifact(tests).step);
|
||||
const docs = b.step("docs", "Generate docs // not a comment");
|
||||
_ = .{ run_step, test_step, docs };
|
||||
}
|
||||
@@ -228,5 +365,39 @@ pub fn build(b: *std.Build) void {
|
||||
assert_eq!(app.extras.before_launch[0].kind, "run");
|
||||
assert_eq!(app.extras.before_launch[0].target, BUILD_ID);
|
||||
assert_eq!(app.extras.params.get("source").map(String::as_str), Some("src/main.zig"));
|
||||
assert_eq!(test.extras.params.get("testRoot").map(String::as_str), Some("src/root.zig"));
|
||||
}
|
||||
|
||||
const TEST_ROOTS: &str = r#"const std = @import("std");
|
||||
|
||||
pub fn build(b: *std.Build) void {
|
||||
const tally = b.addModule("tally", .{ .root_source_file = b.path("src/tally.zig") });
|
||||
const unit = b.addTest(.{ .root_module = tally });
|
||||
const test_step = b.step("test", "Run the unit tests");
|
||||
test_step.dependOn(&b.addRunArtifact(unit).step);
|
||||
const failing = b.addTest(.{ .root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/failing.zig"),
|
||||
}) });
|
||||
const test_failing_step = b.step("test-failing", "Run the failing tests");
|
||||
test_failing_step.dependOn(&b.addRunArtifact(failing).step);
|
||||
const direct = b.addTest(.{ .root_source_file = b.path("src/direct.zig") });
|
||||
const test_direct_step = b.step("test-direct", "Run the direct tests");
|
||||
test_direct_step.dependOn(&b.addRunArtifact(direct).step);
|
||||
const run_step = b.step("run", "Run the app");
|
||||
run_step.dependOn(&b.addRunArtifact(unit).step);
|
||||
}
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn test_roots_come_from_the_step_s_own_artifact() {
|
||||
let src = code_only(TEST_ROOTS);
|
||||
assert_eq!(
|
||||
test_roots(&src),
|
||||
[
|
||||
("test".to_owned(), "src/tally.zig".to_owned()),
|
||||
("test-failing".to_owned(), "src/failing.zig".to_owned()),
|
||||
("test-direct".to_owned(), "src/direct.zig".to_owned()),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -331,8 +331,8 @@ pub fn env_wrapper(bin_dir: &Path, command: &str, target: &Path, env: &[(&str, &
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let link = bin_dir.join(format!("{command}.cmd"));
|
||||
let vars: String = env.iter().map(|(k, v)| format!("set \"{k}={}\"\r\n", v.display())).collect();
|
||||
fs::write(&link, format!("@echo off\r\nsetlocal\r\n{vars}\"{}\" %*\r\n", target.display()))?;
|
||||
let vars: String = env.iter().map(|(k, v)| format!("set \"{k}={}\"\r\n", cmd_path(bin_dir, v))).collect();
|
||||
fs::write(&link, format!("@echo off\r\nsetlocal\r\n{vars}\"{}\" %*\r\n", cmd_path(bin_dir, target)))?;
|
||||
Ok(link)
|
||||
}
|
||||
}
|
||||
@@ -357,11 +357,25 @@ pub fn link_executable(bin_dir: &Path, command: &str, target: &Path) -> IdeResul
|
||||
{
|
||||
let link = bin_dir.join(format!("{command}.cmd"));
|
||||
let runner = if target.extension().is_some_and(|e| e == "js") { "node " } else { "" };
|
||||
fs::write(&link, format!("@echo off\r\n{runner}\"{}\" %*\r\n", target.display()))?;
|
||||
fs::write(&link, format!("@echo off\r\n{runner}\"{}\" %*\r\n", cmd_path(bin_dir, target)))?;
|
||||
Ok(link)
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` as a `.cmd` shim in `bin_dir` names it: relative to the shim (`%~dp0..\…`) when it
|
||||
/// is in the tool's own directory. cmd.exe reads a batch file in the console's code page, so
|
||||
/// an absolute path through a non-ASCII user directory, written as UTF-8, isn't found (#3338).
|
||||
#[cfg_attr(unix, allow(dead_code))]
|
||||
fn cmd_path(bin_dir: &Path, path: &Path) -> String {
|
||||
match bin_dir.parent().and_then(|tool| path.strip_prefix(tool).ok()) {
|
||||
Some(rest) => {
|
||||
let rest: Vec<_> = rest.components().map(|c| c.as_os_str().to_string_lossy()).collect();
|
||||
format!("%~dp0..\\{}", rest.join("\\"))
|
||||
}
|
||||
None => path.display().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -743,6 +757,17 @@ mod tests {
|
||||
assert!(found.ends_with("server/com.microsoft.java.debug.plugin-0.53.2.jar"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_shims_name_the_tool_relative_to_themselves() {
|
||||
let tool = Path::new("/Users/张三/AppData/Local/ai.l0ng.openidea/tools/taplo");
|
||||
let bin = tool.join("bin");
|
||||
assert_eq!(cmd_path(&bin, &tool.join("taplo.exe")), "%~dp0..\\taplo.exe");
|
||||
assert_eq!(cmd_path(&bin, &tool.join("gems/bin/solargraph")), "%~dp0..\\gems\\bin\\solargraph");
|
||||
// Outside the tool's directory (a system SDK) stays absolute.
|
||||
let sdk = Path::new("/usr/local/share/dotnet");
|
||||
assert_eq!(cmd_path(&bin, sdk), sdk.display().to_string());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn wrapper_runs_target() {
|
||||
|
||||
@@ -496,6 +496,9 @@ pub struct CheckoutOptions {
|
||||
/// Required when checking out a remote branch whose local namesake is ahead of it.
|
||||
#[serde(default)]
|
||||
pub diverged: Option<DivergedLocal>,
|
||||
/// Check the branch out even though another worktree has it checked out.
|
||||
#[serde(default)]
|
||||
pub ignore_other_worktrees: bool,
|
||||
}
|
||||
|
||||
/// Result of [`Repo::checkout_with`]; the non-`Done` variants other than `Conflicts`
|
||||
@@ -522,6 +525,12 @@ pub enum CheckoutOutcome {
|
||||
Conflicts {
|
||||
files: Vec<String>,
|
||||
},
|
||||
/// Git refused: `branch` is checked out in the linked worktree at `path`. Nothing
|
||||
/// changed; the branch can be worked on there.
|
||||
CheckedOutInWorktree {
|
||||
branch: String,
|
||||
path: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
/// HEAD before and after a history rewrite, for its Undo.
|
||||
|
||||
@@ -765,6 +765,18 @@ fn overwritten_untracked(stderr: &str) -> Option<Vec<String>> {
|
||||
listed_files(stderr, "untracked working tree files would be")
|
||||
}
|
||||
|
||||
/// The branch git refused to check out or update because another worktree has it, from
|
||||
/// its error message: a switch says `'<branch>' is already used by worktree at '<path>'`,
|
||||
/// a forced update says `cannot force update the branch '<branch>' used by worktree at
|
||||
/// '<path>'`; git before 2.42 says `'<branch>' is already checked out at '<path>'`.
|
||||
fn branch_of_other_worktree(stderr: &str) -> Option<(String, String)> {
|
||||
const MARKERS: [&str; 3] =
|
||||
["' is already used by worktree at '", "' used by worktree at '", "' is already checked out at '"];
|
||||
let (before, path) = stderr.lines().find_map(|l| MARKERS.iter().find_map(|m| l.split_once(m)))?;
|
||||
let branch = before.rsplit('\'').next()?.to_string();
|
||||
Some((branch, path.strip_suffix('\'').unwrap_or(path).to_string()))
|
||||
}
|
||||
|
||||
fn listed_files(stderr: &str, header: &str) -> Option<Vec<String>> {
|
||||
let mut lines = stderr.lines().skip_while(|l| !l.contains(header));
|
||||
lines.next()?;
|
||||
@@ -805,12 +817,18 @@ pub(crate) fn checkout_with(
|
||||
if options.mode == CheckoutMode::Force {
|
||||
args.push("--discard-changes".into());
|
||||
}
|
||||
if options.ignore_other_worktrees {
|
||||
args.push("--ignore-other-worktrees".into());
|
||||
}
|
||||
let argv: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
let out = cli::run_raw(r.root(), &argv, None)?;
|
||||
if out.code == Some(0) {
|
||||
return Ok(CheckoutOutcome::Done);
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
if let Some((branch, path)) = branch_of_other_worktree(&stderr) {
|
||||
return Ok(CheckoutOutcome::CheckedOutInWorktree { branch, path: path.into() });
|
||||
}
|
||||
if let Some(files) = overwritten_untracked(&stderr) {
|
||||
return Ok(CheckoutOutcome::UntrackedFiles { files });
|
||||
}
|
||||
@@ -893,7 +911,14 @@ pub(crate) fn create_branch(
|
||||
args.extend(["--", name]);
|
||||
}
|
||||
args.extend(start);
|
||||
run(r.root(), &args, None).map(|_| ())
|
||||
let out = cli::run_raw(r.root(), &args, None)?;
|
||||
if out.code == Some(0) {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some((branch, path)) = branch_of_other_worktree(&String::from_utf8_lossy(&out.stderr)) {
|
||||
return Err(IdeError::invalid(format!("branch '{branch}' is already checked out in worktree at '{path}'")));
|
||||
}
|
||||
Err(cli::failure(&args, &out.stderr, &out.stdout, out.code))
|
||||
}
|
||||
|
||||
/// Whether `start` is a remote-tracking branch with another name than the new branch
|
||||
@@ -1479,7 +1504,22 @@ fn decode_diff(bytes: &[u8], encoding: TextEncoding) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::append_revision;
|
||||
use super::{append_revision, branch_of_other_worktree};
|
||||
|
||||
#[test]
|
||||
fn the_worktree_holding_a_branch_is_read_from_each_git_wording() {
|
||||
let held = |b: &str, p: &str| Some((b.to_string(), p.to_string()));
|
||||
assert_eq!(
|
||||
branch_of_other_worktree("fatal: 'topic' is already used by worktree at '/w/t'\n"),
|
||||
held("topic", "/w/t")
|
||||
);
|
||||
assert_eq!(
|
||||
branch_of_other_worktree("fatal: cannot force update the branch 'topic' used by worktree at '/w/t'"),
|
||||
held("topic", "/w/t")
|
||||
);
|
||||
assert_eq!(branch_of_other_worktree("fatal: 'a/b' is already checked out at '/w/t'"), held("a/b", "/w/t"));
|
||||
assert_eq!(branch_of_other_worktree("fatal: invalid reference: x"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_revision_is_appended_once_keeping_the_list() {
|
||||
|
||||
@@ -1070,7 +1070,7 @@ fn smart_and_force_checkout_with_local_changes_in_the_way() {
|
||||
fx.commit_all("other edit");
|
||||
fx.git(&["checkout", "-q", "main"]);
|
||||
let repo = fx.repo();
|
||||
let opts = |mode| CheckoutOptions { mode, diverged: None };
|
||||
let opts = |mode| CheckoutOptions { mode, ..Default::default() };
|
||||
|
||||
// A non-conflicting local edit to a file the switch rewrites.
|
||||
fx.write("f.txt", "1\n2\n3\n4\nlocal\n");
|
||||
@@ -1110,6 +1110,50 @@ fn smart_and_force_checkout_with_local_changes_in_the_way() {
|
||||
assert_eq!(fx.read("untouched.txt"), "new\n", "untracked files survive");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkout_of_a_branch_held_by_another_worktree_reports_it_and_changes_nothing() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("f.txt", "1\n");
|
||||
fx.commit_all("base");
|
||||
let linked = fx._tmp.path().join("linked");
|
||||
fx.git(&["worktree", "add", "-q", "-b", "topic", linked.to_str().unwrap()]);
|
||||
let repo = fx.repo();
|
||||
let none = CheckoutOptions::default();
|
||||
let linked_path = std::fs::canonicalize(&linked).unwrap();
|
||||
|
||||
// From the main worktree, the branch the linked worktree has checked out.
|
||||
let outcome = repo.checkout_with("topic", false, &none).unwrap();
|
||||
assert_eq!(outcome, CheckoutOutcome::CheckedOutInWorktree { branch: "topic".into(), path: linked_path.clone() });
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"), "nothing changed");
|
||||
|
||||
// With local changes in the way too: reported before any Smart Checkout stash.
|
||||
fx.write("f.txt", "changed\n");
|
||||
let smart = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() };
|
||||
let outcome = repo.checkout_with("topic", false, &smart).unwrap();
|
||||
assert_eq!(outcome, CheckoutOutcome::CheckedOutInWorktree { branch: "topic".into(), path: linked_path.clone() });
|
||||
assert_eq!(fx.read("f.txt"), "changed\n", "local changes untouched");
|
||||
assert!(repo.stashes().unwrap().is_empty());
|
||||
fx.git(&["reset", "-q", "--hard"]);
|
||||
|
||||
// The same refusal from the linked worktree, for the main worktree's branch.
|
||||
let linked_repo = Repo::discover(&linked).unwrap().unwrap();
|
||||
linked_repo.set_execution_allowed(true);
|
||||
let outcome = linked_repo.checkout_with("main", false, &none).unwrap();
|
||||
let main_path = std::fs::canonicalize(&fx.dir).unwrap();
|
||||
assert_eq!(outcome, CheckoutOutcome::CheckedOutInWorktree { branch: "main".into(), path: main_path });
|
||||
assert_eq!(linked_repo.branch_info().unwrap().head.as_deref(), Some("topic"));
|
||||
|
||||
// Overwriting such a branch (New Branch with Checkout) names the worktree, not raw stderr.
|
||||
let error = repo.create_branch_with_overwrite("topic", Some("main"), true, true).unwrap_err();
|
||||
assert!(error.message.contains("branch 'topic' is already checked out in worktree"), "{error}");
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
|
||||
|
||||
// Checkout Anyway: both worktrees then have the branch.
|
||||
let anyway = CheckoutOptions { ignore_other_worktrees: true, ..Default::default() };
|
||||
assert_eq!(repo.checkout_with("topic", false, &anyway).unwrap(), CheckoutOutcome::Done);
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("topic"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkout_remote_branch_with_existing_local_namesake() {
|
||||
let (fx, bare) = with_remote();
|
||||
@@ -1939,7 +1983,7 @@ fn smart_checkout_keeps_staged_changes_staged() {
|
||||
fx.write("f.txt", "1\n2\n3\n4\nlocal\n");
|
||||
fx.write("s.txt", "staged\n");
|
||||
fx.git(&["add", "s.txt"]);
|
||||
let opts = CheckoutOptions { mode: CheckoutMode::Smart, diverged: None };
|
||||
let opts = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() };
|
||||
assert_eq!(repo.checkout_with("other", false, &opts).unwrap(), CheckoutOutcome::Done);
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("other"));
|
||||
assert_eq!(fx.read("f.txt"), "1\nother\n3\n4\nlocal\n");
|
||||
@@ -1960,7 +2004,7 @@ fn checkout_reports_untracked_files_it_would_overwrite() {
|
||||
fx.write("dir/new.txt", "mine\n");
|
||||
let repo = fx.repo();
|
||||
for mode in [CheckoutMode::Normal, CheckoutMode::Smart] {
|
||||
let opts = CheckoutOptions { mode, diverged: None };
|
||||
let opts = CheckoutOptions { mode, ..Default::default() };
|
||||
let outcome = repo.checkout_with("other", false, &opts).unwrap();
|
||||
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()] });
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
|
||||
|
||||
@@ -197,5 +197,5 @@ You don't write anything special for remote development. In a remote window, `sr
|
||||
1. Put the logic in the owning crate; convert errors to `IdeError` at its edge; use IPC coordinates.
|
||||
2. Add the shared implementation to `ide-host::ops::<domain>` if it touches a project; register it with the remote dispatcher if remote windows need it.
|
||||
3. Add the `#[tauri::command] #[specta::specta]` adapter in `src-tauri/src/commands/<domain>.rs` and list it in `collect_commands!`.
|
||||
4. If it executes anything, leave it out of the restricted-mode allowlist (it is denied in untrusted projects by default).
|
||||
5. `pnpm gen:bindings`, then call it with `call(commands.yourCommand(...))`.
|
||||
4. Decide its trust class: list it by exact name in `restricted_command_allowed` (also in Restricted Mode) or `projectless_command_allowed` (also with no project open), or leave it out to require a trusted project. There are no name prefixes; if it executes anything, leave it out.
|
||||
5. `pnpm gen:bindings`, then call it with `call(commands.yourCommand(...))`. It also rewrites `src-tauri/tests/commands.snap`; check that the new line shows the trust class and placement you meant.
|
||||
@@ -31,7 +31,7 @@ Opening a project folder can run code that the project controls: language server
|
||||
- When a project that hasn't been decided opens, the **Trust and Open Project?** dialog offers **Trust Project**, **Preview in Restricted Mode** and **Don't Open**. Decisions and trusted locations are managed on Settings' **Project Trust** page (group **Security**), and **Revoke Trust** is an action.
|
||||
- Trust is user-owned state (`crates/ide-host/src/trust.rs`). **Project settings never grant trust.**
|
||||
- Enforcement is in the backend, not the UI: every IPC command passes `Host::authorize_command` in the Tauri invoke handler (`src-tauri/src/lib.rs`) before it runs. In an untrusted project only commands on an explicit allowlist (`restricted_command_allowed`) run: reading and editing files and documents, syntax, search, navigation, local history, spelling, analysis, refactoring, settings and similar.
|
||||
- The allowlist is a default-deny list: **a new command that executes anything is denied in restricted mode until you deliberately classify it there.** Don't add an execution command to the allowlist to make a feature "work" in restricted mode.
|
||||
- The allowlist is a default-deny list of exact names: **a new command that executes anything is denied in restricted mode until you deliberately classify it there.** Don't add an execution command to the allowlist to make a feature "work" in restricted mode. `src-tauri/tests/commands.snap` lists every command's trust class, so a change shows up in review.
|
||||
- Below the command layer, language servers don't start (`LspManager` execution switch), and git runs with execution disabled and without the project's `git` executable setting until the project is trusted. Project plugins (`.openidea/plugins/`) load only for trusted projects.
|
||||
- In a remote window the desktop checks the remote project's trust before forwarding a command, and `openidea-server` authorizes every `invoke` again.
|
||||
|
||||
|
||||
@@ -7,12 +7,12 @@ Smoke tests check each language end to end with the real tools the IDE uses: lan
|
||||
|
||||
They are not part of `cargo nextest run` or `pnpm test`, because they need the tools installed. CI runs them in the **Language smoke** workflow with pinned versions.
|
||||
|
||||
| Suite | What it checks | Languages |
|
||||
| ----------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------- |
|
||||
| `crates/ide-host/tests/language_smoke.rs` | Code intelligence through the `ops` the app's commands call | typescript, python, rust, go, java, kotlin, php |
|
||||
| `crates/ide-host/tests/project_smoke.rs` | Opening a fixture with its build tool and SDK | `maven_sync`, `jdk`, `gradle_sync`, `python_venv` |
|
||||
| `smoke/run.test.ts` | Run and test configurations through the run store and a real `openidea-server` | typescript, python, rust, go, java, kotlin, php |
|
||||
| `smoke/debug.test.ts` | Debugging the entry point with the debugger the IDE installs | typescript, python, rust, go, java, kotlin, c, cpp, php |
|
||||
| Suite | What it checks | Languages |
|
||||
| ----------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------ |
|
||||
| `crates/ide-host/tests/language_smoke.rs` | Code intelligence through the `ops` the app's commands call | typescript, python, rust, go, java, kotlin, php |
|
||||
| `crates/ide-host/tests/project_smoke.rs` | Opening a fixture with its build tool and SDK | `maven_sync`, `jdk`, `gradle_sync`, `python_venv` |
|
||||
| `smoke/run.test.ts` | Run and test configurations through the run store and a real `openidea-server` | typescript, python, rust, go, java, kotlin, php, zig |
|
||||
| `smoke/debug.test.ts` | Debugging the entry point with the debugger the IDE installs | typescript, python, rust, go, java, kotlin, c, cpp, zig, php |
|
||||
|
||||
## Language smoke
|
||||
|
||||
|
||||
@@ -197,5 +197,5 @@ onIdeEvent("projectTrustChanged", (e) => {
|
||||
1. 逻辑放在所属的 crate 里;在其边界把错误转成 `IdeError`;使用 IPC 坐标。
|
||||
2. 如果涉及项目,把共享实现加到 `ide-host::ops::<domain>`;远程窗口需要的话,注册到远程 dispatcher。
|
||||
3. 在 `src-tauri/src/commands/<domain>.rs` 添加 `#[tauri::command] #[specta::specta]` 适配函数,并加入 `collect_commands!`。
|
||||
4. 如果它会执行任何东西,不要把它加进受限模式白名单(未受信任的项目里默认拒绝)。
|
||||
5. 运行 `pnpm gen:bindings`,然后用 `call(commands.yourCommand(...))` 调用。
|
||||
4. 决定它的信任级别:在 `restricted_command_allowed`(受限模式下也可运行)或 `projectless_command_allowed`(未打开项目时也可运行)中按完整名称列出它,或者不列出,即需要受信任的项目。没有名称前缀规则;会执行任何东西的命令不要列出。
|
||||
5. 运行 `pnpm gen:bindings`,然后用 `call(commands.yourCommand(...))` 调用。它也会重写 `src-tauri/tests/commands.snap`;检查新增的那一行是否是你想要的信任级别和运行位置。
|
||||
@@ -28,7 +28,7 @@ description: "如何报告漏洞,以及贡献者需要维护的安全模型:
|
||||
- 打开一个尚未做过决定的项目时,会弹出 **信任并打开项目?** 对话框,提供 **信任项目**、**以受限模式预览** 和 **不打开**。已有决定和受信任的位置在设置的 **项目信任** 页面(**安全** 分组)里管理,**撤销信任** 是一个 action。
|
||||
- 信任是用户自己的状态(`crates/ide-host/src/trust.rs`)。**项目设置永远不能授予信任。**
|
||||
- 拦截在后端而不是 UI:每个 IPC 命令执行前,都要在 Tauri 的 invoke handler(`src-tauri/src/lib.rs`)里经过 `Host::authorize_command`。未受信任的项目里,只有显式白名单(`restricted_command_allowed`)中的命令能运行:读写文件和文档、语法、搜索、导航、本地历史、拼写、分析、重构、设置等。
|
||||
- 这份白名单是默认拒绝的:**新增的任何会执行东西的命令,在你有意识地把它归类之前,受限模式下一律拒绝。** 不要为了让某个功能在受限模式下“能用”就把执行类命令加进白名单。
|
||||
- 这份白名单按完整名称列出,默认拒绝:**新增的任何会执行东西的命令,在你有意识地把它归类之前,受限模式下一律拒绝。** 不要为了让某个功能在受限模式下“能用”就把执行类命令加进白名单。`src-tauri/tests/commands.snap` 列出每个命令的信任级别,改动会出现在审查的 diff 里。
|
||||
- 在命令层之下,项目受信任之前语言服务器不会启动(`LspManager` 的执行开关),git 以禁止执行的方式运行,也不使用项目里配置的 `git` 可执行文件。项目插件(`.openidea/plugins/`)只在受信任的项目中加载。
|
||||
- 远程窗口中,桌面端在转发命令前会先确认远程项目是否受信任,`openidea-server` 对每个 `invoke` 还会再校验一次。
|
||||
|
||||
|
||||
@@ -7,12 +7,12 @@ description: "在 fixtures 示例项目上,用真实语言服务器跑语言
|
||||
|
||||
由于需要安装这些工具,冒烟测试不包含在 `cargo nextest run` 或 `pnpm test` 中。CI 在 **Language smoke** 工作流里用固定版本运行它们。
|
||||
|
||||
| 套件 | 检查内容 | 语言 |
|
||||
| ----------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------- |
|
||||
| `crates/ide-host/tests/language_smoke.rs` | 经由应用命令所调用的 `ops` 检查代码智能 | typescript、python、rust、go、java、kotlin、php |
|
||||
| `crates/ide-host/tests/project_smoke.rs` | 用构建工具和 SDK 打开示例项目 | `maven_sync`、`jdk`、`gradle_sync`、`python_venv` |
|
||||
| `smoke/run.test.ts` | 通过 run store 和真实的 `openidea-server` 执行运行与测试配置 | typescript、python、rust、go、java、kotlin、php |
|
||||
| `smoke/debug.test.ts` | 用 IDE 安装的调试器调试入口点 | typescript、python、rust、go、java、kotlin、c、cpp、php |
|
||||
| 套件 | 检查内容 | 语言 |
|
||||
| ----------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
|
||||
| `crates/ide-host/tests/language_smoke.rs` | 经由应用命令所调用的 `ops` 检查代码智能 | typescript、python、rust、go、java、kotlin、php |
|
||||
| `crates/ide-host/tests/project_smoke.rs` | 用构建工具和 SDK 打开示例项目 | `maven_sync`、`jdk`、`gradle_sync`、`python_venv` |
|
||||
| `smoke/run.test.ts` | 通过 run store 和真实的 `openidea-server` 执行运行与测试配置 | typescript、python、rust、go、java、kotlin、php、zig |
|
||||
| `smoke/debug.test.ts` | 用 IDE 安装的调试器调试入口点 | typescript、python、rust、go、java、kotlin、c、cpp、zig、php |
|
||||
|
||||
## 语言冒烟测试
|
||||
|
||||
|
||||
@@ -372,20 +372,25 @@ test("keeps chat history readable and selections free of timestamps and status l
|
||||
expect(narrow.reply).toBeLessThanOrEqual((narrow.width - narrow.padding) * 0.96);
|
||||
});
|
||||
|
||||
test("fits conversation stream, composer, question card and user bubbles to window width when enabled", async ({
|
||||
test("fits conversation stream, composer, question card and off-screen rows live from Settings without restarting", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1800, height: 1000 });
|
||||
await page.setViewportSize({ width: 1800, height: 900 });
|
||||
await openReply(page, "Initial reply");
|
||||
await page.evaluate(async (task) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const store = await import(storePath);
|
||||
const filler = Array.from({ length: 8 }, (_, i) => ({
|
||||
type: "agent" as const,
|
||||
text: `Earlier paragraph ${i + 1}: ` + "wrapped words across the column ".repeat(35),
|
||||
}));
|
||||
store.useAgents.setState({
|
||||
tasks: new Map([[task.id, { ...task, status: "needsInput" as const }]]),
|
||||
entries: new Map([
|
||||
[
|
||||
task.id,
|
||||
[
|
||||
...filler,
|
||||
{
|
||||
type: "user",
|
||||
text: "Long prompt ".repeat(40),
|
||||
@@ -419,11 +424,15 @@ test("fits conversation stream, composer, question card and user bubbles to wind
|
||||
|
||||
const stream = page.locator("[class*='_stream_']:visible");
|
||||
await expect(page.getByRole("form", { name: "Choose layout" })).toBeVisible();
|
||||
await expect(stream.locator("[data-measured]").first()).toBeAttached();
|
||||
|
||||
const measure = () =>
|
||||
stream.evaluate((root) => {
|
||||
const conversation = root.closest<HTMLElement>("[class*='_conversation_']")!;
|
||||
const column = root.querySelector<HTMLElement>("[class*='_agentMessage_']")!.getBoundingClientRect();
|
||||
const rows = [...root.querySelectorAll<HTMLElement>("[class*='_conversationRow_']")];
|
||||
const column = [...root.querySelectorAll<HTMLElement>("[class*='_agentMessage_']")]
|
||||
.at(-1)!
|
||||
.getBoundingClientRect();
|
||||
const bubble = root.querySelector<HTMLElement>("[class*='_user_']")!.getBoundingClientRect();
|
||||
const composer = conversation.querySelector<HTMLElement>("[class*='_composerArea_']")!.getBoundingClientRect();
|
||||
const question = conversation.querySelector<HTMLElement>("[class*='_questionCard_']")!.getBoundingClientRect();
|
||||
@@ -436,6 +445,8 @@ test("fits conversation stream, composer, question card and user bubbles to wind
|
||||
bubbleWidth: bubble.width,
|
||||
composerWidth: composer.width,
|
||||
questionWidth: question.width,
|
||||
offscreenRowHeight: rows[0]!.getBoundingClientRect().height,
|
||||
scrollHeight: root.scrollHeight,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -446,14 +457,18 @@ test("fits conversation stream, composer, question card and user bubbles to wind
|
||||
expect(Math.abs(capped.composerWidth - 924)).toBeLessThan(1);
|
||||
expect(Math.abs(capped.questionWidth - 900)).toBeLessThan(1);
|
||||
|
||||
// Toggle on through Settings › Agents › Chat › Apply and verify live re-layout including off-screen rows.
|
||||
await page.evaluate(async () => {
|
||||
const projectPath = "/src/platform/project.ts";
|
||||
const { useProject } = await import(projectPath);
|
||||
const settings = useProject.getState().settings;
|
||||
useProject.setState({
|
||||
settings: { ...settings, agents: { ...settings?.agents, fitWindowWidth: true } } as never,
|
||||
});
|
||||
const actionsPath = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(actionsPath);
|
||||
await executeAction("file.settings", "agents.chat");
|
||||
});
|
||||
const dialog = page.getByRole("dialog", { name: "Settings" });
|
||||
const toggle = dialog.getByRole("checkbox", { name: "Fit conversation to the window width" });
|
||||
await expect(toggle).not.toBeChecked();
|
||||
await toggle.click();
|
||||
await dialog.getByRole("button", { name: "Apply", exact: true }).click();
|
||||
await expect(stream.locator("[data-measured]").first()).toBeAttached();
|
||||
|
||||
const fitted = await measure();
|
||||
expect(Math.abs(fitted.columnWidth - fitted.streamInnerWidth)).toBeLessThan(1);
|
||||
@@ -461,6 +476,18 @@ test("fits conversation stream, composer, question card and user bubbles to wind
|
||||
expect(Math.abs(fitted.bubbleWidth - fitted.streamInnerWidth * 0.8)).toBeLessThan(1);
|
||||
expect(Math.abs(fitted.composerWidth - fitted.conversationWidth)).toBeLessThan(1);
|
||||
expect(Math.abs(fitted.questionWidth - fitted.streamInnerWidth)).toBeLessThan(1);
|
||||
expect(fitted.offscreenRowHeight).toBeLessThan(capped.offscreenRowHeight);
|
||||
expect(fitted.scrollHeight).toBeLessThan(capped.scrollHeight);
|
||||
|
||||
// Toggle back off and click OK: dialog closes and conversation returns to the 900px column live.
|
||||
await toggle.click();
|
||||
await dialog.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect(stream.locator("[data-measured]").first()).toBeAttached();
|
||||
|
||||
const restored = await measure();
|
||||
expect(Math.abs(restored.columnWidth - 900)).toBeLessThan(1);
|
||||
expect(Math.abs(restored.offscreenRowHeight - capped.offscreenRowHeight)).toBeLessThan(1);
|
||||
});
|
||||
|
||||
test("keeps hover actions reachable when the pointer leaves the message body", async ({ page, context }) => {
|
||||
@@ -668,3 +695,69 @@ test("draws a diagram without reaching the hosts its configuration names", async
|
||||
);
|
||||
expect(asked).toEqual(["/after"]);
|
||||
});
|
||||
|
||||
test("Find in Conversation skips user-select:none summaries and closed <details> until stepped into", async ({
|
||||
page,
|
||||
}) => {
|
||||
await openReply(page, "Confirmed—PR is merged.");
|
||||
await page.evaluate(async (task) => {
|
||||
const path = "/src/features/agents/store.ts";
|
||||
const store = await import(path);
|
||||
store.useAgents.setState({
|
||||
entries: new Map([
|
||||
[
|
||||
task.id,
|
||||
[
|
||||
{
|
||||
type: "thought",
|
||||
text: "**Confirming Active Watch Shell**\n\nCheck background shell before rebasing.",
|
||||
},
|
||||
{
|
||||
type: "tool",
|
||||
id: "t1",
|
||||
title: "stop_bash",
|
||||
kind: "other",
|
||||
status: "completed",
|
||||
locations: [],
|
||||
output: "<command with id: 60 had already stopped>",
|
||||
diffs: [],
|
||||
},
|
||||
{ type: "agent", text: "Confirmed—PR is merged." },
|
||||
],
|
||||
],
|
||||
]),
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
}, TASK);
|
||||
|
||||
const stream = page.locator("[class*='_stream_']:visible");
|
||||
const runSummary = stream.locator("details[class*='_processRun_'] > summary");
|
||||
await runSummary.click();
|
||||
await expect(stream.getByText("stop_bash")).toBeVisible();
|
||||
|
||||
await stream.focus();
|
||||
await page.keyboard.press("Meta+f");
|
||||
const findBox = page.getByLabel("Find in Conversation");
|
||||
await findBox.fill("confirm");
|
||||
|
||||
// 2 matches total (1 inside collapsed thought body, 1 in visible reply); unselectable <summary> is excluded.
|
||||
await expect(page.locator("[class*='_findCount_']")).toHaveText("1/2");
|
||||
const initialHighlights = await page.evaluate(() => ({
|
||||
find: [...(CSS.highlights.get("agent-find") ?? [])].map((r) => (r as Range).startContainer.textContent),
|
||||
current: [...(CSS.highlights.get("agent-find-current") ?? [])].map((r) => (r as Range).startContainer.textContent),
|
||||
}));
|
||||
expect(initialHighlights.find).toEqual(["Confirmed—PR is merged."]);
|
||||
expect(initialHighlights.current).toEqual([]);
|
||||
|
||||
// Stepping to match 2/2 opens the collapsed thought <details> and highlights it.
|
||||
await findBox.press("Enter");
|
||||
await expect(page.locator("[class*='_findCount_']")).toHaveText("2/2");
|
||||
await findBox.press("Enter");
|
||||
await expect(page.locator("[class*='_findCount_']")).toHaveText("1/2");
|
||||
const expandedHighlights = await page.evaluate(() => ({
|
||||
thoughtOpen: document.querySelector<HTMLDetailsElement>("details[class*='_thought_']")?.open,
|
||||
findCount: CSS.highlights.get("agent-find")?.size ?? 0,
|
||||
currentCount: CSS.highlights.get("agent-find-current")?.size ?? 0,
|
||||
}));
|
||||
expect(expandedHighlights).toEqual({ thoughtOpen: true, findCount: 2, currentCount: 1 });
|
||||
});
|
||||
@@ -98,6 +98,58 @@ test("completion lists the server's items and inserts the chosen one", async ({
|
||||
expect((await ipcCalls(page, "lsp_completion")).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("typing closes an open documentation tooltip", async ({ workbench: page }) => {
|
||||
const editor = await openSample(page);
|
||||
await page.evaluate(() => {
|
||||
const item = (label: string) => ({
|
||||
label,
|
||||
labelDetail: "()",
|
||||
detail: "Unit",
|
||||
kind: "method",
|
||||
documentation: { kind: "markdown", value: `Docs for **${label}**.` },
|
||||
sortText: null,
|
||||
filterText: null,
|
||||
preselect: false,
|
||||
deprecated: false,
|
||||
insertText: `${label}()`,
|
||||
isSnippet: false,
|
||||
replaceRange: null,
|
||||
replaceRangeTab: null,
|
||||
additionalEdits: [],
|
||||
commitCharacters: [],
|
||||
command: null,
|
||||
data: null,
|
||||
server: 1,
|
||||
});
|
||||
window.__ipc.handlers.lsp_completion = () => ({
|
||||
isIncomplete: false,
|
||||
items: [item("service"), item("serviceName"), item("setUp")],
|
||||
});
|
||||
window.__ipc.handlers.lsp_hover = () => ({
|
||||
contents: { kind: "markdown", value: "Docs for **service**." },
|
||||
range: null,
|
||||
});
|
||||
});
|
||||
const geometry = await editor.locator(".cm-content").evaluate(async (content) => {
|
||||
const viewModule = "/node_modules/.vite/deps/@codemirror_view.js";
|
||||
const { EditorView } = await import(/* @vite-ignore */ viewModule);
|
||||
const view = EditorView.findFromDOM(content as HTMLElement)!;
|
||||
const find = view.state.doc.toString().indexOf("find");
|
||||
if (find < 0 || !view.coordsAtPos(find)) throw new Error('the fixture has no visible "find"');
|
||||
const word = view.coordsAtPos(find)!;
|
||||
view.dispatch({ selection: { anchor: find + 5 } });
|
||||
view.focus();
|
||||
return { wordX: word.left + 2, wordY: (word.top + word.bottom) / 2 };
|
||||
});
|
||||
await page.mouse.move(geometry.wordX, geometry.wordY);
|
||||
const tooltip = page.locator(".cm-tooltip-hover");
|
||||
await expect(tooltip).toBeVisible();
|
||||
await page.keyboard.type("se");
|
||||
const popup = page.locator(".cm-tooltip-autocomplete");
|
||||
await expect(popup.getByText("service", { exact: true })).toBeVisible();
|
||||
await expect(tooltip).toHaveCount(0);
|
||||
});
|
||||
|
||||
for (const key of ["Enter", "Tab"]) {
|
||||
for (const prefix of ["", "v"]) {
|
||||
test(`${key} leaves the caret after a field snippet at root.${prefix}`, async ({ workbench: page }, info) => {
|
||||
|
||||
@@ -174,12 +174,36 @@ test("⌘R replaces every match in the file", async ({ workbench: page }) => {
|
||||
await expect(editor.locator(".cm-line", { hasText: "OrderDto" })).toHaveCount(2);
|
||||
});
|
||||
|
||||
test("Markdown preview highlights ⌘F matches and selected word occurrences", async ({ workbench: page }) => {
|
||||
test("Markdown preview highlights ⌘F matches, selected words and scales diagrams with font zoom", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.evaluate(async () => {
|
||||
const svg =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 96" width="320" height="96"><!-- svg-source:excalidraw --><rect width="320" height="96"/></svg>';
|
||||
const url = `data:image/svg+xml;base64,${btoa(svg)}`;
|
||||
const routeModule = "/src/platform/tauriCore.ts";
|
||||
const { setInvokeRoute } = await import(/* @vite-ignore */ routeModule);
|
||||
setInvokeRoute((cmd: string) => (cmd === "fs_read_image" ? Promise.resolve(url) : null));
|
||||
});
|
||||
|
||||
const editor = await openFromTree(page, "README.md");
|
||||
const content = editor.locator(".cm-content");
|
||||
await content.click();
|
||||
await page.keyboard.press("Meta+a");
|
||||
await page.keyboard.insertText("# Order Service\n\nManage **Order** items and `Order` status.\n");
|
||||
await page.keyboard.insertText(
|
||||
[
|
||||
"# Order Service",
|
||||
"",
|
||||
"Manage **Order** items and `Order` status.",
|
||||
"",
|
||||
"```mermaid",
|
||||
"flowchart LR",
|
||||
" A --> B",
|
||||
"```",
|
||||
"",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
await expect(preview).toContainText("Manage Order items");
|
||||
@@ -209,6 +233,44 @@ test("Markdown preview highlights ⌘F matches and selected word occurrences", a
|
||||
})),
|
||||
)
|
||||
.toEqual({ current: ["Order"], other: ["Order", "Order"] });
|
||||
|
||||
const mermaidSvg = preview.locator(".mermaid-output svg");
|
||||
const excalidrawImg = preview.locator('img[alt="Diagram"]');
|
||||
await expect(mermaidSvg).toBeVisible();
|
||||
await expect(excalidrawImg).toHaveAttribute("src", /^data:image\/svg\+xml/);
|
||||
|
||||
const widths = async () => ({
|
||||
mermaid: (await mermaidSvg.boundingBox())!.width,
|
||||
excalidraw: (await excalidrawImg.boundingBox())!.width,
|
||||
});
|
||||
const base = await widths();
|
||||
expect(base.mermaid).toBeGreaterThan(50);
|
||||
expect(base.excalidraw).toBeCloseTo(320, 0);
|
||||
|
||||
const runAction = (id: string, times = 1) =>
|
||||
page.evaluate(
|
||||
async ({ id, times }) => {
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
for (let i = 0; i < times; i++) await executeAction(id);
|
||||
},
|
||||
{ id, times },
|
||||
);
|
||||
|
||||
await runAction("editor.increaseFontSize", 4);
|
||||
const zoomedIn = await widths();
|
||||
expect(zoomedIn.mermaid / base.mermaid).toBeCloseTo(17 / 13, 2);
|
||||
expect(zoomedIn.excalidraw / base.excalidraw).toBeCloseTo(17 / 13, 2);
|
||||
|
||||
await runAction("editor.decreaseFontSize", 6);
|
||||
const zoomedOut = await widths();
|
||||
expect(zoomedOut.mermaid / base.mermaid).toBeCloseTo(11 / 13, 2);
|
||||
expect(zoomedOut.excalidraw / base.excalidraw).toBeCloseTo(11 / 13, 2);
|
||||
|
||||
await runAction("editor.resetFontSize");
|
||||
const reset = await widths();
|
||||
expect(reset.mermaid).toBeCloseTo(base.mermaid, 1);
|
||||
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
|
||||
});
|
||||
|
||||
test("the bookmark gutter takes no width until the file has a bookmark", async ({ workbench: page }) => {
|
||||
|
||||
@@ -28,4 +28,11 @@ pub fn build(b: *std.Build) void {
|
||||
const tests = b.addTest(.{ .root_module = tally });
|
||||
const test_step = b.step("test", "Run the tests");
|
||||
test_step.dependOn(&b.addRunArtifact(tests).step);
|
||||
|
||||
const failing_tests = b.addTest(.{ .root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/failing.zig"),
|
||||
.target = target,
|
||||
}) });
|
||||
const test_failing_step = b.step("test-failing", "Run the tests that fail on purpose");
|
||||
test_failing_step.dependOn(&b.addRunArtifact(failing_tests).step);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Fails on purpose: the `test-failing` step, for checking that a run's failure shows up
|
||||
//! in the test tree and Rerun Failed Tests re-runs it alone.
|
||||
test "intentionally fails" {
|
||||
return error.OpenideaFail;
|
||||
}
|
||||
@@ -3,7 +3,8 @@ const tally = @import("tally");
|
||||
|
||||
pub fn main() !void {
|
||||
const prices = [_]u32{ 4999, 2499, 5999 };
|
||||
const sum = tally.total(&prices); // Set a breakpoint here
|
||||
const sum = tally.total(&prices);
|
||||
var buf: [16]u8 = undefined;
|
||||
// Set a breakpoint here (QA: debugger) and inspect `sum`.
|
||||
std.debug.print("Total: {s}\n", .{try tally.format(&buf, sum)});
|
||||
}
|
||||
@@ -164,6 +164,17 @@ const CASES: Record<string, Case> = {
|
||||
variable: "line",
|
||||
evaluate: ["print line", / = /],
|
||||
},
|
||||
// Zig ships no debugger of its own: CodeLLDB debugs the binary `zig build` produces.
|
||||
// The breakpoint lands on the last use of `sum`: zig's debuginfo gives a const local a
|
||||
// location only within its live range, so `prices` (used earlier) is not in the frame.
|
||||
zig: {
|
||||
fixture: "zig-app",
|
||||
tools: ["codelldb"],
|
||||
adapter: "codelldb",
|
||||
file: "src/main.zig",
|
||||
variable: "sum",
|
||||
evaluate: ["sum", /13497/],
|
||||
},
|
||||
php: {
|
||||
fixture: "php-app",
|
||||
setup: (root) =>
|
||||
|
||||
@@ -135,6 +135,19 @@ const CASES: Record<string, Case> = {
|
||||
file: "ThresholdCustomsTest.php",
|
||||
},
|
||||
},
|
||||
// The failing run uses the fixture's dedicated `test-failing` step (`zig build` forwards
|
||||
// no args to the test binary, so a failing test can't be switched on through the config).
|
||||
zig: {
|
||||
fixture: "zig-app",
|
||||
run: { config: "zig:run", prints: "Total: $134.97" },
|
||||
tests: {
|
||||
config: "zig:test-failing",
|
||||
failing: (c) => c,
|
||||
passed: 0,
|
||||
failed: "intentionally fails",
|
||||
file: "src/failing.zig",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
let server: Server | null = null;
|
||||
|
||||
@@ -76,15 +76,26 @@ pub async fn clipboard_set_file_list(app: AppHandle, paths: Vec<PathBuf>) -> Ide
|
||||
with_clipboard(app, move || Ok(ide_clipboard::set_files(&paths))).await
|
||||
}
|
||||
|
||||
/// The clipboard's image as a PNG data URL, for a paste whose event carried no
|
||||
/// files: WebKitGTK leaves `clipboardData` empty for a raw image (a screenshot).
|
||||
/// None when the clipboard holds no image, and always on other platforms.
|
||||
/// Whether the clipboard holds an image (a screenshot): cheap, for the Paste item's
|
||||
/// enabled state.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn clipboard_has_image() -> bool {
|
||||
// Synchronous Tauri commands run on the main thread, as macOS and GTK require.
|
||||
ide_clipboard::has_image()
|
||||
}
|
||||
|
||||
/// The clipboard's image as a PNG data URL: for a paste whose event carried no files
|
||||
/// (WebKitGTK leaves `clipboardData` empty for a raw image, a screenshot), and for
|
||||
/// the project view's Paste, which has no paste event. None when it holds no image.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn clipboard_image(app: AppHandle) -> IdeResult<Option<String>> {
|
||||
use base64::Engine;
|
||||
let data_url =
|
||||
|bytes: Vec<u8>| format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes));
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
use base64::Engine;
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
app.run_on_main_thread(move || {
|
||||
let sender = std::cell::Cell::new(Some(tx));
|
||||
@@ -98,14 +109,11 @@ pub async fn clipboard_image(app: AppHandle) -> IdeResult<Option<String>> {
|
||||
.map_err(|error| {
|
||||
ide_core::IdeError::internal(format!("Cannot dispatch clipboard access to the main thread: {error}"))
|
||||
})?;
|
||||
let png = rx.await.ok().flatten();
|
||||
Ok(png
|
||||
.map(|bytes| format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes))))
|
||||
Ok(rx.await.ok().flatten().map(data_url))
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let _ = app;
|
||||
Ok(None)
|
||||
Ok(with_clipboard(app, || Ok(ide_clipboard::png())).await?.map(data_url))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -195,6 +195,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
clipboard::clipboard_text,
|
||||
clipboard::clipboard_file_list,
|
||||
clipboard::clipboard_has_files,
|
||||
clipboard::clipboard_has_image,
|
||||
clipboard::clipboard_image,
|
||||
clipboard::clipboard_set_file_list,
|
||||
fonts::system_font_families,
|
||||
|
||||
@@ -0,0 +1,698 @@
|
||||
# Generated by `pnpm gen:bindings`; do not edit. One line per command:
|
||||
# name, trust class, placement in a remote window, in bindings.ts, how Tauri runs it.
|
||||
agent_accept_changes trusted project_host bindings async
|
||||
agent_archive always project_host bindings sync
|
||||
agent_base_text trusted project_host bindings async
|
||||
agent_cancel always project_host bindings sync
|
||||
agent_changes trusted project_host bindings async
|
||||
agent_commands always project_host bindings async
|
||||
agent_create trusted project_host bindings async
|
||||
agent_create_ephemeral trusted desktop bindings async
|
||||
agent_custom_import trusted desktop bindings sync
|
||||
agent_custom_remove trusted desktop bindings sync
|
||||
agent_custom_save trusted desktop bindings sync
|
||||
agent_delete trusted project_host bindings async
|
||||
agent_entries always project_host bindings sync
|
||||
agent_external_sessions trusted project_host bindings async
|
||||
agent_fork trusted project_host bindings async
|
||||
agent_grouped_changes trusted project_host bindings async
|
||||
agent_import_session trusted project_host bindings async
|
||||
agent_mcp_import always project_host bindings sync
|
||||
agent_mcp_list always project_host bindings sync
|
||||
agent_mcp_remove always project_host bindings sync
|
||||
agent_mcp_save always project_host bindings sync
|
||||
agent_mcp_set_enabled always project_host bindings sync
|
||||
agent_probe trusted project_host bindings async
|
||||
agent_prompt trusted project_host bindings async
|
||||
agent_providers trusted project_host bindings sync
|
||||
agent_refresh_models trusted project_host bindings sync
|
||||
agent_registry_install always project_host bindings async
|
||||
agent_registry_list always project_host bindings async
|
||||
agent_registry_remove always project_host bindings async
|
||||
agent_rename trusted project_host bindings sync
|
||||
agent_respond trusted project_host bindings sync
|
||||
agent_rollback trusted project_host bindings async
|
||||
agent_rollback_changes trusted project_host bindings async
|
||||
agent_send_queued_now trusted project_host bindings sync
|
||||
agent_set_command trusted project_host bindings sync
|
||||
agent_set_config trusted project_host bindings async
|
||||
agent_set_env trusted project_host bindings sync
|
||||
agent_stop_background always project_host bindings async
|
||||
agent_subscribe always project_host bindings sync
|
||||
agent_unarchive always project_host bindings sync
|
||||
agent_unqueue always project_host bindings sync
|
||||
analysis_locate_duplicates always project_host bindings async
|
||||
android_devices trusted desktop bindings async
|
||||
android_logcat trusted desktop bindings async
|
||||
app_build_info always desktop bindings sync
|
||||
app_cancel_quit always desktop bindings sync
|
||||
app_check_update always desktop bindings async
|
||||
app_cli_install always desktop bindings async
|
||||
app_cli_uninstall always desktop bindings async
|
||||
app_info always desktop bindings sync
|
||||
app_install_update always desktop bindings async
|
||||
app_log_location always desktop bindings sync
|
||||
app_metrics always desktop bindings async
|
||||
app_quit always desktop bindings sync
|
||||
app_release_notes trusted desktop bindings async
|
||||
app_restart always desktop bindings sync
|
||||
app_update_announcement always desktop bindings sync
|
||||
app_update_status always desktop bindings sync
|
||||
app_update_window_ready always desktop bindings sync
|
||||
apply_workspace_edit always project_host bindings async
|
||||
build_compile_file trusted project_host bindings async
|
||||
build_model trusted project_host bindings async
|
||||
build_run trusted project_host bindings async
|
||||
build_sync trusted project_host bindings async
|
||||
caches_local_data_info trusted desktop bindings sync
|
||||
caches_schedule_invalidation always desktop bindings sync
|
||||
caches_set_local_data_dir trusted desktop bindings sync
|
||||
cancel_request always project_host bindings sync
|
||||
cancel_task always project_host bindings sync
|
||||
clear_caches always desktop bindings async
|
||||
clipboard_file_list always desktop bindings async
|
||||
clipboard_has_files always desktop bindings sync
|
||||
clipboard_image always desktop bindings async
|
||||
clipboard_set_file_list always desktop bindings async
|
||||
clipboard_text trusted desktop bindings async
|
||||
clipboard_write_text always desktop bindings async
|
||||
close_project always project_host bindings spawn
|
||||
coverage_collect trusted project_host bindings async
|
||||
coverage_import always project_host bindings async
|
||||
coverage_prepare trusted project_host bindings async
|
||||
db_apply_edits trusted project_host bindings async
|
||||
db_completion trusted project_host bindings async
|
||||
db_connect trusted project_host bindings async
|
||||
db_connected trusted project_host bindings sync
|
||||
db_console_path always project_host bindings sync
|
||||
db_consoles always project_host bindings sync
|
||||
db_database_catalog trusted project_host bindings async
|
||||
db_databases trusted project_host bindings async
|
||||
db_ddl trusted project_host bindings async
|
||||
db_disconnect trusted project_host bindings async
|
||||
db_execute trusted project_host bindings async
|
||||
db_explain trusted project_host bindings async
|
||||
db_export_file always desktop bindings async
|
||||
db_finish_transaction trusted project_host bindings async
|
||||
db_history trusted project_host bindings async
|
||||
db_object_ddl trusted project_host bindings async
|
||||
db_remove_history trusted project_host bindings async
|
||||
db_retain_catalog trusted project_host bindings async
|
||||
db_save_sources trusted project_host bindings async
|
||||
db_saved_catalog trusted project_host bindings async
|
||||
db_schema_objects trusted project_host bindings async
|
||||
db_schemas trusted project_host bindings async
|
||||
db_session_context trusted project_host bindings async
|
||||
db_set_manual_commit trusted project_host bindings async
|
||||
db_set_password trusted project_host bindings async
|
||||
db_set_ssh_secret trusted project_host bindings async
|
||||
db_sources trusted project_host bindings sync
|
||||
db_statements trusted project_host bindings sync
|
||||
db_table_details trusted project_host bindings async
|
||||
db_table_page trusted project_host bindings async
|
||||
db_tables trusted project_host bindings async
|
||||
db_test trusted project_host bindings async
|
||||
db_test_tunnel trusted project_host bindings async
|
||||
db_trust_ssh_host trusted project_host bindings async
|
||||
debug_attachable_processes always project_host bindings async
|
||||
debug_breakpoint_states trusted project_host bindings sync
|
||||
debug_capabilities trusted project_host bindings sync
|
||||
debug_completions trusted project_host bindings async
|
||||
debug_data_breakpoint_info trusted project_host bindings async
|
||||
debug_evaluate trusted project_host bindings async
|
||||
debug_evaluate_in trusted project_host bindings async
|
||||
debug_exception_filters trusted project_host bindings sync
|
||||
debug_force_step_over trusted project_host bindings async
|
||||
debug_free_port trusted project_host bindings async
|
||||
debug_heap_capture trusted project_host bindings async
|
||||
debug_heap_classes trusted project_host bindings async
|
||||
debug_heap_close trusted project_host bindings async
|
||||
debug_heap_compare trusted project_host bindings async
|
||||
debug_heap_dominators trusted project_host bindings async
|
||||
debug_heap_open trusted project_host bindings async
|
||||
debug_heap_path trusted project_host bindings async
|
||||
debug_heap_save trusted project_host bindings async
|
||||
debug_hot_reload trusted desktop bindings async
|
||||
debug_hot_restart trusted desktop bindings async
|
||||
debug_js_custom_breakpoints trusted project_host bindings async
|
||||
debug_js_response_body trusted project_host bindings async
|
||||
debug_js_response_overrides trusted project_host bindings async
|
||||
debug_js_start_profile trusted project_host bindings async
|
||||
debug_js_stop_profile trusted project_host bindings async
|
||||
debug_jvm_memory_classes trusted project_host bindings async
|
||||
debug_jvm_memory_fields trusted project_host bindings async
|
||||
debug_jvm_memory_instances trusted project_host bindings async
|
||||
debug_jvm_memory_referrers trusted project_host bindings async
|
||||
debug_listen_for_jvm trusted project_host bindings async
|
||||
debug_pause trusted project_host bindings async
|
||||
debug_redefine_classes trusted project_host bindings async
|
||||
debug_restart_frame trusted project_host bindings async
|
||||
debug_resume trusted project_host bindings async
|
||||
debug_run_to trusted project_host bindings async
|
||||
debug_scopes trusted project_host bindings async
|
||||
debug_send_input trusted project_host bindings async
|
||||
debug_sessions always project_host bindings sync
|
||||
debug_set_breakpoints trusted project_host bindings async
|
||||
debug_set_data_breakpoints trusted project_host bindings async
|
||||
debug_set_exception_breakpoints trusted project_host bindings async
|
||||
debug_set_function_breakpoints trusted project_host bindings async
|
||||
debug_set_variable trusted project_host bindings async
|
||||
debug_stack_trace trusted project_host bindings async
|
||||
debug_start trusted project_host bindings async
|
||||
debug_step trusted project_host bindings async
|
||||
debug_step_in_target trusted project_host bindings async
|
||||
debug_step_in_targets trusted project_host bindings async
|
||||
debug_stop always project_host bindings async
|
||||
debug_threads trusted project_host bindings async
|
||||
debug_variables trusted project_host bindings async
|
||||
dependency_versions trusted project_host bindings async
|
||||
deploy_compare trusted project_host bindings async
|
||||
deploy_coverage always project_host bindings async
|
||||
deploy_delete_remote trusted project_host bindings async
|
||||
deploy_download trusted project_host bindings async
|
||||
deploy_info trusted project_host bindings async
|
||||
deploy_server_root trusted project_host bindings async
|
||||
deploy_sync trusted project_host bindings async
|
||||
deploy_test_connection always project_host bindings async
|
||||
deploy_upload trusted project_host bindings async
|
||||
doc_close always project_host bindings async
|
||||
doc_edit always project_host bindings async
|
||||
doc_folding always project_host bindings async
|
||||
doc_highlights always project_host bindings async
|
||||
doc_open always project_host bindings async
|
||||
doc_open_untitled always project_host bindings async
|
||||
doc_open_virtual always project_host bindings async
|
||||
doc_outline always project_host bindings async
|
||||
doc_python_facts always project_host bindings async
|
||||
doc_save always project_host bindings async
|
||||
doc_save_all always project_host bindings async
|
||||
doc_save_as always project_host bindings async
|
||||
doc_selection_ranges always project_host bindings async
|
||||
doc_set_bom always project_host bindings async
|
||||
doc_set_encoding always project_host bindings async
|
||||
doc_set_line_ending always project_host bindings async
|
||||
doc_snapshot always project_host bindings async
|
||||
doc_sync_from_disk always project_host bindings async
|
||||
doc_ui_mode always project_host bindings async
|
||||
docker_compose_op trusted desktop bindings async
|
||||
docker_container_op trusted desktop bindings async
|
||||
docker_container_stats trusted desktop bindings async
|
||||
docker_container_top trusted desktop bindings async
|
||||
docker_events trusted desktop bindings async
|
||||
docker_image_history trusted desktop bindings async
|
||||
docker_inspect trusted desktop bindings async
|
||||
docker_logs trusted desktop bindings async
|
||||
docker_prune trusted desktop bindings async
|
||||
docker_pull trusted desktop bindings async
|
||||
docker_registry_login trusted desktop bindings async
|
||||
docker_remove trusted desktop bindings async
|
||||
docker_run_env always project_host bindings async
|
||||
docker_save_settings always desktop bindings async
|
||||
docker_set_registry_password always desktop bindings async
|
||||
docker_settings always desktop bindings async
|
||||
docker_snapshot trusted desktop bindings async
|
||||
end_process trusted desktop bindings async
|
||||
env_reload always project_host bindings async
|
||||
file_dialog_needs_gtk trusted desktop bindings async
|
||||
find_dirs always project_host bindings sync
|
||||
find_files always project_host bindings sync
|
||||
find_files_named always project_host bindings async
|
||||
find_symbols always project_host bindings sync
|
||||
fs_compare_directories always project_host bindings async
|
||||
fs_copy always project_host bindings async
|
||||
fs_copy_merge always project_host bindings async
|
||||
fs_create_dir always project_host bindings sync
|
||||
fs_create_file always project_host bindings sync
|
||||
fs_create_file_bytes always project_host bindings async
|
||||
fs_delete always project_host bindings async
|
||||
fs_entry_kind always project_host bindings async
|
||||
fs_open_with_system always desktop bindings async
|
||||
fs_probe always project_host bindings async
|
||||
fs_read_dir always project_host bindings async
|
||||
fs_read_image always project_host bindings async
|
||||
fs_read_range always project_host bindings async
|
||||
fs_read_text always project_host bindings async
|
||||
fs_rename always project_host bindings async
|
||||
fs_resolve_reference always project_host bindings async
|
||||
fs_set_writable always project_host bindings sync
|
||||
gh_account_repos trusted desktop bindings async
|
||||
gh_api trusted desktop bindings async
|
||||
gh_availability trusted desktop bindings async
|
||||
gh_pr_checkout trusted desktop bindings async
|
||||
gh_pr_comment trusted desktop bindings async
|
||||
gh_pr_create trusted desktop bindings async
|
||||
gh_pr_list trusted desktop bindings async
|
||||
gh_pr_prepare_diff trusted desktop bindings async
|
||||
gh_pr_review trusted desktop bindings async
|
||||
gh_pr_review_comments trusted desktop bindings async
|
||||
gh_pr_view trusted desktop bindings async
|
||||
git_credential_forget always desktop bindings sync
|
||||
git_credentials always desktop bindings sync
|
||||
gradle_dependencies trusted project_host bindings async
|
||||
gradle_link_projects trusted project_host bindings async
|
||||
gradle_published_catalog trusted project_host bindings async
|
||||
gradle_unlink_projects trusted project_host bindings async
|
||||
gtk_pick_paths trusted desktop bindings async
|
||||
history_content always project_host bindings async
|
||||
history_list always project_host bindings async
|
||||
history_list_dir always project_host bindings async
|
||||
history_put_label always project_host bindings sync
|
||||
history_restore always project_host bindings async
|
||||
http_curl trusted desktop bindings async
|
||||
http_environment_file trusted desktop bindings async
|
||||
http_environments trusted desktop bindings async
|
||||
http_execute trusted desktop bindings async
|
||||
http_from_curl trusted desktop bindings sync
|
||||
http_history trusted desktop bindings sync
|
||||
http_history_clear trusted desktop bindings sync
|
||||
http_history_get trusted desktop bindings sync
|
||||
http_requests trusted desktop bindings sync
|
||||
http_variable_definitions trusted desktop bindings async
|
||||
index_file_extensions always project_host bindings sync
|
||||
index_status always project_host bindings sync
|
||||
inspect_code trusted project_host bindings async
|
||||
java_build_workspace trusted project_host bindings async
|
||||
java_debug_server trusted project_host bindings async
|
||||
java_resolve_launch trusted project_host bindings async
|
||||
jdk_download always project_host bindings async
|
||||
jdk_download_location always project_host bindings sync
|
||||
jdk_download_releases always project_host bindings async
|
||||
jdk_download_vendors always project_host bindings sync
|
||||
jdtls_required_java always project_host bindings async
|
||||
jvm_file_presentations always project_host bindings async
|
||||
languages always desktop bindings sync
|
||||
light_edit_open always desktop bindings async
|
||||
light_edit_open_untitled always desktop bindings async
|
||||
log_frontend always desktop bindings sync
|
||||
lsp_apply_code_action trusted project_host bindings async
|
||||
lsp_call_hierarchy trusted project_host bindings async
|
||||
lsp_can_download_sources trusted project_host bindings async
|
||||
lsp_code_action_query trusted project_host bindings async
|
||||
lsp_code_actions trusted project_host bindings async
|
||||
lsp_code_lens trusted project_host bindings async
|
||||
lsp_completion trusted project_host bindings async
|
||||
lsp_document_highlights trusted project_host bindings async
|
||||
lsp_document_links trusted project_host bindings async
|
||||
lsp_execute_code_action trusted project_host bindings async
|
||||
lsp_execute_command trusted project_host bindings async
|
||||
lsp_format trusted project_host bindings async
|
||||
lsp_goto trusted project_host bindings async
|
||||
lsp_goto_implementation trusted project_host bindings async
|
||||
lsp_hierarchy_members trusted project_host bindings async
|
||||
lsp_hierarchy_refactor trusted project_host bindings async
|
||||
lsp_hover trusted project_host bindings async
|
||||
lsp_implementations trusted project_host bindings async
|
||||
lsp_inlay_hints trusted project_host bindings async
|
||||
lsp_inline_completion trusted project_host bindings async
|
||||
lsp_library_sources trusted project_host bindings async
|
||||
lsp_prepare_rename trusted project_host bindings async
|
||||
lsp_prepare_type_hierarchy trusted project_host bindings async
|
||||
lsp_references trusted project_host bindings async
|
||||
lsp_rename trusted project_host bindings async
|
||||
lsp_resend_diagnostics always project_host bindings sync
|
||||
lsp_resolve_class_file trusted project_host bindings async
|
||||
lsp_resolve_code_action trusted project_host bindings async
|
||||
lsp_resolve_command trusted project_host bindings async
|
||||
lsp_resolve_completion trusted project_host bindings async
|
||||
lsp_restart trusted project_host bindings async
|
||||
lsp_restart_named trusted desktop bindings async
|
||||
lsp_semantic_tokens trusted project_host bindings async
|
||||
lsp_servers always project_host bindings sync
|
||||
lsp_signature_help trusted project_host bindings async
|
||||
lsp_type_hierarchy trusted project_host bindings async
|
||||
lsp_virtual_document trusted project_host bindings async
|
||||
lsp_workspace_symbols trusted project_host bindings async
|
||||
mark_recent always project_host bindings sync
|
||||
maven_dependency_completion trusted project_host bindings async
|
||||
maven_dependency_declaration trusted project_host bindings async
|
||||
maven_exclude_dependency trusted project_host bindings async
|
||||
maven_goto_declaration trusted project_host bindings async
|
||||
mcp_agent_run_closed trusted desktop bindings sync
|
||||
mcp_regenerate_token trusted desktop bindings sync
|
||||
mcp_report_problems trusted project_host bindings sync
|
||||
mcp_respond trusted desktop bindings sync
|
||||
mcp_server_status trusted desktop bindings sync
|
||||
mcp_set_focused_editor trusted project_host bindings sync
|
||||
mcp_set_open_editors trusted project_host bindings sync
|
||||
mcp_ui_ready trusted desktop bindings sync
|
||||
menu_configure always desktop bindings sync
|
||||
menu_model always desktop bindings sync
|
||||
menu_refresh always desktop bindings sync
|
||||
menu_set_disabled always desktop bindings sync
|
||||
nav_index_definitions always project_host bindings async
|
||||
nav_inheritance always project_host bindings async
|
||||
nav_resolve_module always project_host bindings async
|
||||
notebook_cell_docs trusted project_host bindings sync
|
||||
notebook_close always project_host bindings async
|
||||
notebook_edit always project_host bindings async
|
||||
notebook_execute trusted project_host bindings async
|
||||
notebook_get always project_host bindings sync
|
||||
notebook_interrupt always project_host bindings async
|
||||
notebook_open always project_host bindings async
|
||||
notebook_redo always project_host bindings async
|
||||
notebook_reload always project_host bindings async
|
||||
notebook_restart trusted project_host bindings async
|
||||
notebook_save always project_host bindings async
|
||||
notebook_undo always project_host bindings async
|
||||
open_project always project_host bindings async
|
||||
path_completions always project_host bindings async
|
||||
plugin_activation_event trusted desktop bindings async
|
||||
plugin_answer_command trusted project_host bindings sync
|
||||
plugin_answer_commit trusted project_host bindings sync
|
||||
plugin_answer_prompt trusted project_host bindings sync
|
||||
plugin_answer_run_target trusted project_host bindings async
|
||||
plugin_assets always desktop bindings async
|
||||
plugin_cancel_task trusted project_host bindings sync
|
||||
plugin_catalog always desktop bindings async
|
||||
plugin_choose_program outside_restricted project_host bindings async
|
||||
plugin_color_presentations trusted project_host bindings async
|
||||
plugin_commit_checks trusted project_host bindings async
|
||||
plugin_content_tab_action trusted project_host bindings sync
|
||||
plugin_context_keys trusted project_host bindings sync
|
||||
plugin_debug_attach_target trusted project_host bindings async
|
||||
plugin_decoration_sets trusted project_host bindings sync
|
||||
plugin_endpoints trusted project_host bindings async
|
||||
plugin_event_kinds trusted project_host bindings async
|
||||
plugin_finish_operation trusted project_host bindings sync
|
||||
plugin_formatters trusted project_host bindings sync
|
||||
plugin_grant outside_restricted desktop bindings async
|
||||
plugin_install_dir outside_restricted desktop bindings async
|
||||
plugin_installed_intellij_themes always desktop bindings async
|
||||
plugin_language_visuals trusted project_host bindings async
|
||||
plugin_line_markers trusted project_host bindings async
|
||||
plugin_link trusted desktop bindings async
|
||||
plugin_list always desktop bindings async
|
||||
plugin_log_tab_spawn trusted desktop bindings async
|
||||
plugin_market always desktop bindings async
|
||||
plugin_market_download always desktop bindings async
|
||||
plugin_market_url always desktop bindings sync
|
||||
plugin_navigation_files trusted project_host bindings async
|
||||
plugin_navigation_goto trusted project_host bindings async
|
||||
plugin_navigation_index trusted project_host bindings async
|
||||
plugin_navigation_invalidate trusted project_host bindings sync
|
||||
plugin_navigation_markers trusted project_host bindings async
|
||||
plugin_parse_test_results trusted project_host bindings async
|
||||
plugin_post_events trusted project_host bindings sync
|
||||
plugin_prepare_debug_run trusted project_host bindings async
|
||||
plugin_preview_install always desktop bindings async
|
||||
plugin_program outside_restricted project_host bindings async
|
||||
plugin_read_intellij_theme always desktop bindings async
|
||||
plugin_reload outside_restricted desktop bindings async
|
||||
plugin_revoke_net_host outside_restricted desktop bindings async
|
||||
plugin_roll_back outside_restricted desktop bindings async
|
||||
plugin_run_command trusted project_host bindings async
|
||||
plugin_run_targets trusted project_host bindings async
|
||||
plugin_secrets trusted desktop bindings sync
|
||||
plugin_select_tests trusted project_host bindings async
|
||||
plugin_service_detail trusted project_host bindings async
|
||||
plugin_service_log trusted project_host bindings async
|
||||
plugin_set_active_file always project_host bindings sync
|
||||
plugin_set_capability outside_restricted desktop bindings async
|
||||
plugin_set_enabled outside_restricted desktop bindings async
|
||||
plugin_set_market_url always desktop bindings sync
|
||||
plugin_set_secret trusted desktop bindings sync
|
||||
plugin_set_theme always desktop bindings sync
|
||||
plugin_set_theme_frame always desktop bindings sync
|
||||
plugin_set_ui_locale always project_host bindings async
|
||||
plugin_stage_package always desktop bindings async
|
||||
plugin_status_items trusted project_host bindings sync
|
||||
plugin_subscribe always desktop bindings sync
|
||||
plugin_sync_languages trusted project_host - -
|
||||
plugin_sync_packages trusted project_host - -
|
||||
plugin_terminal_session_close trusted project_host bindings sync
|
||||
plugin_terminal_session_spawn trusted project_host bindings async
|
||||
plugin_uninstall outside_restricted desktop bindings async
|
||||
plugin_unlink trusted desktop bindings async
|
||||
plugin_unpack_package always desktop bindings async
|
||||
plugin_view_event trusted project_host bindings async
|
||||
plugin_view_render trusted project_host bindings async
|
||||
plugin_web_page trusted desktop bindings sync
|
||||
plugin_web_pty_spawn trusted desktop bindings async
|
||||
plugin_web_read_file trusted desktop bindings async
|
||||
plugin_web_save_file trusted desktop bindings async
|
||||
prepare_workspace_edit always project_host bindings async
|
||||
profiler_collect trusted desktop bindings async
|
||||
profiler_gc_before_stop trusted desktop bindings async
|
||||
profiler_prepare trusted desktop bindings async
|
||||
project_current always project_host bindings sync
|
||||
project_rename always desktop bindings sync
|
||||
project_roots always project_host bindings sync
|
||||
project_trust_add_location always desktop bindings async
|
||||
project_trust_list always project_host bindings sync
|
||||
project_trust_remove_location always project_host bindings async
|
||||
project_trust_set always project_host bindings async
|
||||
project_trust_status always project_host bindings sync
|
||||
proxy_check_connection always desktop bindings async
|
||||
recent_files always project_host bindings sync
|
||||
recent_project_groups always desktop bindings sync
|
||||
recent_projects always desktop bindings async
|
||||
redo_workspace_edit always project_host bindings async
|
||||
refactor_can_undo_file_move always project_host bindings sync
|
||||
refactor_file_move_edits always project_host bindings async
|
||||
refactor_file_move_text_edits always project_host bindings async
|
||||
refactor_move_files always project_host bindings async
|
||||
refactor_undo_file_move always project_host bindings async
|
||||
remote_bootstrap_list always desktop bindings async
|
||||
remote_connect always desktop bindings async
|
||||
remote_current always desktop bindings sync
|
||||
remote_delete trusted project_host bindings async
|
||||
remote_disconnect always desktop bindings sync
|
||||
remote_download_into trusted project_host bindings async
|
||||
remote_forward_port trusted desktop bindings async
|
||||
remote_forwarded_ports trusted desktop bindings sync
|
||||
remote_import_local trusted desktop bindings async
|
||||
remote_invoke always desktop bindings async
|
||||
remote_list always project_host bindings async
|
||||
remote_mkdir trusted project_host bindings async
|
||||
remote_of always project_host bindings sync
|
||||
remote_open always project_host bindings async
|
||||
remote_rename trusted project_host bindings async
|
||||
remote_stop_forwarding trusted desktop bindings async
|
||||
remote_trust_set always desktop bindings sync
|
||||
remote_trust_status always desktop bindings sync
|
||||
remove_recent always project_host bindings sync
|
||||
remove_recent_project always desktop bindings sync
|
||||
replace_in_files trusted project_host bindings async
|
||||
replace_preview trusted project_host bindings async
|
||||
run_application_build trusted project_host bindings async
|
||||
run_application_publish trusted project_host bindings async
|
||||
run_apply_settings trusted project_host bindings async
|
||||
run_close_stdin trusted project_host bindings sync
|
||||
run_configs trusted project_host bindings async
|
||||
run_dotnet_resolve trusted project_host bindings async
|
||||
run_env_files trusted project_host bindings async
|
||||
run_gradle_init_script trusted project_host bindings async
|
||||
run_gradle_jvm_args_script always project_host bindings async
|
||||
run_import_configs trusted project_host bindings async
|
||||
run_import_sources trusted project_host bindings async
|
||||
run_list always project_host bindings sync
|
||||
run_resize trusted project_host bindings sync
|
||||
run_save_configs trusted project_host bindings async
|
||||
run_save_templates trusted project_host bindings async
|
||||
run_start trusted project_host bindings async
|
||||
run_stdin trusted project_host bindings sync
|
||||
run_stop always project_host bindings sync
|
||||
run_system_env always project_host bindings sync
|
||||
run_templates trusted project_host bindings async
|
||||
run_test_reports trusted project_host bindings async
|
||||
run_tomcat_artifacts trusted project_host bindings async
|
||||
run_tomcat_build trusted project_host bindings async
|
||||
run_tomcat_home trusted project_host bindings async
|
||||
run_tomcat_installations trusted project_host bindings async
|
||||
run_tomcat_sync trusted project_host bindings async
|
||||
run_tomcat_update trusted project_host bindings async
|
||||
run_without_derived trusted project_host bindings async
|
||||
scaffold_catalog always project_host bindings sync
|
||||
scaffold_create always project_host bindings async
|
||||
scaffold_options always project_host bindings async
|
||||
scaffold_requirements always project_host bindings async
|
||||
sdk_container_python trusted project_host bindings sync
|
||||
sdk_container_python_refresh trusted project_host bindings async
|
||||
sdk_detect trusted project_host bindings async
|
||||
sdk_locate_tools trusted project_host bindings async
|
||||
sdk_php_composer_install trusted project_host bindings async
|
||||
sdk_php_effective trusted project_host bindings sync
|
||||
sdk_php_language_level trusted project_host bindings async
|
||||
sdk_php_xdebug trusted project_host bindings async
|
||||
sdk_project_libraries trusted project_host bindings async
|
||||
sdk_python_create_venv trusted project_host bindings async
|
||||
sdk_python_effective trusted project_host bindings sync
|
||||
sdk_python_interpreter trusted project_host bindings async
|
||||
sdk_python_packages trusted project_host bindings async
|
||||
sdk_python_pip trusted project_host bindings async
|
||||
sdk_python_project_interpreters trusted project_host bindings async
|
||||
search_start always project_host bindings async
|
||||
search_validate always project_host bindings sync
|
||||
set_recent_project_groups always desktop bindings sync
|
||||
settings_export always desktop bindings async
|
||||
settings_get always project_host bindings sync
|
||||
settings_get_global always desktop bindings sync
|
||||
settings_import always desktop bindings async
|
||||
settings_list_jetbrains_ides always desktop bindings async
|
||||
settings_read_jetbrains always desktop bindings async
|
||||
settings_set always project_host bindings sync
|
||||
spell_check always project_host bindings async
|
||||
spell_suggest always project_host bindings async
|
||||
spring_route_sources trusted desktop bindings sync
|
||||
ssh_askpass_answer always desktop bindings sync
|
||||
ssh_connected always project_host bindings sync
|
||||
ssh_disconnect always project_host bindings sync
|
||||
ssh_needs_secret always project_host bindings sync
|
||||
ssh_open_terminal always desktop bindings async
|
||||
ssh_password_saved always project_host bindings sync
|
||||
ssh_set_secret always project_host bindings sync
|
||||
ssh_test always project_host bindings async
|
||||
ssh_trust_host always project_host bindings async
|
||||
structural_languages always project_host bindings async
|
||||
structural_search always project_host bindings async
|
||||
structural_validate always project_host bindings async
|
||||
syntax_errors always project_host bindings async
|
||||
syntax_expression_at always project_host bindings async
|
||||
syntax_identifiers always project_host bindings async
|
||||
syntax_identifiers_in_files always project_host bindings async
|
||||
syntax_locals always project_host bindings async
|
||||
syntax_node_at always project_host bindings async
|
||||
syntax_structural_ranges always project_host bindings async
|
||||
syntax_support always project_host bindings sync
|
||||
system_font_families always desktop bindings async
|
||||
system_probe_hotkeys trusted desktop bindings sync
|
||||
term_available_shells always project_host bindings sync
|
||||
term_default_shell always project_host bindings sync
|
||||
term_is_busy always project_host bindings async
|
||||
term_kill always project_host bindings sync
|
||||
term_resize always project_host bindings sync
|
||||
term_spawn always project_host bindings async
|
||||
term_store_image always project_host bindings async
|
||||
term_write always project_host bindings sync
|
||||
tools_install trusted project_host bindings async
|
||||
tools_list trusted project_host bindings async
|
||||
tools_uninstall trusted project_host bindings async
|
||||
tools_updates trusted project_host bindings async
|
||||
undo_workspace_edit always project_host bindings async
|
||||
user_font_data always desktop - async
|
||||
vcs_add_to_ignore trusted project_host bindings async
|
||||
vcs_add_worktree trusted project_host bindings async
|
||||
vcs_apply_patch trusted project_host bindings async
|
||||
vcs_blame always project_host bindings async
|
||||
vcs_block_history always project_host bindings async
|
||||
vcs_branch_info always project_host bindings async
|
||||
vcs_branches always project_host bindings async
|
||||
vcs_changelists_load always project_host bindings async
|
||||
vcs_changelists_save trusted project_host bindings sync
|
||||
vcs_checkout trusted project_host bindings async
|
||||
vcs_clone always project_host bindings async
|
||||
vcs_commit trusted project_host bindings async
|
||||
vcs_commit_files always project_host bindings async
|
||||
vcs_commits_changes always project_host bindings async
|
||||
vcs_compare_paths always project_host bindings async
|
||||
vcs_compare_scope always project_host bindings async
|
||||
vcs_config_get always project_host bindings async
|
||||
vcs_conflict_versions always project_host bindings async
|
||||
vcs_create_branch trusted project_host bindings async
|
||||
vcs_create_patch trusted project_host bindings async
|
||||
vcs_create_tag trusted project_host bindings async
|
||||
vcs_delete_branch trusted project_host bindings async
|
||||
vcs_delete_tag trusted project_host bindings async
|
||||
vcs_detected_git always project_host bindings sync
|
||||
vcs_diff_hunks always project_host bindings async
|
||||
vcs_diff_numstat always project_host bindings async
|
||||
vcs_diff_revisions always project_host bindings async
|
||||
vcs_diff_text always project_host bindings async
|
||||
vcs_diff_with_worktree always project_host bindings async
|
||||
vcs_discard trusted project_host bindings async
|
||||
vcs_edit_remote trusted project_host bindings async
|
||||
vcs_file_at always project_host bindings async
|
||||
vcs_file_mode trusted project_host bindings async
|
||||
vcs_git_version trusted project_host bindings async
|
||||
vcs_has_hook always project_host bindings async
|
||||
vcs_ignore_blame_revision trusted project_host bindings async
|
||||
vcs_init always project_host bindings async
|
||||
vcs_line_hunks always project_host bindings async
|
||||
vcs_log always project_host bindings async
|
||||
vcs_log_details always project_host bindings async
|
||||
vcs_log_details_batch always project_host bindings async
|
||||
vcs_log_refs always project_host bindings async
|
||||
vcs_log_users always project_host bindings async
|
||||
vcs_merge trusted project_host bindings async
|
||||
vcs_merge_base always project_host bindings async
|
||||
vcs_merge_with trusted project_host bindings async
|
||||
vcs_move_worktree trusted project_host bindings async
|
||||
vcs_open_external_log always project_host bindings async
|
||||
vcs_operation trusted project_host bindings async
|
||||
vcs_patch_preview trusted project_host bindings async
|
||||
vcs_rebase trusted project_host bindings async
|
||||
vcs_rebase_with trusted project_host bindings async
|
||||
vcs_remote trusted project_host bindings async
|
||||
vcs_remotes always project_host bindings async
|
||||
vcs_remove_worktree trusted project_host bindings async
|
||||
vcs_rename_branch trusted project_host bindings async
|
||||
vcs_restore_branch trusted project_host bindings async
|
||||
vcs_restore_head trusted project_host bindings async
|
||||
vcs_restore_tag trusted project_host bindings async
|
||||
vcs_revision_children always project_host bindings async
|
||||
vcs_revision_files always project_host bindings async
|
||||
vcs_reword trusted project_host bindings async
|
||||
vcs_roots always project_host bindings sync
|
||||
vcs_shelf_delete trusted project_host bindings async
|
||||
vcs_shelf_diff trusted project_host bindings async
|
||||
vcs_shelf_import trusted project_host bindings async
|
||||
vcs_shelf_patch always project_host bindings async
|
||||
vcs_shelf_rename trusted project_host bindings async
|
||||
vcs_shelve trusted project_host bindings async
|
||||
vcs_shelves always project_host bindings async
|
||||
vcs_stage trusted project_host bindings async
|
||||
vcs_stage_hunks trusted project_host bindings async
|
||||
vcs_stage_patch trusted project_host bindings async
|
||||
vcs_stash_apply trusted project_host bindings async
|
||||
vcs_stash_drop trusted project_host bindings async
|
||||
vcs_stash_push trusted project_host bindings async
|
||||
vcs_stashes always project_host bindings async
|
||||
vcs_status always project_host bindings async
|
||||
vcs_status_paths always project_host bindings async
|
||||
vcs_tags always project_host bindings async
|
||||
vcs_undo_commit trusted project_host bindings async
|
||||
vcs_unshelve trusted project_host bindings async
|
||||
vcs_unstage trusted project_host bindings async
|
||||
vcs_worktrees always project_host bindings async
|
||||
vcs_write_patch always project_host bindings async
|
||||
web_browsers always desktop bindings async
|
||||
web_goto always project_host bindings async
|
||||
web_open always desktop bindings async
|
||||
web_serves_page trusted desktop bindings async
|
||||
web_unresolved_references always project_host bindings async
|
||||
web_url always project_host bindings async
|
||||
window_close_context always desktop bindings sync
|
||||
window_complete_launch always desktop bindings sync
|
||||
window_cycle always desktop bindings sync
|
||||
window_flash_taskbar always desktop bindings sync
|
||||
window_group_cancel_close always desktop bindings sync
|
||||
window_group_close always desktop bindings sync
|
||||
window_group_close_tabs always desktop bindings sync
|
||||
window_group_current always desktop bindings sync
|
||||
window_group_detach always desktop bindings async
|
||||
window_group_merge always desktop bindings async
|
||||
window_group_reorder always desktop bindings async
|
||||
window_group_restore always desktop bindings async
|
||||
window_group_select always desktop bindings async
|
||||
window_is_fullscreen always desktop bindings sync
|
||||
window_new always desktop bindings async
|
||||
window_open_comparison always desktop bindings async
|
||||
window_open_deployment always desktop bindings async
|
||||
window_open_diff always desktop bindings async
|
||||
window_open_file_in_new_window always desktop bindings async
|
||||
window_open_files always desktop bindings async
|
||||
window_open_project always desktop bindings async
|
||||
window_open_projects always desktop bindings sync
|
||||
window_open_remote always desktop bindings async
|
||||
window_open_settings always desktop bindings async
|
||||
window_set_titlebar_height always desktop bindings sync
|
||||
window_start_drag always desktop bindings sync
|
||||
window_take_launch always desktop bindings sync
|
||||
window_toggle_fullscreen always desktop bindings sync
|
||||
window_toggle_zoom always desktop bindings sync
|
||||
workspace_attach always desktop bindings async
|
||||
workspace_create always desktop bindings async
|
||||
workspace_discover_projects always desktop bindings async
|
||||
workspace_update always desktop bindings async
|
||||
wsl_distros always desktop bindings async
|
||||
wsl_resolve always desktop bindings sync
|
||||
@@ -1,7 +1,98 @@
|
||||
//! `cargo test -p openidea --test export_bindings` regenerates `src/bindings.ts`
|
||||
//! without launching the app (used by `pnpm gen:bindings` and CI drift checks).
|
||||
//! `cargo test -p openidea --test export_bindings` regenerates `src/bindings.ts` and
|
||||
//! `src-tauri/tests/commands.snap` without launching the app (used by `pnpm gen:bindings`
|
||||
//! and CI drift checks).
|
||||
|
||||
use ide_host::trust::{projectless_command_allowed, restricted_command_allowed};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::Path;
|
||||
use tauri_specta::{BuilderConfiguration, LanguageExt};
|
||||
|
||||
#[test]
|
||||
fn export_bindings() {
|
||||
openidea_lib::export_bindings(&openidea_lib::specta_builder());
|
||||
}
|
||||
|
||||
/// Commands registered outside tauri-specta (`src-tauri/src/lib.rs`), with how Tauri runs them.
|
||||
const RAW_COMMANDS: &[(&str, &str)] = &[("user_font_data", "async")];
|
||||
|
||||
/// Every command, one line each: its trust class, where a remote window runs it, whether it is
|
||||
/// in `bindings.ts`, and how Tauri runs it. A change to any of these shows up in this file's diff.
|
||||
#[test]
|
||||
fn export_command_snapshot() {
|
||||
let target = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/commands.snap");
|
||||
let fresh = std::env::temp_dir().join(format!("openidea-commands-{}.snap", std::process::id()));
|
||||
openidea_lib::specta_builder().export(CommandSnapshot, &fresh).expect("command snapshot");
|
||||
let text = std::fs::read(&fresh).expect("exported command snapshot");
|
||||
let _ = std::fs::remove_file(&fresh);
|
||||
if std::fs::read(&target).ok().as_deref() != Some(text.as_slice()) {
|
||||
std::fs::write(&target, text).expect("failed to write the command snapshot");
|
||||
}
|
||||
}
|
||||
|
||||
struct CommandSnapshot;
|
||||
|
||||
impl LanguageExt for CommandSnapshot {
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn export(self, cfg: &BuilderConfiguration, path: &Path) -> std::io::Result<()> {
|
||||
let spawned = spawned_commands();
|
||||
let mut modes: BTreeMap<&str, &str> = cfg
|
||||
.commands
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let mode = if spawned.contains(f.name()) {
|
||||
"spawn"
|
||||
} else if f.asyncness() {
|
||||
"async"
|
||||
} else {
|
||||
"sync"
|
||||
};
|
||||
(f.name(), mode)
|
||||
})
|
||||
.collect();
|
||||
let in_bindings: BTreeSet<&str> = modes.keys().copied().collect();
|
||||
modes.extend(RAW_COMMANDS.iter().copied());
|
||||
let routed: BTreeSet<&str> = ide_host::rpc::client_commands().into_iter().collect();
|
||||
let names: BTreeSet<&str> = modes.keys().chain(&routed).copied().collect();
|
||||
|
||||
let mut out = String::from(
|
||||
"# Generated by `pnpm gen:bindings`; do not edit. One line per command:\n\
|
||||
# name, trust class, placement in a remote window, in bindings.ts, how Tauri runs it.\n",
|
||||
);
|
||||
for name in names {
|
||||
let trust = if restricted_command_allowed(name) {
|
||||
"always"
|
||||
} else if projectless_command_allowed(name) {
|
||||
"outside_restricted"
|
||||
} else {
|
||||
"trusted"
|
||||
};
|
||||
let placement = if routed.contains(name) { "project_host" } else { "desktop" };
|
||||
let bindings = if in_bindings.contains(name) { "bindings" } else { "-" };
|
||||
let mode = modes.get(name).copied().unwrap_or("-");
|
||||
out.push_str(&format!("{name:<44} {trust:<18} {placement:<12} {bindings:<8} {mode}\n"));
|
||||
}
|
||||
std::fs::write(path, out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Sync commands declared `#[tauri::command(async)]`, which Tauri runs off the main thread.
|
||||
fn spawned_commands() -> BTreeSet<String> {
|
||||
let mut out = BTreeSet::new();
|
||||
let mut dirs = vec![Path::new(env!("CARGO_MANIFEST_DIR")).join("src")];
|
||||
while let Some(dir) = dirs.pop() {
|
||||
for entry in std::fs::read_dir(&dir).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.is_dir() {
|
||||
dirs.push(path);
|
||||
continue;
|
||||
}
|
||||
let source = std::fs::read_to_string(&path).unwrap_or_default();
|
||||
for (_, rest) in source.match_indices("#[tauri::command(async)]").map(|(i, _)| source.split_at(i)) {
|
||||
let name = rest.split("fn ").nth(1).and_then(|s| s.split('(').next());
|
||||
out.insert(name.expect("a function after #[tauri::command(async)]").trim().to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
+18
-4
@@ -310,9 +310,14 @@ export const commands = {
|
||||
/** Whether the clipboard holds files: cheap, for the Paste item's enabled state. */
|
||||
clipboardHasFiles: () => __TAURI_INVOKE<boolean>("clipboard_has_files"),
|
||||
/**
|
||||
* The clipboard's image as a PNG data URL, for a paste whose event carried no
|
||||
* files: WebKitGTK leaves `clipboardData` empty for a raw image (a screenshot).
|
||||
* None when the clipboard holds no image, and always on other platforms.
|
||||
* Whether the clipboard holds an image (a screenshot): cheap, for the Paste item's
|
||||
* enabled state.
|
||||
*/
|
||||
clipboardHasImage: () => __TAURI_INVOKE<boolean>("clipboard_has_image"),
|
||||
/**
|
||||
* The clipboard's image as a PNG data URL: for a paste whose event carried no files
|
||||
* (WebKitGTK leaves `clipboardData` empty for a raw image, a screenshot), and for
|
||||
* the project view's Paste, which has no paste event. None when it holds no image.
|
||||
*/
|
||||
clipboardImage: () => typedError<string | null, IdeError>(__TAURI_INVOKE("clipboard_image")),
|
||||
/**
|
||||
@@ -708,6 +713,8 @@ export const commands = {
|
||||
mode?: CheckoutMode,
|
||||
/** Required when checking out a remote branch whose local namesake is ahead of it. */
|
||||
diverged?: DivergedLocal | null,
|
||||
/** Check the branch out even though another worktree has it checked out. */
|
||||
ignoreOtherWorktrees?: boolean,
|
||||
} | null) => typedError<CheckoutOutcome, IdeError>(__TAURI_INVOKE("vcs_checkout", { repo, branch, create, options })),
|
||||
vcsDeleteBranch: (repo: string | null, branch: string) => typedError<DeletedBranch, IdeError>(__TAURI_INVOKE("vcs_delete_branch", { repo, branch })),
|
||||
/** "Restore" of the branch-deleted notification. */
|
||||
@@ -2980,6 +2987,8 @@ export type CheckoutOptions = {
|
||||
mode?: CheckoutMode,
|
||||
/** Required when checking out a remote branch whose local namesake is ahead of it. */
|
||||
diverged?: DivergedLocal | null,
|
||||
/** Check the branch out even though another worktree has it checked out. */
|
||||
ignoreOtherWorktrees?: boolean,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -2997,7 +3006,12 @@ export type CheckoutOutcome = { kind: "done" } |
|
||||
* Switched, but restoring the local changes (Smart Checkout) or the rebase stopped
|
||||
* on conflicts in these files.
|
||||
*/
|
||||
{ kind: "conflicts"; files: string[] };
|
||||
{ kind: "conflicts"; files: string[] } |
|
||||
/**
|
||||
* Git refused: `branch` is checked out in the linked worktree at `path`. Nothing
|
||||
* changed; the branch can be worked on there.
|
||||
*/
|
||||
{ kind: "checkedOutInWorktree"; branch: string; path: string };
|
||||
|
||||
export type ChoiceOption = {
|
||||
value: string,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { DocModel } from "./model/document";
|
||||
import { readOnlyQuestion, toggleReadOnly } from "./fileAttributes";
|
||||
import { offerMakeWritable, readOnlyQuestion, toggleReadOnly } from "./fileAttributes";
|
||||
|
||||
function model(readOnly: boolean, extra: Partial<{ virtual: boolean; banner: string | null }> = {}) {
|
||||
const meta = { readOnly, banner: extra.banner ?? (readOnly ? "readOnly" : null) };
|
||||
@@ -43,3 +43,27 @@ describe("Toggle Read-only Attribute", () => {
|
||||
expect(readOnlyQuestion("a.txt", false).confirm).toBe("Make Read-only");
|
||||
});
|
||||
});
|
||||
|
||||
describe("editing a read-only file", () => {
|
||||
it("offers to make it writable once, then lets edits through", async () => {
|
||||
const m = model(true);
|
||||
answer = true;
|
||||
expect(offerMakeWritable(m)).toBe(true);
|
||||
expect(offerMakeWritable(m)).toBe(true);
|
||||
expect(confirm).toHaveBeenCalledTimes(1);
|
||||
expect(confirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Make File Writable" }));
|
||||
await vi.waitFor(() => expect(m.setReadOnly).toHaveBeenCalledWith(false));
|
||||
expect(offerMakeWritable(m)).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses edits without asking for library, binary and too-large documents", () => {
|
||||
for (const m of [
|
||||
model(true, { virtual: true }),
|
||||
model(true, { banner: "binary" }),
|
||||
model(true, { banner: "tooLarge" }),
|
||||
])
|
||||
expect(offerMakeWritable(m)).toBe(true);
|
||||
expect(confirm).not.toHaveBeenCalled();
|
||||
expect(offerMakeWritable(model(false))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* File › File Properties › Make File Read-only / Writable (IDEA's "Toggle
|
||||
* Read-only Attribute", also the status bar lock): asks, then flips the
|
||||
* file's writable bit and the open document's editability.
|
||||
* file's writable bit and the open document's editability. Typing into a file
|
||||
* whose read-only attribute is set asks the same (IDEA's Clear Read-Only Status).
|
||||
*/
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { basename } from "@/platform/project";
|
||||
@@ -41,3 +42,22 @@ export function toggleReadOnly(model: DocModel) {
|
||||
(ok) => ok && void setFileWritable(model, meta.readOnly),
|
||||
);
|
||||
}
|
||||
|
||||
let asking: DocModel | null = null;
|
||||
|
||||
/**
|
||||
* An edit was attempted in `model`. When only the file's read-only attribute is in the
|
||||
* way (not a binary, too large or library file), offers to make it writable, once at a
|
||||
* time. Returns whether the edit was refused: the caller drops it either way.
|
||||
*/
|
||||
export function offerMakeWritable(model: DocModel): boolean {
|
||||
const meta = model.getMeta();
|
||||
if (!meta.readOnly) return false;
|
||||
if (model.virtual || meta.banner !== "readOnly" || asking) return true;
|
||||
asking = model;
|
||||
const q = readOnlyQuestion(basename(model.path), true);
|
||||
void confirm({ title: q.title, message: q.message, ok: q.confirm })
|
||||
.then((ok) => ok && model.getMeta().readOnly && setFileWritable(model, true))
|
||||
.finally(() => (asking = null));
|
||||
return true;
|
||||
}
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
import { showContextMenu } from "@/ui";
|
||||
import { baseExtensions, compartments, contributionExtensions } from "../cm/setup";
|
||||
import { gutterMenuItems, inGutterMenuArea } from "../gutterMenu";
|
||||
import { offerMakeWritable } from "../fileAttributes";
|
||||
import type { DocModel } from "./document";
|
||||
import type { WorkspaceHistoryTarget } from "./workspaceHistory";
|
||||
import { isNavigation } from "./navHistory";
|
||||
@@ -147,6 +148,12 @@ export class EditorSlot {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
private refuseReadOnlyEdit(e: Event): boolean {
|
||||
if (!offerMakeWritable(this.model)) return false;
|
||||
e.preventDefault();
|
||||
return true;
|
||||
}
|
||||
|
||||
private slotExtensions() {
|
||||
return [
|
||||
this.model.manager.workspaceHistory.extension(this.historyTarget),
|
||||
@@ -169,6 +176,10 @@ export class EditorSlot {
|
||||
this.host.onContextMenu(this, e);
|
||||
return true;
|
||||
},
|
||||
// Typing, pasting or dropping into a read-only file offers to make it writable.
|
||||
beforeinput: (e) => this.refuseReadOnlyEdit(e),
|
||||
paste: (e) => this.refuseReadOnlyEdit(e),
|
||||
drop: (e) => this.refuseReadOnlyEdit(e),
|
||||
}),
|
||||
ViewPlugin.define((view) => {
|
||||
// Gutters sit outside the content DOM. Gutter extensions with their own menu (breakpoints,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState, StateEffect, type Extension } from "@codemirror/state";
|
||||
import { EditorView, runScopeHandlers } from "@codemirror/view";
|
||||
import type { CompletionItem } from "@/bindings";
|
||||
import type { EditorDocContext } from "@/editor/api";
|
||||
import { remoteChange, type EditorDocContext } from "@/editor/api";
|
||||
import { lspDoc } from "./lsp";
|
||||
import { insertTab, tabOut, tabOutOfScope } from "@/editor/core/cm/smartKeys";
|
||||
import {
|
||||
@@ -294,6 +294,32 @@ describe("applying completions", () => {
|
||||
await vi.waitFor(() => expect(view.state.selection.main.head).toBe(17));
|
||||
});
|
||||
|
||||
it("leaves an item its server inserts to the server, and puts the caret after what it inserted", async () => {
|
||||
const executed: string[] = [];
|
||||
setInvokeRoute((cmd) => {
|
||||
executed.push(cmd);
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
try {
|
||||
const { view, req } = setup("p.ref|\n", "", [completionExtension()]);
|
||||
view.dispatch({ effects: StateEffect.appendConfig.of(lspDoc.of({ doc: 1 } as EditorDocContext)) });
|
||||
// kotlin-lsp: an empty text, inserted by `jetbrains.kotlin.completion.apply` as a workspace edit.
|
||||
const command = { title: "Apply Completion", command: "jetbrains.kotlin.completion.apply", arguments: ["1"] };
|
||||
const kotlin = item({ label: "refreshName", labelDetail: "()", insertText: "", command });
|
||||
applyLspCompletion(view, makeCompletion(kotlin, req), 5, 5, "insert");
|
||||
expect(view.state.doc.toString()).toBe("p.ref\n");
|
||||
await vi.waitFor(() => expect(executed).toContain("lsp_execute_command"));
|
||||
view.dispatch({ changes: { from: 5, insert: "reshName()" }, annotations: remoteChange.of(true) });
|
||||
expect(view.state.doc.toString()).toBe("p.refreshName()\n");
|
||||
expect(view.state.selection.main.head).toBe(15);
|
||||
// Later edits from elsewhere leave the caret alone.
|
||||
view.dispatch({ changes: { from: 15, insert: " " }, annotations: remoteChange.of(true) });
|
||||
expect(view.state.selection.main.head).toBe(15);
|
||||
} finally {
|
||||
setInvokeRoute(null);
|
||||
}
|
||||
});
|
||||
|
||||
it("does not register a scope when jumping outside closing brackets is off", () => {
|
||||
const { view, req } = setup("service.cr|");
|
||||
applyLspCompletion(view, makeCompletion(item(), req), 8, 10, "insert");
|
||||
@@ -532,6 +558,7 @@ describe("insert parentheses", () => {
|
||||
expect(callParens(item({ kind: "field" }), line("a.cr"), 2, 4)).toBeNull();
|
||||
expect(callParens(item({ isSnippet: true }), line("a.cr"), 2, 4)).toBeNull();
|
||||
expect(callParens(item({ insertText: "create()" }), line("a.cr"), 2, 4)).toBeNull();
|
||||
expect(callParens(item({ insertText: "" }), line("a.cr"), 4, 4)).toBeNull();
|
||||
});
|
||||
|
||||
it("skips calls that already have parentheses and imports", () => {
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
type CompletionResult,
|
||||
type CompletionSource,
|
||||
} from "@codemirror/autocomplete";
|
||||
import { EditorSelection, Prec, type Text } from "@codemirror/state";
|
||||
import { EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state";
|
||||
import { EditorView, ViewPlugin, keymap, type ViewUpdate } from "@codemirror/view";
|
||||
import {
|
||||
call,
|
||||
@@ -58,6 +58,7 @@ import { tx } from "@/platform/i18n";
|
||||
import { showHint } from "./hint";
|
||||
import { inplaceRenameActive } from "./inplaceRename";
|
||||
import { languageSemantics } from "./semantic";
|
||||
import { remoteChange } from "@/editor/api";
|
||||
|
||||
interface RequestContext {
|
||||
doc: number;
|
||||
@@ -297,7 +298,9 @@ export function callParens(
|
||||
start: number,
|
||||
end: number,
|
||||
): "inside" | "after" | null {
|
||||
if (item.isSnippet || !item.kind || !CALLABLE.has(item.kind) || /[(<[{]/.test(item.insertText)) return null;
|
||||
// An empty text is inserted by the item's server command (kotlin-lsp), parentheses included.
|
||||
if (item.isSnippet || !item.kind || !CALLABLE.has(item.kind) || !item.insertText || /[(<[{]/.test(item.insertText))
|
||||
return null;
|
||||
const next = line.text.charAt(end - line.from);
|
||||
if (next && /[(\p{L}\p{N}_$'"`]/u.test(next)) return null;
|
||||
if (IMPORT_LINE.test(line.text.slice(0, start - line.from))) return null;
|
||||
@@ -322,6 +325,33 @@ async function applyLateEdits(view: EditorView, c: LspCompletion, insertedAt: nu
|
||||
view.dispatch({ changes: edits, userEvent: "input.complete" });
|
||||
}
|
||||
|
||||
/** Where the caret was when an item its server inserts was picked, until that edit lands (`null`: none). */
|
||||
const awaitServerInsert = StateEffect.define<number | null>();
|
||||
const serverInsertAt = StateField.define<number | null>({
|
||||
create: () => null,
|
||||
update(at, tr) {
|
||||
for (const e of tr.effects) if (e.is(awaitServerInsert)) return e.value;
|
||||
// The edit landed, or the caret moved on before it did.
|
||||
if (at === null || tr.annotation(remoteChange) || tr.selection) return null;
|
||||
return tr.changes.mapPos(at, -1);
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* The server's edit inserts the item at the caret: the caret goes after it, as after any other
|
||||
* completion (a remote insertion at the caret would otherwise leave it in front).
|
||||
*/
|
||||
const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
|
||||
const at = tr.startState.field(serverInsertAt, false);
|
||||
const caret = tr.startState.selection.main;
|
||||
if (at == null || !tr.docChanged || !tr.annotation(remoteChange) || !caret.empty || caret.head !== at) return tr;
|
||||
let inserted = false;
|
||||
tr.changes.iterChangedRanges((fromA, toA) => {
|
||||
if (fromA <= at && toA >= at) inserted = true;
|
||||
});
|
||||
return inserted ? [tr, { selection: EditorSelection.cursor(tr.changes.mapPos(at, 1)), sequential: true }] : tr;
|
||||
});
|
||||
|
||||
/** Client-side commands handled by the editor itself (VS Code ids servers commonly send). */
|
||||
const CLIENT_COMMANDS = new Set(["editor.action.triggerParameterHints", "editor.action.triggerSuggest"]);
|
||||
|
||||
@@ -329,18 +359,30 @@ function runCommand(view: EditorView, item: CompletionItem) {
|
||||
const command = item.command;
|
||||
if (!command?.command) return;
|
||||
const cmd = command.command;
|
||||
// kotlin-lsp inserts the item itself (`jetbrains.kotlin.completion.apply`): nothing went in here.
|
||||
const serverInserted = !item.insertText && !CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.");
|
||||
if (serverInserted) view.dispatch({ effects: awaitServerInsert.of(view.state.selection.main.head) });
|
||||
if (cmd === "editor.action.triggerParameterHints") setTimeout(() => triggerSignatureHelp(view), 0);
|
||||
else if (cmd === "editor.action.triggerSuggest") setTimeout(() => startCompletion(view), 0);
|
||||
else if (!CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.")) {
|
||||
const doc = docOf(view);
|
||||
// Server commands (auto-import, postfix…); resulting edits come back as workspace/applyEdit.
|
||||
if (doc)
|
||||
void lspRequest(() => commands.lspExecuteCommand(doc.doc, command)).catch((e: unknown) =>
|
||||
reportLspError(view, e, false),
|
||||
);
|
||||
void lspRequest(() => commands.lspExecuteCommand(doc.doc, command))
|
||||
.catch((e: unknown) => reportLspError(view, e, false))
|
||||
.finally(() => {
|
||||
// The edit arrives before the command's answer; allow for the document update.
|
||||
if (serverInserted)
|
||||
setTimeout(() => {
|
||||
if (view.dom.isConnected && view.state.field(serverInsertAt, false) != null)
|
||||
view.dispatch({ effects: awaitServerInsert.of(null) });
|
||||
}, SERVER_INSERT_WAIT_MS);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const SERVER_INSERT_WAIT_MS = 1000;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Source
|
||||
|
||||
@@ -828,6 +870,8 @@ export function completionExtension() {
|
||||
}),
|
||||
completionFooter,
|
||||
lookupTracker,
|
||||
serverInsertAt,
|
||||
caretAfterServerInsert,
|
||||
Prec.highest(
|
||||
keymap.of([
|
||||
// macOS: ⌃N / ⌃P are line down / up in text, so they move through the lookup as ↓ / ↑ do.
|
||||
|
||||
@@ -216,7 +216,10 @@ const hoverYieldsToNavigation = ViewPlugin.fromClass(
|
||||
|
||||
export function hoverExtension(): Extension {
|
||||
return [
|
||||
hoverTooltip(hoverSource, { hoverTime: Math.max(100, editorPrefs().codeEditing.quickDocDelay) }),
|
||||
hoverTooltip(hoverSource, {
|
||||
hoverTime: Math.max(100, editorPrefs().codeEditing.quickDocDelay),
|
||||
hideOnChange: true,
|
||||
}),
|
||||
hoverYieldsToNavigation,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ import {
|
||||
} from "./composerModel";
|
||||
import { ConfigPickers } from "./ConfigPickers";
|
||||
import { useEffortFocus } from "./effortFocus";
|
||||
import { findRanges, formatDuration, formatSentAt } from "./conversation";
|
||||
import { findRanges, formatDuration, formatSentAt, isFindRangeShown } from "./conversation";
|
||||
import { ImagePreview, imageSrc } from "./ImagePreview";
|
||||
import { useAgentSettings } from "./agentSettings";
|
||||
import { foldedTurns, summarizeWork, workParts, type FoldedTurn, type WorkSummary } from "./timeline";
|
||||
@@ -594,10 +594,15 @@ function SubagentBar({
|
||||
* doesn't jump (WebKit has no scroll anchoring). A new width lays them out again once it
|
||||
* settles; Find in Conversation (`enabled` false) needs every row laid out.
|
||||
*/
|
||||
function useOffscreenRows(ref: RefObject<HTMLElement | null>, visible: boolean, enabled: boolean) {
|
||||
// The width the marked rows were laid out at.
|
||||
const width = useRef(0);
|
||||
useEffect(() => {
|
||||
function useOffscreenRows(
|
||||
ref: RefObject<HTMLElement | null>,
|
||||
visible: boolean,
|
||||
enabled: boolean,
|
||||
fitWindowWidth: boolean,
|
||||
) {
|
||||
// The container width and column mode the marked rows were laid out at.
|
||||
const measured = useRef<{ width: number; fitWindowWidth: boolean } | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const unmark = () => {
|
||||
@@ -605,10 +610,26 @@ function useOffscreenRows(ref: RefObject<HTMLElement | null>, visible: boolean,
|
||||
row.removeAttribute("data-measured");
|
||||
}
|
||||
};
|
||||
if (!enabled) return unmark();
|
||||
if (!enabled) {
|
||||
measured.current = null;
|
||||
unmark();
|
||||
return;
|
||||
}
|
||||
if (!visible) return;
|
||||
if (measured.current?.width === el.clientWidth && measured.current.fitWindowWidth === fitWindowWidth) return;
|
||||
measured.current = { width: el.clientWidth, fitWindowWidth };
|
||||
unmark();
|
||||
}, [ref, visible, enabled, fitWindowWidth]);
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el || !enabled || !visible) return;
|
||||
let frame = 0;
|
||||
let timer: number | undefined;
|
||||
const unmark = () => {
|
||||
for (const row of el.querySelectorAll(`:scope > .${styles.conversationRow}[data-measured]`)) {
|
||||
row.removeAttribute("data-measured");
|
||||
}
|
||||
};
|
||||
const mark = () => {
|
||||
cancelAnimationFrame(frame);
|
||||
// The next frame lays the new rows out (and remembers their size); mark them after it.
|
||||
@@ -621,8 +642,8 @@ function useOffscreenRows(ref: RefObject<HTMLElement | null>, visible: boolean,
|
||||
});
|
||||
};
|
||||
const remeasure = () => {
|
||||
if (el.clientWidth === width.current) return;
|
||||
width.current = el.clientWidth;
|
||||
if (measured.current?.width === el.clientWidth && measured.current.fitWindowWidth === fitWindowWidth) return;
|
||||
measured.current = { width: el.clientWidth, fitWindowWidth };
|
||||
unmark();
|
||||
};
|
||||
remeasure();
|
||||
@@ -643,7 +664,7 @@ function useOffscreenRows(ref: RefObject<HTMLElement | null>, visible: boolean,
|
||||
rows.disconnect();
|
||||
resize.disconnect();
|
||||
};
|
||||
}, [ref, visible, enabled]);
|
||||
}, [ref, visible, enabled, fitWindowWidth]);
|
||||
}
|
||||
|
||||
interface StreamProps {
|
||||
@@ -765,7 +786,8 @@ function Stream({ loadError, task, entries, subagent, onOpenSubagent, finding, f
|
||||
}, [start]);
|
||||
// Hidden behind another tab, it has no layout to scroll; shown again, it follows the end again.
|
||||
const visible = useEditorShown();
|
||||
useOffscreenRows(ref, visible, !finding);
|
||||
const { foldTurns, toolCalls, fitWindowWidth } = useAgentSettings();
|
||||
useOffscreenRows(ref, visible, !finding, fitWindowWidth);
|
||||
/** A diagram that drew after the last streamed chunk grows the conversation: keep following. */
|
||||
const onDiagramDrawn = useCallback(() => {
|
||||
const el = ref.current;
|
||||
@@ -874,7 +896,6 @@ function Stream({ loadError, task, entries, subagent, onOpenSubagent, finding, f
|
||||
const busy = subagent ? subagentWorking(subagent.status) : isBusy(task.status);
|
||||
const lastIndex = entries ? entries.length - 1 : -1;
|
||||
// Keep the row stable when earlier history is prepended; its author can move with the work.
|
||||
const { foldTurns, toolCalls } = useAgentSettings();
|
||||
const rows = useMemo(() => {
|
||||
if (!entries) return [];
|
||||
const rows = conversationRows(entries, start, toolCalls === "grouped");
|
||||
@@ -1121,14 +1142,9 @@ interface RangeSet {
|
||||
clear(): void;
|
||||
add(range: Range): void;
|
||||
}
|
||||
const highlights = (globalThis as { CSS?: { highlights?: Map<string, RangeSet> } }).CSS?.highlights;
|
||||
const HighlightCtor = (globalThis as { Highlight?: new () => RangeSet }).Highlight;
|
||||
|
||||
/**
|
||||
* Sets the ranges of highlight `name`. One registered highlight per name, changed in
|
||||
* place: WebKit doesn't repaint where a replaced highlight object was.
|
||||
*/
|
||||
function setHighlight(name: string, ranges: Range[]) {
|
||||
const highlights = (globalThis as { CSS?: { highlights?: Map<string, RangeSet> } }).CSS?.highlights;
|
||||
const HighlightCtor = (globalThis as { Highlight?: new () => RangeSet }).Highlight;
|
||||
if (!highlights || !HighlightCtor) return;
|
||||
let set = highlights.get(name);
|
||||
if (!set) {
|
||||
@@ -1204,12 +1220,15 @@ function FindBar({
|
||||
return () => stream?.removeEventListener("toggle", toggled, true);
|
||||
}, [streamRef]);
|
||||
useEffect(() => {
|
||||
// Only rendered matches: WebKit paints those in collapsed <details> over the text next to them.
|
||||
const visible = (r: Range) => r.getClientRects().length > 0;
|
||||
const stream = streamRef.current;
|
||||
if (!stream) return;
|
||||
// Only rendered selectable matches outside closed <details>: WebKit paints unrendered
|
||||
// or user-select:none ranges in CSS.highlights over the next selectable row instead.
|
||||
const visible = (r: Range) => isFindRangeShown(r, stream);
|
||||
const current = index >= 0 ? ranges[index]! : null;
|
||||
setHighlight("agent-find", ranges.filter(visible));
|
||||
setHighlight("agent-find-current", current && visible(current) ? [current] : []);
|
||||
}, [ranges, index, shown]);
|
||||
}, [ranges, index, shown, streamRef]);
|
||||
useEffect(
|
||||
() => () => {
|
||||
setHighlight("agent-find", []);
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fileHref, findAll, findRanges, formatDuration, pathLink, quoteText, withQuote } from "./conversation";
|
||||
import {
|
||||
fileHref,
|
||||
findAll,
|
||||
findRanges,
|
||||
formatDuration,
|
||||
isFindRangeShown,
|
||||
pathLink,
|
||||
quoteText,
|
||||
withQuote,
|
||||
} from "./conversation";
|
||||
|
||||
describe("quoting", () => {
|
||||
it("quotes each line and leaves a line to type on", () => {
|
||||
@@ -84,4 +93,28 @@ describe("finding", () => {
|
||||
expect(findRanges(root, "one").map((r) => r.toString())).toEqual(["one", "one"]);
|
||||
expect(findRanges(root, "TWO")).toHaveLength(1);
|
||||
});
|
||||
it("skips user-select:none chrome, buttons, svgs and mermaid source, and hides ranges in closed <details>", () => {
|
||||
const root = document.createElement("div");
|
||||
root.innerHTML = [
|
||||
'<details><summary style="user-select: none">Confirming summary</summary><div>hidden confirm body</div></details>',
|
||||
"<details><summary>stop_bash confirm</summary><pre>tool confirm output</pre></details>",
|
||||
"<button>confirm button</button>",
|
||||
"<svg><text>confirm svg</text></svg>",
|
||||
'<div data-mermaid-state="ok"><pre><code>graph TD; confirm</code></pre></div>',
|
||||
"<p>Visible confirm</p>",
|
||||
].join("");
|
||||
const ranges = findRanges(root, "confirm");
|
||||
expect(ranges.map((r) => r.startContainer.parentElement?.tagName)).toEqual(["DIV", "SUMMARY", "PRE", "P"]);
|
||||
|
||||
// Simulate WebKit's content-visibility: hidden on closed <details>, where getClientRects() stays non-empty.
|
||||
for (const r of ranges) r.getClientRects = () => [new DOMRect(0, 0, 10, 10)] as unknown as DOMRectList;
|
||||
expect(ranges.filter((r) => isFindRangeShown(r, root)).map((r) => r.startContainer.parentElement?.tagName)).toEqual(
|
||||
["SUMMARY", "P"],
|
||||
);
|
||||
|
||||
for (const d of root.querySelectorAll("details")) d.open = true;
|
||||
expect(ranges.filter((r) => isFindRangeShown(r, root)).map((r) => r.startContainer.parentElement?.tagName)).toEqual(
|
||||
["DIV", "SUMMARY", "PRE", "P"],
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -93,11 +93,36 @@ export function findAll(text: string, query: string): number[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** DOM ranges of `query` in the text under `root` (matches within one text node). */
|
||||
const SKIP_FIND_TAGS = new Set(["STYLE", "SCRIPT", "NOSCRIPT", "SVG", "BUTTON"]);
|
||||
|
||||
function isUnselectable(el: Element): boolean {
|
||||
const style = getComputedStyle(el);
|
||||
return style.userSelect === "none" || style.webkitUserSelect === "none";
|
||||
}
|
||||
|
||||
/**
|
||||
* DOM ranges of `query` in the selectable text under `root` (matches within one text node).
|
||||
* Skips `user-select: none` chrome (`.thought summary`, `.processSummary`, `.messageTime`,
|
||||
* `.role`…): WebKit's `CSS.highlights` skips unselectable text renderers and paints the
|
||||
* highlight over the next selectable text node instead.
|
||||
*/
|
||||
export function findRanges(root: Node, query: string): Range[] {
|
||||
const out: Range[] = [];
|
||||
if (!query) return out;
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {
|
||||
acceptNode(node) {
|
||||
if (node.nodeType === Node.ELEMENT_NODE) {
|
||||
const el = node as Element;
|
||||
const tag = el.tagName.toUpperCase();
|
||||
if (SKIP_FIND_TAGS.has(tag)) return NodeFilter.FILTER_REJECT;
|
||||
if (tag === "PRE" && el.parentElement?.getAttribute("data-mermaid-state") === "ok")
|
||||
return NodeFilter.FILTER_REJECT;
|
||||
if (isUnselectable(el)) return NodeFilter.FILTER_REJECT;
|
||||
return NodeFilter.FILTER_SKIP;
|
||||
}
|
||||
return NodeFilter.FILTER_ACCEPT;
|
||||
},
|
||||
});
|
||||
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
||||
for (const at of findAll(node.textContent ?? "", query)) {
|
||||
const range = document.createRange();
|
||||
@@ -108,3 +133,20 @@ export function findRanges(root: Node, query: string): Range[] {
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when `range` is rendered on screen and not inside a collapsed `<details>` or
|
||||
* `user-select: none` subtree. WebKit hides closed `<details>` bodies with
|
||||
* `content-visibility: hidden` (where `getClientRects()` stays non-empty once opened)
|
||||
* and forwards unrendered or unselectable `CSS.highlights` ranges onto adjacent rows.
|
||||
*/
|
||||
export function isFindRangeShown(range: Range, root: Node): boolean {
|
||||
for (let el = range.startContainer.parentElement; el && el !== root; el = el.parentElement) {
|
||||
if (isUnselectable(el)) return false;
|
||||
if (el instanceof HTMLDetailsElement && !el.open) {
|
||||
const summary = el.querySelector(":scope > summary");
|
||||
if (!summary?.contains(range.startContainer)) return false;
|
||||
}
|
||||
}
|
||||
return range.getClientRects().length > 0;
|
||||
}
|
||||
@@ -540,20 +540,60 @@ describe("opened runs", () => {
|
||||
});
|
||||
|
||||
describe("folded content", () => {
|
||||
it("is rendered for Find in Conversation, so its text is found", async () => {
|
||||
backend.entries.set("A", [
|
||||
tool("one", { output: "needle in a tool output" }),
|
||||
tool("two"),
|
||||
{ type: "agent", text: "Answer A" },
|
||||
]);
|
||||
useAgents.setState({ entries: new Map(backend.entries) });
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
const summary = await screen.findByText("Read 2 files");
|
||||
expect(screen.queryByText("needle in a tool output")).toBeNull();
|
||||
fireEvent.focus(summary);
|
||||
act(() => focusedSession()!.openFind());
|
||||
expect(await screen.findByText("needle in a tool output")).toBeInTheDocument();
|
||||
expect(summary.closest("details")!.open).toBe(false);
|
||||
it("is rendered for Find in Conversation without painting closed <details> highlights until stepped into", async () => {
|
||||
const rectSpy = vi
|
||||
.spyOn(Range.prototype, "getClientRects")
|
||||
.mockImplementation(() => [new DOMRect(0, 0, 20, 12)] as unknown as DOMRectList);
|
||||
const prevCss = (globalThis as { CSS?: unknown }).CSS;
|
||||
const prevHighlight = (globalThis as { Highlight?: unknown }).Highlight;
|
||||
const highlights = new Map<string, Set<Range>>();
|
||||
if (typeof prevHighlight === "undefined") {
|
||||
(globalThis as { Highlight?: unknown }).Highlight = Set;
|
||||
}
|
||||
if (!(prevCss as { highlights?: unknown } | undefined)?.highlights) {
|
||||
(globalThis as { CSS?: unknown }).CSS = {
|
||||
...(typeof prevCss === "object" && prevCss ? prevCss : {}),
|
||||
highlights,
|
||||
};
|
||||
}
|
||||
try {
|
||||
backend.entries.set("A", [
|
||||
{ type: "thought", text: "Reviewing Changes\n\nConfirm the branch state before rebasing." },
|
||||
tool("one", { title: "stop_bash", output: "stopped" }),
|
||||
{ type: "agent", text: "Confirmed—PR is merged." },
|
||||
]);
|
||||
useAgents.setState({ entries: new Map(backend.entries) });
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
const runSummary = await screen.findByText("Read 1 file");
|
||||
const runDetails = runSummary.closest("details")!;
|
||||
runDetails.open = true;
|
||||
fireEvent(runDetails, new Event("toggle"));
|
||||
|
||||
const thoughtDetails = (await screen.findByText("Reviewing Changes")).closest("details")!;
|
||||
expect(thoughtDetails.open).toBe(false);
|
||||
|
||||
fireEvent.focus(runSummary);
|
||||
act(() => focusedSession()!.openFind());
|
||||
const findBox = await screen.findByLabelText("Find in Conversation");
|
||||
fireEvent.change(findBox, { target: { value: "confirm" } });
|
||||
|
||||
const registry = (globalThis as unknown as { CSS: { highlights: Map<string, Set<Range>> } }).CSS.highlights;
|
||||
await waitFor(() => expect(screen.getByText("1/2")).toBeInTheDocument());
|
||||
await waitFor(() => expect([...(registry.get("agent-find") ?? [])]).toHaveLength(1));
|
||||
expect([...(registry.get("agent-find") ?? [])][0]!.startContainer.textContent).toContain("Confirmed");
|
||||
expect([...(registry.get("agent-find-current") ?? [])]).toHaveLength(0);
|
||||
|
||||
fireEvent.keyDown(findBox, { key: "Enter" });
|
||||
fireEvent.keyDown(findBox, { key: "Enter" });
|
||||
fireEvent(thoughtDetails, new Event("toggle"));
|
||||
expect(thoughtDetails.open).toBe(true);
|
||||
await waitFor(() => expect([...(registry.get("agent-find") ?? [])]).toHaveLength(2));
|
||||
expect([...(registry.get("agent-find-current") ?? [])]).toHaveLength(1);
|
||||
} finally {
|
||||
rectSpy.mockRestore();
|
||||
(globalThis as { CSS?: unknown }).CSS = prevCss;
|
||||
(globalThis as { Highlight?: unknown }).Highlight = prevHighlight;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1817,30 +1857,57 @@ describe("meters in the task header", () => {
|
||||
expect(screen.getByText("$0.42")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("toggles fitWidth on the session root from settings.agents.fitWindowWidth", () => {
|
||||
const { container } = render(<SessionEditor input={input("A")} />);
|
||||
const root = container.querySelector(`.${styles.session}`)!;
|
||||
expect(root).not.toHaveClass(styles.fitWidth!);
|
||||
act(() =>
|
||||
useProject.setState({
|
||||
settings: {
|
||||
agents: {
|
||||
fitWindowWidth: true,
|
||||
},
|
||||
} as never,
|
||||
}),
|
||||
);
|
||||
expect(root).toHaveClass(styles.fitWidth!);
|
||||
act(() =>
|
||||
useProject.setState({
|
||||
settings: {
|
||||
agents: {
|
||||
fitWindowWidth: false,
|
||||
},
|
||||
} as never,
|
||||
}),
|
||||
);
|
||||
expect(root).not.toHaveClass(styles.fitWidth!);
|
||||
it("toggles fitWidth on the session root and remeasures off-screen rows from settings.agents.fitWindowWidth", async () => {
|
||||
const frames: FrameRequestCallback[] = [];
|
||||
const raf = vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => {
|
||||
frames.push(cb);
|
||||
return frames.length;
|
||||
});
|
||||
const flushFrames = () => {
|
||||
for (let pass = 0; pass < 2; pass++) {
|
||||
for (const cb of frames.splice(0)) cb(performance.now());
|
||||
}
|
||||
};
|
||||
try {
|
||||
const { container } = render(<SessionEditor input={input("A")} />);
|
||||
await screen.findByText("Answer A");
|
||||
const root = container.querySelector(`.${styles.session}`)!;
|
||||
const row = container.querySelector(`.${styles.conversationRow}`)!;
|
||||
act(flushFrames);
|
||||
expect(root).not.toHaveClass(styles.fitWidth!);
|
||||
expect(row).toHaveAttribute("data-measured");
|
||||
|
||||
act(() =>
|
||||
useProject.setState({
|
||||
settings: {
|
||||
agents: {
|
||||
fitWindowWidth: true,
|
||||
},
|
||||
} as never,
|
||||
}),
|
||||
);
|
||||
expect(root).toHaveClass(styles.fitWidth!);
|
||||
// Cleared synchronously before paint so content-visibility doesn't keep the 900px intrinsic height.
|
||||
expect(row).not.toHaveAttribute("data-measured");
|
||||
act(flushFrames);
|
||||
expect(row).toHaveAttribute("data-measured");
|
||||
|
||||
act(() =>
|
||||
useProject.setState({
|
||||
settings: {
|
||||
agents: {
|
||||
fitWindowWidth: false,
|
||||
},
|
||||
} as never,
|
||||
}),
|
||||
);
|
||||
expect(root).not.toHaveClass(styles.fitWidth!);
|
||||
expect(row).not.toHaveAttribute("data-measured");
|
||||
act(flushFrames);
|
||||
expect(row).toHaveAttribute("data-measured");
|
||||
} finally {
|
||||
raf.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("hides the status-bar Terminal button in the local checkout and opens the worktree's terminal otherwise", async () => {
|
||||
|
||||
@@ -303,6 +303,6 @@ describe("closing the hierarchy tab", () => {
|
||||
useHierarchy.setState({ root: { name: "Number", path: "/p/Number.java", line: 0, col: 0 } as never });
|
||||
closeHierarchy();
|
||||
expect(useHierarchy.getState().root).toBeNull();
|
||||
expect(hide).toHaveBeenCalledWith("hierarchy");
|
||||
expect(hide).toHaveBeenCalledWith("hierarchy", { removeFromStripe: true });
|
||||
});
|
||||
});
|
||||
@@ -92,10 +92,10 @@ export function resetHierarchy() {
|
||||
}));
|
||||
}
|
||||
|
||||
/** Closes the hierarchy's content tab; with no content left the tool window hides. */
|
||||
/** Closes the hierarchy's content tab; with no content left the tool window and its stripe button go. */
|
||||
export function closeHierarchy() {
|
||||
resetHierarchy();
|
||||
toolWindowService().hide("hierarchy");
|
||||
toolWindowService().hide("hierarchy", { removeFromStripe: true });
|
||||
}
|
||||
|
||||
/** The empty-result line of the hierarchy tree. */
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const show = vi.fn();
|
||||
const hide = vi.fn();
|
||||
vi.mock("@/workbench/contributions", async (orig) => ({
|
||||
...(await orig<typeof import("@/workbench/contributions")>()),
|
||||
toolWindowService: () => ({ show }),
|
||||
toolWindowService: () => ({ show, hide }),
|
||||
}));
|
||||
/** The editor at the caret (`null`: a search from outside an editor). */
|
||||
let caretView: import("@codemirror/view").EditorView | null = null;
|
||||
@@ -35,8 +36,16 @@ vi.mock("@tauri-apps/api/core", async (orig) => ({
|
||||
|
||||
const { registerDocumentIndexSync } = await import("@/workbench/contributions");
|
||||
|
||||
const { activeUsageSearch, findUsages, openUsageTab, pinUsageTab, resetUsages, showUsageResults, useUsages } =
|
||||
await import("./usages");
|
||||
const {
|
||||
activeUsageSearch,
|
||||
closeUsageTab,
|
||||
findUsages,
|
||||
openUsageTab,
|
||||
pinUsageTab,
|
||||
resetUsages,
|
||||
showUsageResults,
|
||||
useUsages,
|
||||
} = await import("./usages");
|
||||
|
||||
describe("showUsageResults", () => {
|
||||
it("shows given usages in the Find Usages tool window", async () => {
|
||||
@@ -221,4 +230,16 @@ describe("usage tabs", () => {
|
||||
openUsageTab(search(104));
|
||||
expect(useUsages.getState().tabs.map((t) => t.id)).toEqual([102, 104]);
|
||||
});
|
||||
|
||||
it("take the tool window and its stripe button away with the last one", () => {
|
||||
resetUsages();
|
||||
hide.mockClear();
|
||||
openUsageTab(search(201));
|
||||
pinUsageTab(201, true);
|
||||
openUsageTab(search(202));
|
||||
closeUsageTab(201);
|
||||
expect(hide).not.toHaveBeenCalled();
|
||||
closeUsageTab(202);
|
||||
expect(hide).toHaveBeenCalledWith("usages", { removeFromStripe: true });
|
||||
});
|
||||
});
|
||||
@@ -168,6 +168,14 @@ export function closeUsageTab(id: number) {
|
||||
const active = s.active === id ? (tabs[Math.min(i, tabs.length - 1)]?.id ?? null) : s.active;
|
||||
return { tabs, active };
|
||||
});
|
||||
// As in IDEA, the tool window and its stripe button go away with its last tab.
|
||||
if (!useUsages.getState().tabs.length) {
|
||||
try {
|
||||
toolWindowService().hide("usages", { removeFromStripe: true });
|
||||
} catch {
|
||||
// Workbench not ready (tests).
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Rerun of the selected tab (⌘R in the Find Usages tool window). */
|
||||
|
||||
@@ -15,5 +15,5 @@ it("hides the Debug tool window once its last session tab is closed", async () =
|
||||
expect(await closeSessionTab(1)).toBe(true);
|
||||
expect(hide).not.toHaveBeenCalled();
|
||||
expect(await closeSessionTab(2)).toBe(true);
|
||||
expect(hide).toHaveBeenCalledWith("debug");
|
||||
expect(hide).toHaveBeenCalledWith("debug", { removeFromStripe: true });
|
||||
});
|
||||
@@ -372,6 +372,31 @@ describe("run config → launch config", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("Zig under CodeLLDB: no source-language mode, so evaluation stays LLDB's own", () => {
|
||||
const exe = launchConfigFor(
|
||||
rc({ kind: "zig-application", command: "./zig-out/bin/app", debugAdapter: "codelldb" }),
|
||||
"/p",
|
||||
)!;
|
||||
expect(exe.adapter).toBe("codelldb");
|
||||
expect(extra(exe)).toEqual({ sourceLanguages: [] });
|
||||
const single = launchConfigFor(
|
||||
rc({
|
||||
kind: "native",
|
||||
command: "/tmp/openidea-run/calc-1",
|
||||
debugAdapter: "codelldb",
|
||||
params: { language: "zig" },
|
||||
}),
|
||||
"/p",
|
||||
)!;
|
||||
expect(extra(single)).toEqual({ sourceLanguages: [] });
|
||||
// Rust-compiled binaries keep CodeLLDB's default (Rust) source mode.
|
||||
const rust = launchConfigFor(
|
||||
rc({ kind: "native", command: "/tmp/openidea-run/app-1", debugAdapter: "codelldb" }),
|
||||
"/p",
|
||||
)!;
|
||||
expect(rust.extraJson).toBeNull();
|
||||
});
|
||||
|
||||
it("Godot: the editor's adapter plays the main scene or the chosen one of the project", () => {
|
||||
const project = rc({
|
||||
kind: "godot",
|
||||
|
||||
@@ -359,6 +359,10 @@ function nativeLaunch(rc: RunConfig, cwd: string, adapter: string): LaunchConfig
|
||||
env: Object.entries(rc.env).map(([k, v]) => `${k}=${v}`),
|
||||
...(from && to && from !== to ? { sourceMap: [[from, to]] } : {}),
|
||||
});
|
||||
} else if (rc.kind === "zig-application" || rc.params?.language === "zig") {
|
||||
// Zig under CodeLLDB: without a source language, evaluation stays LLDB's own
|
||||
// (the default Rust mode would shape `Evaluate Expression` as Rust).
|
||||
out.extraJson = JSON.stringify({ sourceLanguages: [] });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -880,10 +880,10 @@ export async function closeSessionTab(id: DebugSessionId): Promise<boolean> {
|
||||
await stopSession(s.id);
|
||||
}
|
||||
removeSession(s.id);
|
||||
// As in IDEA, the tool window goes away with its last tab.
|
||||
// As in IDEA, the tool window and its stripe button go away with its last tab.
|
||||
if (!Object.keys(useDebug.getState().sessions).length) {
|
||||
try {
|
||||
toolWindowService().hide("debug");
|
||||
toolWindowService().hide("debug", { removeFromStripe: true });
|
||||
} catch {
|
||||
// Workbench not ready (tests).
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
font-size: var(--fs-small, var(--fs-ui));
|
||||
}
|
||||
|
||||
.button.text:hover,
|
||||
.button:hover,
|
||||
.button[aria-expanded="true"] {
|
||||
background-color: var(--bg-toolbar-hover);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* The OS clipboard's file list: what Explorer copies, and what the project view
|
||||
* puts there so Explorer can paste it back. The format is native (Windows
|
||||
* puts there so Explorer can paste it back; and its image (a screenshot), which
|
||||
* Paste saves as a file. The format is native (Windows
|
||||
* `CF_HDROP`), so the backend owns it; a plain browser has nothing to exchange
|
||||
* and every call degrades to "no files".
|
||||
*/
|
||||
@@ -13,6 +14,10 @@ export interface OsClipboard {
|
||||
hasFiles(): Promise<boolean>;
|
||||
/** True only when the OS accepted the file list; false for unsupported hosts. */
|
||||
setFiles(paths: string[]): Promise<boolean>;
|
||||
/** Whether the clipboard holds an image: cheap, for the Paste item's enabled state. */
|
||||
hasImage(): Promise<boolean>;
|
||||
/** The clipboard's image as PNG bytes, null when it holds none. */
|
||||
image(): Promise<Uint8Array | null>;
|
||||
}
|
||||
|
||||
const native: OsClipboard = {
|
||||
@@ -39,6 +44,23 @@ const native: OsClipboard = {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
async hasImage() {
|
||||
if (!isTauri()) return false;
|
||||
try {
|
||||
return await commands.clipboardHasImage();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
async image() {
|
||||
if (!isTauri()) return null;
|
||||
const url = await call(commands.clipboardImage());
|
||||
if (!url) return null;
|
||||
const binary = atob(url.slice(url.indexOf(",") + 1));
|
||||
return Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
||||
},
|
||||
};
|
||||
|
||||
let current = native;
|
||||
@@ -47,7 +69,16 @@ export function osClipboard(): OsClipboard {
|
||||
return current;
|
||||
}
|
||||
|
||||
/** Tests: force a clipboard implementation. */
|
||||
export function setOsClipboardForTests(clipboard: OsClipboard | null) {
|
||||
current = clipboard ?? native;
|
||||
/** Tests: force a clipboard implementation; what it leaves out holds nothing. */
|
||||
export function setOsClipboardForTests(clipboard: Partial<OsClipboard> | null) {
|
||||
current = clipboard
|
||||
? {
|
||||
files: async () => [],
|
||||
hasFiles: async () => false,
|
||||
setFiles: async () => false,
|
||||
hasImage: async () => false,
|
||||
image: async () => null,
|
||||
...clipboard,
|
||||
}
|
||||
: native;
|
||||
}
|
||||
@@ -14,6 +14,8 @@ import { isInside, joinPath, nameOf, parentOf } from "./paths";
|
||||
export interface ProjectFs {
|
||||
readDir(path: string): Promise<FileEntry[]>;
|
||||
createFile(path: string): Promise<void>;
|
||||
/** Creates `path` with `data`; fails when it exists. */
|
||||
createFileBytes(path: string, data: Uint8Array): Promise<void>;
|
||||
createDir(path: string): Promise<void>;
|
||||
rename(from: string, to: string): Promise<void>;
|
||||
/** Moves to the trash when possible. */
|
||||
@@ -28,6 +30,10 @@ export const tauriFs: ProjectFs = {
|
||||
await call(commands.fsCreateFile(path));
|
||||
notifyFileOperation({ kind: "created", paths: [path] });
|
||||
},
|
||||
createFileBytes: async (path, data) => {
|
||||
await call(commands.fsCreateFileBytes(path, [...data]));
|
||||
notifyFileOperation({ kind: "created", paths: [path] });
|
||||
},
|
||||
createDir: async (path) => void (await call(commands.fsCreateDir(path))),
|
||||
rename: async (from, to) => void (await call(commands.fsRename(from, to))),
|
||||
delete: async (path) => {
|
||||
@@ -161,6 +167,13 @@ export class MemoryFs implements ProjectFs {
|
||||
this.emit({ created: [path] });
|
||||
}
|
||||
|
||||
async createFileBytes(path: string, data: Uint8Array) {
|
||||
if (this.nodes.has(path)) throw err("alreadyExists", `${path} already exists`);
|
||||
this.mkdirp(parentOf(path));
|
||||
this.nodes.set(path, { kind: "file", size: data.length });
|
||||
this.emit({ created: [path] });
|
||||
}
|
||||
|
||||
async createDir(path: string) {
|
||||
if (this.nodes.has(path)) throw err("alreadyExists", `${path} already exists`);
|
||||
this.mkdirp(path);
|
||||
|
||||
@@ -185,6 +185,26 @@ describe("OS file imports", () => {
|
||||
expect(fs.nodes.has("/p/target/local.txt")).toBe(true);
|
||||
});
|
||||
|
||||
it("saves a pasted image as img.png, then img_1.png, and selects it", async () => {
|
||||
const png = new Uint8Array([137, 80, 78, 71]);
|
||||
setOsClipboardForTests({ hasImage: async () => true, image: async () => png });
|
||||
await refreshOsClipboard();
|
||||
expect(canPaste()).toBe(true);
|
||||
await paste("/p/target");
|
||||
await paste("/p/target");
|
||||
expect(fs.nodes.get("/p/target/img.png")).toEqual({ kind: "file", size: 4 });
|
||||
expect(fs.nodes.has("/p/target/img_1.png")).toBe(true);
|
||||
expect(useProjectTree.getState().revealRequest?.path).toBe("/p/target/img_1.png");
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("says the clipboard is empty when it holds neither files nor an image", async () => {
|
||||
setOsClipboardForTests({});
|
||||
await paste("/p/target");
|
||||
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "No files on the clipboard" }));
|
||||
expect([...fs.nodes.keys()].filter((p) => p.startsWith("/p/target/"))).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports a clipboard read failure", async () => {
|
||||
setOsClipboardForTests({
|
||||
files: async () => {
|
||||
|
||||
@@ -13,7 +13,7 @@ import { osClipboard } from "./clipboard";
|
||||
import { lastFileRefactoring, nextFileOperation, runFileRefactoring, undoFileRefactoring } from "./fileRefactor";
|
||||
import { openFileRefactorDialog, rememberedOptions } from "./FileRefactorDialogs";
|
||||
import { beginLocalImport, projectFs } from "./fs";
|
||||
import { call, commands, isCancelled } from "@/platform/ipc";
|
||||
import { call, commands, IpcError, isCancelled } from "@/platform/ipc";
|
||||
import { MEMBER_PREFIX, type ProjectNode } from "./model";
|
||||
import {
|
||||
isInside,
|
||||
@@ -573,8 +573,9 @@ export function copySelection(cut: boolean) {
|
||||
setClipboard({ paths, cut, remote, osWrite });
|
||||
}
|
||||
|
||||
/** Files on the OS clipboard, cached: `canPaste` runs while a menu renders. */
|
||||
/** Files or an image on the OS clipboard, cached: `canPaste` runs while a menu renders. */
|
||||
let osHasFiles = false;
|
||||
let osHasImage = false;
|
||||
|
||||
/** Keeps Paste enabled for what Explorer copied; called when the window gains focus. */
|
||||
export async function refreshOsClipboard() {
|
||||
@@ -588,10 +589,11 @@ export async function refreshOsClipboard() {
|
||||
async function readOsClipboard(): Promise<string[] | null> {
|
||||
const { clipboard } = get();
|
||||
const handedOff = await clipboard?.osWrite;
|
||||
const external = await osClipboard().files();
|
||||
const [external, image] = await Promise.all([osClipboard().files(), osClipboard().hasImage()]);
|
||||
// A newer Copy/Cut owns the state if this read (or its hand-off) was delayed.
|
||||
if (get().clipboard !== clipboard) return null;
|
||||
osHasFiles = external.length > 0;
|
||||
osHasImage = image;
|
||||
// Our remote text write removes file URLs, so any files were copied later.
|
||||
// A failed write leaves ownership uncertain; retain the remote copy then.
|
||||
if (handedOff && (clipboard?.remote ? external.length > 0 : !sameFiles(external, clipboard?.paths)))
|
||||
@@ -600,12 +602,13 @@ async function readOsClipboard(): Promise<string[] | null> {
|
||||
}
|
||||
|
||||
export function canPaste(): boolean {
|
||||
return !!get().clipboard?.paths.length || osHasFiles;
|
||||
return !!get().clipboard?.paths.length || osHasFiles || osHasImage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Paste: cut items go through the Move dialog, copied ones through the Copy
|
||||
* dialog (IDEA). Files copied in Explorer paste as copies.
|
||||
* dialog (IDEA). Files copied in Explorer paste as copies; an image (a
|
||||
* screenshot) is saved as `img.png`.
|
||||
*/
|
||||
export async function paste(target = targetFolder()) {
|
||||
if (!target || isReadOnlyPath(target)) return;
|
||||
@@ -626,6 +629,7 @@ export async function paste(target = targetFolder()) {
|
||||
if (!clipboard?.remote && external.length && !sameFiles(external, clipboard?.paths))
|
||||
return pasteFromOsClipboard(external, target);
|
||||
if (!clipboard?.paths.length) {
|
||||
if (await pasteImage(target)) return;
|
||||
notifications().notify({ level: "info", title: "No files on the clipboard" });
|
||||
return;
|
||||
}
|
||||
@@ -640,6 +644,39 @@ export async function paste(target = targetFolder()) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the clipboard's image in `target` as `img.png`, or `img_1.png`, `img_2.png`
|
||||
* … when taken, and selects it. False when the clipboard holds no image.
|
||||
*/
|
||||
async function pasteImage(target: string): Promise<boolean> {
|
||||
let png: Uint8Array | null;
|
||||
try {
|
||||
png = await osClipboard().image();
|
||||
} catch (e) {
|
||||
fail(tx("Cannot access the clipboard"), e);
|
||||
return true;
|
||||
}
|
||||
if (!png) return false;
|
||||
await loadDir(target);
|
||||
const taken = new Set((get().listings.get(target) ?? []).map((e) => e.name));
|
||||
for (let i = 0; ; i++) {
|
||||
const name = i ? `img_${i}.png` : "img.png";
|
||||
if (taken.has(name)) continue;
|
||||
const path = joinPath(target, name);
|
||||
try {
|
||||
await projectFs(get().root ?? target).createFileBytes(path, png);
|
||||
} catch (e) {
|
||||
// Created since the listing was read: take the next name.
|
||||
if (e instanceof IpcError && e.kind === "alreadyExists") continue;
|
||||
fail(tx`Cannot paste the image into ${name}`, e);
|
||||
return true;
|
||||
}
|
||||
await loadDir(target, true);
|
||||
revealPath(path, true);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Pasting from Explorer copies, whatever the source: never a move or a refactoring. */
|
||||
async function pasteFromOsClipboard(paths: string[], target: string) {
|
||||
osHasFiles = true;
|
||||
|
||||
@@ -303,7 +303,8 @@ function currentTab(
|
||||
export async function closeRunTab(id: string, traces: readonly StackTraceTab[]) {
|
||||
if (traces.some((t) => t.id === id)) closeStackTrace(id);
|
||||
else if (!(await closeSessionTab(id))) return;
|
||||
if (!useRun.getState().sessions.length && !useStackTraces.getState().tabs.length) toolWindowService().hide("run");
|
||||
if (!useRun.getState().sessions.length && !useStackTraces.getState().tabs.length)
|
||||
toolWindowService().hide("run", { removeFromStripe: true });
|
||||
}
|
||||
|
||||
/** Session (and stack trace) tabs in the tool window header. */
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
import { useState } from "react";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { ContextMenuHost } from "@/ui";
|
||||
import { occurrenceNavigator } from "@/workbench/contributions";
|
||||
import { TestResults } from "./testing";
|
||||
import { TestTreeView } from "./TestTreeView";
|
||||
import { testTree } from "./testTree";
|
||||
|
||||
const nav = vi.hoisted(() => ({ openTarget: vi.fn(async () => {}) }));
|
||||
vi.mock("./navigate", () => nav);
|
||||
@@ -112,3 +116,173 @@ describe("TestTreeView", () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("Previous / Next Failed Test", () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
/** Two suites with failures in a nested suite and between passing tests. */
|
||||
function nested(failures = true) {
|
||||
const r = new TestResults();
|
||||
const bad = failures ? "failed" : "passed";
|
||||
r.apply([
|
||||
{ type: "result", path: ["ApiTest", "lists()"], status: "passed" },
|
||||
{ type: "result", path: ["ApiTest", "Auth", "rejects()"], status: bad },
|
||||
{ type: "result", path: ["ApiTest", "Auth", "accepts()"], status: "passed" },
|
||||
{ type: "result", path: ["DbTest", "reads()"], status: bad },
|
||||
{ type: "result", path: ["DbTest", "skips()"], status: "skipped" },
|
||||
{ type: "result", path: ["DbTest", "writes()"], status: bad },
|
||||
{ type: "location", path: ["DbTest", "writes()"], location: { path: "DbTest.java", line: 20, resolve: "name" } },
|
||||
]);
|
||||
r.finish(failures ? 1 : 0);
|
||||
return r;
|
||||
}
|
||||
|
||||
function Nested({ results }: { results: TestResults }) {
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
return (
|
||||
<TestTreeView results={results} version={1} cwd="/p" selected={selected} onSelect={setSelected} running={false} />
|
||||
);
|
||||
}
|
||||
|
||||
const go = (dir: 1 | -1, focus = false) => {
|
||||
let step: ReturnType<NonNullable<ReturnType<typeof occurrenceNavigator>>["go"]> = null;
|
||||
act(() => {
|
||||
step = occurrenceNavigator("run")!.go(dir, focus);
|
||||
});
|
||||
return step as { key: string; index: number; total: number } | null;
|
||||
};
|
||||
const selectedName = () => screen.getByRole("treeitem", { selected: true }).textContent;
|
||||
const prev = () => screen.getByRole("button", { name: "Previous Failed Test" });
|
||||
const next = () => screen.getByRole("button", { name: "Next Failed Test" });
|
||||
|
||||
it("steps through the failed tests in tree order and stops at both ends", () => {
|
||||
render(<Nested results={nested()} />);
|
||||
expect(prev()).toBeEnabled();
|
||||
expect(next()).toBeEnabled();
|
||||
expect(go(1)).toMatchObject({ index: 1, total: 3 });
|
||||
expect(selectedName()).toContain("rejects()");
|
||||
expect(go(1)).toMatchObject({ index: 2, total: 3 });
|
||||
expect(selectedName()).toContain("reads()");
|
||||
expect(go(1)).toMatchObject({ index: 3, total: 3 });
|
||||
expect(selectedName()).toContain("writes()");
|
||||
// IDEA doesn't wrap: Next is unavailable on the last failure, and the selection stays.
|
||||
expect(next()).toBeDisabled();
|
||||
expect(prev()).toBeEnabled();
|
||||
expect(go(1)).toBeNull();
|
||||
expect(selectedName()).toContain("writes()");
|
||||
expect(go(-1)).toMatchObject({ index: 2 });
|
||||
expect(go(-1)).toMatchObject({ index: 1 });
|
||||
expect(prev()).toBeDisabled();
|
||||
expect(go(-1)).toBeNull();
|
||||
expect(selectedName()).toContain("rejects()");
|
||||
});
|
||||
|
||||
it("expands the collapsed suites of the failure it selects", () => {
|
||||
render(<Nested results={nested()} />);
|
||||
const suite = screen.getByText("ApiTest").closest('[role="treeitem"]')!;
|
||||
fireEvent.mouseDown(suite.querySelector("[data-tree-toggle]")!, { button: 0 });
|
||||
expect(screen.queryByText("rejects()")).toBeNull();
|
||||
go(1);
|
||||
expect(selectedName()).toContain("rejects()");
|
||||
});
|
||||
|
||||
it("opens the failure's source, focusing the editor only when asked", () => {
|
||||
render(<Nested results={nested()} />);
|
||||
go(-1);
|
||||
expect(nav.openTarget).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ path: "DbTest.java", line: 20 }),
|
||||
"/p",
|
||||
false,
|
||||
);
|
||||
go(-1, true);
|
||||
// reads() has no location: nothing to open.
|
||||
expect(nav.openTarget).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("is unavailable when no test failed", () => {
|
||||
render(<Nested results={nested(false)} />);
|
||||
expect(prev()).toBeDisabled();
|
||||
expect(next()).toBeDisabled();
|
||||
expect(go(1)).toBeNull();
|
||||
expect(go(-1)).toBeNull();
|
||||
});
|
||||
|
||||
it("runs Previous / Next Occurrence, so ⌘⌥↑ / ⌘⌥↓ do the same", () => {
|
||||
render(<Nested results={nested()} />);
|
||||
fireEvent.click(next());
|
||||
expect(actions.executeAction).toHaveBeenCalledWith("navigate.nextOccurrence", undefined);
|
||||
fireEvent.click(prev());
|
||||
expect(actions.executeAction).toHaveBeenCalledWith("navigate.prevOccurrence", undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Expand All / Collapse All", () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
function nested() {
|
||||
const r = new TestResults();
|
||||
r.apply([
|
||||
{ type: "result", path: ["ApiTest", "Auth", "Tokens", "refreshes()"], status: "failed" },
|
||||
{ type: "result", path: ["ApiTest", "Users", "lists()"], status: "passed" },
|
||||
{ type: "result", path: ["DbTest", "Pool", "reuses()"], status: "passed" },
|
||||
]);
|
||||
r.finish(1);
|
||||
return r;
|
||||
}
|
||||
|
||||
const view = (results: TestResults) => (
|
||||
<TestTreeView results={results} version={1} cwd="/p" selected={null} onSelect={() => {}} running={false} />
|
||||
);
|
||||
const rows = () => screen.queryAllByRole("treeitem").map((r) => r.textContent?.replace(/\d+ ms$/, ""));
|
||||
|
||||
it("opens every suite, including those of hidden passed tests, and folds back to the top-level suites", () => {
|
||||
localStorage.setItem("openidea.run.testFilters", JSON.stringify({ showPassed: true }));
|
||||
render(view(nested()));
|
||||
// By default only the top level and the suites with failures are open.
|
||||
expect(rows()).toEqual(["ApiTest", "Auth", "Tokens", "refreshes()", "Users", "DbTest", "Pool"]);
|
||||
act(() => testTree.expandAll!());
|
||||
expect(rows()).toEqual([
|
||||
"ApiTest",
|
||||
"Auth",
|
||||
"Tokens",
|
||||
"refreshes()",
|
||||
"Users",
|
||||
"lists()",
|
||||
"DbTest",
|
||||
"Pool",
|
||||
"reuses()",
|
||||
]);
|
||||
act(() => testTree.collapseAll!());
|
||||
expect(rows()).toEqual(["ApiTest", "DbTest"]);
|
||||
// Expanded state survives a filter change.
|
||||
act(() => testTree.expandAll!());
|
||||
fireEvent.click(screen.getByRole("button", { name: "Show Passed" }));
|
||||
expect(rows()).toEqual(["ApiTest", "Auth", "Tokens", "refreshes()"]);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Show Passed" }));
|
||||
expect(rows()).toContain("reuses()");
|
||||
});
|
||||
|
||||
it("the buttons run the actions, and are unavailable without suites", () => {
|
||||
const dispose = registerActions([
|
||||
{ id: "run.expandAllTests", title: "Expand All", run: () => {} },
|
||||
{ id: "run.collapseAllTests", title: "Collapse All", run: () => {} },
|
||||
]);
|
||||
onTestFinished(dispose);
|
||||
const { unmount } = render(view(nested()));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Expand All" }));
|
||||
expect(actions.executeAction).toHaveBeenCalledWith("run.expandAllTests", undefined);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Collapse All" }));
|
||||
expect(actions.executeAction).toHaveBeenCalledWith("run.collapseAllTests", undefined);
|
||||
unmount();
|
||||
expect(testTree.expandAll).toBeNull();
|
||||
|
||||
const flat = new TestResults();
|
||||
flat.apply([{ type: "result", path: ["main_test"], status: "failed" }]);
|
||||
flat.finish(1);
|
||||
render(view(flat));
|
||||
expect(screen.getByRole("button", { name: "Expand All" })).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "Collapse All" })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,22 @@
|
||||
import { useMemo, useState, type MouseEvent } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type MouseEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { Icon, IconButton, showContextMenu, useContextMenuStore, Spinner, Tree, type MenuItem } from "@/ui";
|
||||
import {
|
||||
findOccurrence,
|
||||
Icon,
|
||||
IconButton,
|
||||
showContextMenu,
|
||||
useContextMenuStore,
|
||||
Spinner,
|
||||
Tree,
|
||||
type MenuItem,
|
||||
type TreeHandle,
|
||||
} from "@/ui";
|
||||
import { useOccurrenceNavigator } from "@/workbench/contributions";
|
||||
import { openTarget } from "./navigate";
|
||||
import { nodeStatus, type TestNode, type TestResults, type TestStatus } from "./testing";
|
||||
import { parseComparison } from "./testing/comparison";
|
||||
import { TEST_TREE_FOCUS, testTree } from "./testTree";
|
||||
import styles from "./Run.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -84,6 +96,24 @@ export function StatusIcon({ status }: { status: TestStatus | null }) {
|
||||
}
|
||||
}
|
||||
|
||||
const isFailedTest = (n: TestNode) => n.children.length === 0 && nodeStatus(n) === "failed";
|
||||
|
||||
const treeModel = {
|
||||
getKey: (n: TestNode) => n.id,
|
||||
getChildren: (n: TestNode) => n.children,
|
||||
isExpandable: (n: TestNode) => n.children.length > 0,
|
||||
isOccurrence: isFailedTest,
|
||||
};
|
||||
|
||||
function suiteIds(nodes: readonly TestNode[], out: Set<string> = new Set()): Set<string> {
|
||||
for (const n of nodes) {
|
||||
if (n.children.length === 0) continue;
|
||||
out.add(n.id);
|
||||
suiteIds(n.children, out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function filterTree(nodes: readonly TestNode[], keep: (n: TestNode) => boolean): TestNode[] {
|
||||
const out: TestNode[] = [];
|
||||
for (const n of nodes) {
|
||||
@@ -129,6 +159,7 @@ export function TestTreeView({
|
||||
});
|
||||
const [expanded, setExpanded] = useState<Set<string> | null>(null);
|
||||
const [selection, setSelection] = useState<Set<string>>(new Set());
|
||||
const tree = useRef<TreeHandle>(null);
|
||||
const selectedKeys = useMemo(
|
||||
() => (selected === null ? new Set<string>() : selection.has(selected) ? selection : new Set([selected])),
|
||||
[selected, selection],
|
||||
@@ -209,6 +240,28 @@ export function TestTreeView({
|
||||
return set;
|
||||
}, [expanded, roots]);
|
||||
|
||||
// Collapse All leaves the top-level suites in view, as IDEA's test tree does.
|
||||
useEffect(() => {
|
||||
testTree.expandAll = () => setExpanded(suiteIds(results.roots));
|
||||
testTree.collapseAll = () => setExpanded(new Set());
|
||||
return () => {
|
||||
testTree.expandAll = null;
|
||||
testTree.collapseAll = null;
|
||||
};
|
||||
});
|
||||
const hasSuites = roots.some((n) => n.children.length > 0);
|
||||
|
||||
// Previous / Next Failed Test (⌘⌥↑ / ⌘⌥↓): like IDEA, stops at the first / last failure instead of wrapping.
|
||||
useOccurrenceNavigator("run", (dir, focus) => {
|
||||
const step = tree.current?.selectOccurrence(dir);
|
||||
if (!step) return null;
|
||||
const n = step.node as TestNode;
|
||||
if (n.location) void openTarget(n.location, cwd, focus);
|
||||
return step;
|
||||
});
|
||||
const hasPrevFailed = findOccurrence(roots, selected, -1, treeModel) !== null;
|
||||
const hasNextFailed = findOccurrence(roots, selected, 1, treeModel) !== null;
|
||||
|
||||
const status = running ? "running" : counts.failed > 0 ? "failed" : counts.total > 0 ? "passed" : null;
|
||||
const duration = results.summary.durationMs;
|
||||
|
||||
@@ -240,15 +293,42 @@ export function TestTreeView({
|
||||
pressed={showIgnored}
|
||||
onClick={() => toggle("showIgnored")}
|
||||
/>
|
||||
<IconButton icon="expand-all" action="run.expandAllTests" size="small" iconSize={16} disabled={!hasSuites} />
|
||||
<IconButton
|
||||
icon="collapse-all"
|
||||
action="run.collapseAllTests"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
disabled={!hasSuites}
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-up"
|
||||
action="navigate.prevOccurrence"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title="Previous Failed Test"
|
||||
disabled={!hasPrevFailed}
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-down"
|
||||
action="navigate.nextOccurrence"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title="Next Failed Test"
|
||||
disabled={!hasNextFailed}
|
||||
/>
|
||||
</div>
|
||||
<Tree<TestNode>
|
||||
aria-label="Test results"
|
||||
className={styles.testTree}
|
||||
handleRef={tree}
|
||||
focusContext={TEST_TREE_FOCUS}
|
||||
roots={roots}
|
||||
getKey={(n) => n.id}
|
||||
getLabel={(n) => n.name}
|
||||
getChildren={(n) => (n.children.length ? n.children : undefined)}
|
||||
isExpandable={(n) => n.children.length > 0}
|
||||
isOccurrence={isFailedTest}
|
||||
expanded={effectiveExpanded}
|
||||
onExpandedChange={(next) => setExpanded(next)}
|
||||
selected={selectedKeys}
|
||||
|
||||
@@ -24,5 +24,5 @@ it("hides the Run tool window once its last tab is closed", async () => {
|
||||
await closeRunTab("t", useStackTraces.getState().tabs);
|
||||
expect(hide).not.toHaveBeenCalled();
|
||||
await closeRunTab("b", useStackTraces.getState().tabs);
|
||||
expect(hide).toHaveBeenCalledWith("run");
|
||||
expect(hide).toHaveBeenCalledWith("run", { removeFromStripe: true });
|
||||
});
|
||||
@@ -1,15 +1,36 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { menuGroupItems, registerMenuGroup } from "@/workbench/contributions";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import { canDebugProduced, choiceItems, contextMenuItems } from "./contextRun";
|
||||
import { OPTIMISTIC, produceContextChoices } from "./producers";
|
||||
import { canDebugProduced, choiceItems, compiledDebugPlan, contextMenuItems } from "./contextRun";
|
||||
import { OPTIMISTIC, produceContextChoices, type ToolEnv } from "./producers";
|
||||
import { gutterTestState, markerIcon, targetMenuItems } from "./runGutter";
|
||||
import { useRun } from "./store";
|
||||
import type { RunTarget } from "./targets";
|
||||
import { TestResults } from "./testing";
|
||||
import { clearTestStates, recordTestStates } from "./testing/states";
|
||||
import { setInvokeRoute } from "@/platform/tauriCore";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tauri: { value: false },
|
||||
read: { value: null as string | null },
|
||||
toolEnv: { value: null as ((...args: unknown[]) => unknown) | null },
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return { ...actual, isTauri: () => mocks.tauri.value };
|
||||
});
|
||||
|
||||
vi.mock("./runtimes", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("./runtimes")>();
|
||||
return {
|
||||
...actual,
|
||||
toolEnv: (...args: Parameters<typeof actual.toolEnv>) =>
|
||||
mocks.toolEnv.value ? mocks.toolEnv.value(...args) : actual.toolEnv(...args),
|
||||
};
|
||||
});
|
||||
|
||||
const ROOT = "/work/app";
|
||||
const SCRATCHES = "/Users/me/scratches";
|
||||
@@ -203,6 +224,23 @@ describe("run gutter popup", () => {
|
||||
describe("Debug entry", () => {
|
||||
const config = (c: Partial<RunConfig>) =>
|
||||
({ id: "c", name: "c", command: "", args: [], cwd: "", env: {}, ...c }) as RunConfig;
|
||||
const MAIN_ZIG = [
|
||||
'const std = @import("std");',
|
||||
"pub fn main() !void {",
|
||||
' std.debug.print("hi\\n", .{});',
|
||||
"}",
|
||||
].join("\n");
|
||||
const CALC_ZIG = [
|
||||
'const std = @import("std");',
|
||||
'test "adds two numbers" {',
|
||||
" try std.testing.expect(true);",
|
||||
"}",
|
||||
].join("\n");
|
||||
const zigEnv: ToolEnv = {
|
||||
tool: (n) => (n === "zig" ? { path: "/bin/zig", version: "0.17.1" } : null),
|
||||
compileDir: "/tmp/openidea-run",
|
||||
};
|
||||
|
||||
it("is offered for Maven and Gradle tests, which run with a JDWP agent", () => {
|
||||
const mavenTest = config({ kind: "maven", command: "mvn", args: ["test", "-Dtest=A#b"], isTest: true });
|
||||
expect(canDebugProduced({ name: "A.b", scope: "element", config: mavenTest })).toBe(true);
|
||||
@@ -217,4 +255,113 @@ describe("Debug entry", () => {
|
||||
canDebugProduced({ name: "lint", scope: "file", config: config({ kind: "npm", args: ["run", "lint"] }) }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
useProject.setState({ project: { name: "app", root: ROOT, trusted: true, isGit: false, settings: {} } as never });
|
||||
useRun.setState({ configs: [], loaded: true });
|
||||
mocks.tauri.value = true;
|
||||
mocks.toolEnv.value = () => zigEnv;
|
||||
// Bindings' `typedError` wraps the raw invoke result: `fs_read_text` resolves to its text.
|
||||
setInvokeRoute((cmd) =>
|
||||
cmd === "fs_read_text" ? Promise.resolve(mocks.read.value) : Promise.reject(new Error("not stubbed")),
|
||||
);
|
||||
});
|
||||
afterEach(() => {
|
||||
mocks.tauri.value = false;
|
||||
mocks.read.value = null;
|
||||
mocks.toolEnv.value = null;
|
||||
setInvokeRoute(null);
|
||||
useProject.setState({ project: null });
|
||||
useRun.setState({ configs: [], loaded: false });
|
||||
});
|
||||
|
||||
it("re-debug of a saved zig file config rebuilds the build-then-debug plan", async () => {
|
||||
mocks.read.value = MAIN_ZIG;
|
||||
const saved = config({
|
||||
id: "context:file:src/main.zig",
|
||||
kind: "zig",
|
||||
command: "zig",
|
||||
args: ["run", "src/main.zig"],
|
||||
cwd: null,
|
||||
});
|
||||
const plan = await compiledDebugPlan(saved);
|
||||
expect(plan?.debug).toBeTruthy();
|
||||
expect(plan!.debug!.build.command).toMatch(
|
||||
/zig build-exe src\/main\.zig -femit-bin=\/tmp\/openidea-run\/main-\w+$/,
|
||||
);
|
||||
expect(plan!.debug!.config).toMatchObject({
|
||||
kind: "native",
|
||||
debugAdapter: "codelldb",
|
||||
params: { language: "zig" },
|
||||
});
|
||||
});
|
||||
|
||||
it("re-debug of a saved zig test config re-targets its test", async () => {
|
||||
mocks.read.value = CALC_ZIG;
|
||||
const saved = config({
|
||||
id: "context:file:src/calc.zig#adds two numbers",
|
||||
kind: "zig",
|
||||
command: "zig",
|
||||
args: ["test", "src/calc.zig", "--test-filter", "adds two numbers"],
|
||||
cwd: null,
|
||||
});
|
||||
const plan = await compiledDebugPlan(saved);
|
||||
expect(plan?.debug).toBeTruthy();
|
||||
expect(plan!.debug!.build.command).toMatch(
|
||||
/zig test src\/calc\.zig --test-filter 'adds two numbers' --test-no-exec/,
|
||||
);
|
||||
expect(plan!.debug!.config.args).toEqual([]);
|
||||
});
|
||||
|
||||
it("leaves other configurations alone", async () => {
|
||||
expect(await compiledDebugPlan(config({ id: "c", kind: "shell", command: "make" }))).toBeNull();
|
||||
expect(
|
||||
await compiledDebugPlan(config({ id: "user:x", kind: "zig", command: "zig", args: ["run", "x.zig"], cwd: null })),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Run with Fuzzing", () => {
|
||||
const goTest: RunConfig = {
|
||||
...npmTest,
|
||||
id: "go:test",
|
||||
name: "go test ./...",
|
||||
kind: "go",
|
||||
command: "go",
|
||||
args: ["test", "./..."],
|
||||
debugAdapter: "delve",
|
||||
};
|
||||
const text = "package parse\nfunc TestParse(t *testing.T) {}\nfunc FuzzParse(f *testing.F) {\n}\n";
|
||||
const path = `${ROOT}/parse/parse_test.go`;
|
||||
const target = (line: number, name: string): RunTarget => ({ line, kind: "test", name, path: [name] });
|
||||
const itemLabels = (items: MenuItem[]) => items.map((i) => ("label" in i ? (i.label ?? "") : "---"));
|
||||
|
||||
beforeEach(() => {
|
||||
useProject.setState({ project: { name: "app", root: ROOT, trusted: true, isGit: false, settings: {} } as never });
|
||||
useRun.setState({ configs: [goTest], loaded: true });
|
||||
});
|
||||
afterEach(() => {
|
||||
useProject.setState({ project: null });
|
||||
useRun.setState({ configs: [], loaded: false });
|
||||
});
|
||||
|
||||
it("the gutter offers it on a Fuzz function, after Run and Debug", () => {
|
||||
expect(itemLabels(targetMenuItems(target(2, "FuzzParse"), path, text))).toEqual([
|
||||
"Run 'FuzzParse in parse'",
|
||||
"Debug 'FuzzParse in parse'",
|
||||
"Run 'FuzzParse in parse' with Fuzzing",
|
||||
"---",
|
||||
"Modify Run Configuration…",
|
||||
]);
|
||||
expect(itemLabels(targetMenuItems(target(1, "TestParse"), path, text)).some((l) => /Fuzzing/.test(l))).toBe(false);
|
||||
});
|
||||
|
||||
it("the editor menu offers it under More Run/Debug at a Fuzz function only", () => {
|
||||
const at = (line: number) => labels(contextMenuItems("editor", { paths: [path], text, line }));
|
||||
expect(at(2)).toContain("Run 'FuzzParse in parse' with Fuzzing");
|
||||
expect(at(1).some((l) => /Fuzzing/.test(l))).toBe(false);
|
||||
expect(
|
||||
labels(contextMenuItems("projectView", { paths: [path], dirs: [false] })).some((l) => /Fuzzing/.test(l)),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
produceContextChoices,
|
||||
produceDirectory,
|
||||
produceFile,
|
||||
produceFuzz,
|
||||
scriptLanguage,
|
||||
type ContextInput,
|
||||
type Produced,
|
||||
@@ -196,9 +197,9 @@ export async function compiledDebugPlan(config: RunConfig): Promise<Produced | n
|
||||
const input: ContextInput = { ...projectContext(), root, path, content };
|
||||
const env = await toolEnv(neededTools(input), path, root, false);
|
||||
if (m[2]) {
|
||||
// A test: find the target by name again.
|
||||
// A test: find the target by name again (targets and the id carry the unescaped name).
|
||||
if (config.kind === "zig") {
|
||||
const test = zigTargets(content ?? "").find((t) => t.name.replace(/\\(.)/g, "$1") === m[2]);
|
||||
const test = zigTargets(content ?? "").find((t) => t.name === m[2]);
|
||||
return test ? produceContext({ ...input, line: test.line }, env) : null;
|
||||
}
|
||||
const lines = (content ?? "").split("\n");
|
||||
@@ -293,6 +294,21 @@ export function executorItems(config: RunConfig | null | undefined, name: string
|
||||
}));
|
||||
}
|
||||
|
||||
/** "Run '<FuzzXxx>' with Fuzzing" at a Go fuzz target: `go test -fuzz` until it is stopped or fails. */
|
||||
export function fuzzItems(input: ContextInput, context: ContextArg): MenuItem[] {
|
||||
const p = produceFuzz(input, OPTIMISTIC);
|
||||
return p ? [{ label: tx`Run '${p.name}' with Fuzzing`, icon: "run", run: () => void fuzzContext(context) }] : [];
|
||||
}
|
||||
|
||||
async function fuzzContext(arg: ContextArg): Promise<void> {
|
||||
await ensureConfigs();
|
||||
const input = await withArgContent(arg);
|
||||
if (!input) return;
|
||||
await loadGoModules(input.root, useRun.getState().configs);
|
||||
const p = produceFuzz({ ...input, configs: useRun.getState().configs, goModule: goModulePath }, OPTIMISTIC);
|
||||
if (p) await launchProduced(p, false);
|
||||
}
|
||||
|
||||
export interface ContextArg {
|
||||
path: string;
|
||||
line?: number;
|
||||
@@ -349,7 +365,7 @@ function peekContent(path: string): string | undefined {
|
||||
/** Whether the file's runnability depends on its text (`package main`, `fn main`, `#!`…). */
|
||||
function needsContent(path: string): boolean {
|
||||
const name = path.slice(path.lastIndexOf("/") + 1);
|
||||
return /\.(go|rs|java|kt|c|cpp|cc|cxx)$/.test(name) || !name.includes(".");
|
||||
return /\.(go|rs|java|kt|c|cpp|cc|cxx|zig)$/.test(name) || !name.includes(".");
|
||||
}
|
||||
|
||||
export async function prepareMenu(_menu: ContextMenuId, ctx: MenuGroupContext): Promise<void> {
|
||||
@@ -394,6 +410,7 @@ export function contextMenuItems(menu: ContextMenuId, ctx: MenuGroupContext): Me
|
||||
label: "More Run/Debug",
|
||||
submenu: [
|
||||
...executorItems(p.config, p.name, arg),
|
||||
...fuzzItems(input, arg),
|
||||
{ kind: "action", action: "run.modifyContext", arg, label: "Modify Run Configuration…", icon: "edit" },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -99,6 +99,7 @@ import {
|
||||
isLive,
|
||||
} from "./store";
|
||||
import { rerunFailedConfigs } from "./testing/rerun";
|
||||
import { TEST_TREE_FOCUS, testTree } from "./testTree";
|
||||
import { startAgentRun, trimAgentArchive, type AgentRunRequest } from "./agentRuns";
|
||||
import { compoundTargets, selectedTarget } from "./sessionTargets";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -184,7 +185,7 @@ async function debugConfig(config: RunConfig, chain: readonly string[] = [], sho
|
||||
await executeAction("debug.startConfig", show === false ? { config, show: false } : config);
|
||||
return;
|
||||
}
|
||||
// A single compiled file (rustc / clang): build with debug info, then debug the binary.
|
||||
// A single compiled file (rustc / clang / zig): build with debug info, then debug the binary.
|
||||
const compiled = await compiledDebugPlan(config);
|
||||
if (compiled?.debug) {
|
||||
await launchProduced(compiled, true, show);
|
||||
@@ -638,6 +639,24 @@ export function activate(): () => void {
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "run.expandAllTests",
|
||||
title: "Expand All",
|
||||
category: "Run",
|
||||
icon: "expand-all",
|
||||
when: "projectOpen && activeToolWindow == 'run'",
|
||||
keyWhen: TEST_TREE_FOCUS,
|
||||
run: () => testTree.expandAll?.(),
|
||||
},
|
||||
{
|
||||
id: "run.collapseAllTests",
|
||||
title: "Collapse All",
|
||||
category: "Run",
|
||||
icon: "collapse-all",
|
||||
when: "projectOpen && activeToolWindow == 'run'",
|
||||
keyWhen: TEST_TREE_FOCUS,
|
||||
run: () => testTree.collapseAll?.(),
|
||||
},
|
||||
{
|
||||
id: "run.reloadConfigs",
|
||||
title: "Reload Run Configurations",
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
produceContextChoices,
|
||||
produceDirectory,
|
||||
produceFile,
|
||||
produceFuzz,
|
||||
shebang,
|
||||
shellWord,
|
||||
fileTargets,
|
||||
@@ -423,7 +424,12 @@ describe("single-file producers (scratches)", () => {
|
||||
expect(main.debug!.build.command).toMatch(
|
||||
/^mkdir -p \/tmp\/openidea-run && \/bin\/zig build-exe calc\.zig -femit-bin=\/tmp\/openidea-run\/calc-\w+$/,
|
||||
);
|
||||
expect(main.debug!.config).toMatchObject({ kind: "native", debugAdapter: "codelldb", args: [] });
|
||||
expect(main.debug!.config).toMatchObject({
|
||||
kind: "native",
|
||||
debugAdapter: "codelldb",
|
||||
args: [],
|
||||
params: { language: "zig" },
|
||||
});
|
||||
|
||||
const test = produceContext(scratch("calc.zig", src, 3), e)!;
|
||||
expect(test).toMatchObject({ name: "adds two numbers", scope: "element" });
|
||||
@@ -1137,6 +1143,57 @@ describe("Go test names (GoLand)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Go Run with Fuzzing (GoLand)", () => {
|
||||
const GO = [
|
||||
cfg({ id: "go:test", kind: "go", command: "go", args: ["test", "./..."], isTest: true, debugAdapter: "delve" }),
|
||||
];
|
||||
const src = [
|
||||
"package parse", // 0
|
||||
'import "testing"',
|
||||
"func TestParse(t *testing.T) {}", // 2
|
||||
"func BenchmarkParse(b *testing.B) {}",
|
||||
"func ExampleParse() {}",
|
||||
"func FuzzParse(f *testing.F) {", // 5
|
||||
'\tf.Add("x")',
|
||||
"\tf.Fuzz(func(t *testing.T, s string) {", // 7
|
||||
"\t})",
|
||||
"}",
|
||||
"func helper() {}", // 10
|
||||
].join("\n");
|
||||
const modules = (dir: string) => (dir === ROOT ? "example.com/fixture" : undefined);
|
||||
const at = (line: number | undefined, path = `${ROOT}/internal/parse/parse_test.go`, content = src) =>
|
||||
produceFuzz({ path, root: ROOT, configs: GO, content, line, goModule: modules }, ALL);
|
||||
|
||||
it("the Fuzz function at the caret, its body included, fuzzes its package", () => {
|
||||
for (const line of [5, 7]) {
|
||||
const p = at(line)!;
|
||||
expect(p.name).toBe("FuzzParse in example.com/fixture/internal/parse");
|
||||
expect(p.config).toMatchObject({
|
||||
args: ["test", "./internal/parse", "-run", "^FuzzParse$", "-fuzz", "^FuzzParse$"],
|
||||
name: "FuzzParse in example.com/fixture/internal/parse (fuzzing)",
|
||||
isTest: true,
|
||||
});
|
||||
}
|
||||
expect(at(5, `${ROOT}/parse_test.go`)!.config!.args).toEqual([
|
||||
"test",
|
||||
".",
|
||||
"-run",
|
||||
"^FuzzParse$",
|
||||
"-fuzz",
|
||||
"^FuzzParse$",
|
||||
]);
|
||||
});
|
||||
|
||||
it("nothing for tests, benchmarks, examples, other code or the file", () => {
|
||||
for (const line of [0, 2, 3, 4, 10, undefined]) expect(at(line)).toBeNull();
|
||||
// Not a test file: `go test` doesn't build its Fuzz functions as fuzz targets.
|
||||
expect(at(5, `${ROOT}/internal/parse/parse.go`)).toBeNull();
|
||||
// `Fuzzer` is not a fuzz target name; a Fuzz function needs a *testing.F.
|
||||
const misnamed = "package p\nfunc Fuzzer(f *testing.F) {}\nfunc FuzzT(t *testing.T) {}";
|
||||
for (const line of [1, 2]) expect(at(line, undefined, misnamed)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("CMake file context", () => {
|
||||
const configure = cfg({
|
||||
id: "cmake:build:configure",
|
||||
|
||||
@@ -31,7 +31,7 @@ import { djangoLabel, djangoTestsOf, hasDjangoTests } from "./djangoTypes";
|
||||
import { firstTopLevelType, scanJvmTargets, simpleClassName } from "./jvmTargets";
|
||||
import { isWindows } from "./jvmTypes";
|
||||
import { inheritedRunTargets } from "./inheritedMain";
|
||||
import { detectRunTargets, targetConfig, targetLanguage, zigTargets, type RunTarget } from "./targets";
|
||||
import { detectRunTargets, goFuzzConfig, targetConfig, targetLanguage, zigTargets, type RunTarget } from "./targets";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
export interface LocatedTool {
|
||||
@@ -660,7 +660,15 @@ function zigFile(input: ContextInput, env: ToolEnv, s: FileSite, test?: { name:
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
};
|
||||
const binary: RunConfig = { ...config, kind: "native", command: out, args: [], isTest: false };
|
||||
const binary: RunConfig = {
|
||||
...config,
|
||||
kind: "native",
|
||||
command: out,
|
||||
args: [],
|
||||
isTest: false,
|
||||
// Marks the debugged program as Zig: CodeLLDB's source mode stays off (see nativeLaunch).
|
||||
params: { language: "zig" },
|
||||
};
|
||||
return { name, scope, config, debug: { build: buildConfig, config: binary } };
|
||||
}
|
||||
|
||||
@@ -1164,6 +1172,17 @@ export function produceContext(input: ContextInput, env: ToolEnv): Produced | nu
|
||||
return produceFile(input, env);
|
||||
}
|
||||
|
||||
/** GoLand's "Run '<name>' with Fuzzing": the `Fuzz` function at the caret, run with `go test -fuzz`. */
|
||||
export function produceFuzz(input: ContextInput, env: ToolEnv): Produced | null {
|
||||
input = scopedInput(input);
|
||||
if (input.content === undefined || input.line === undefined || !/_test\.go$/.test(input.path)) return null;
|
||||
const targets = fileTargets(input, input.content.slice(0, 400_000));
|
||||
const inner = innermostTarget(input.content, targets, input.line);
|
||||
const produced = inner && elementProduction(input, env, inner);
|
||||
const config = inner && produced?.config && goFuzzConfig(produced.config, inner);
|
||||
return produced && config ? { ...produced, config } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every configuration that can run the context, when several test
|
||||
* configurations match it equally well (`npm run test` and `npm run test:unit`):
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
canDebugProduced,
|
||||
choiceItems,
|
||||
executeContext,
|
||||
fuzzItems,
|
||||
launchProduced,
|
||||
modifyContext,
|
||||
produceResolved,
|
||||
@@ -123,6 +124,7 @@ export function targetMenuItems(target: RunTarget, path: string, content: string
|
||||
...runExecutors()
|
||||
.filter((e) => !!p?.config && e.supports(p.config))
|
||||
.map((e) => ({ label: e.label(name), icon: e.icon, run: () => void executeContext(e.id, context) })),
|
||||
...fuzzItems(input, context),
|
||||
{ kind: "separator" },
|
||||
{ label: "Modify Run Configuration…", icon: "edit", run: () => void modifyContext(context) },
|
||||
];
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { detectRunTargets, jsNamePattern, targetConfig } from "./targets";
|
||||
import { detectRunTargets, goFuzzConfig, jsNamePattern, targetConfig, type RunTarget } from "./targets";
|
||||
|
||||
const cfg = (over: Partial<RunConfig> & { id: string; kind: string }): RunConfig => ({
|
||||
name: over.id,
|
||||
@@ -239,6 +239,99 @@ describe("Go test targets", () => {
|
||||
"-test.short",
|
||||
]);
|
||||
});
|
||||
describe("Run with Fuzzing", () => {
|
||||
const text = [
|
||||
"package parse",
|
||||
"func TestParse(t *testing.T) {}",
|
||||
"func BenchmarkParse(b *testing.B) {}",
|
||||
"func FuzzParse(f *testing.F) {",
|
||||
' f.Add("x")',
|
||||
" f.Fuzz(func(t *testing.T, s string) {})",
|
||||
"}",
|
||||
"func ExampleParse() {}",
|
||||
].join("\n");
|
||||
const base = cfg({ id: "go:test", kind: "go", args: ["test", "-tags", "demo", "./...", "-args", "-test.short"] });
|
||||
const fuzzOf = (rel: string, name: string, configs = [base]) => {
|
||||
const target = detectRunTargets(text, rel).find((t) => t.name === name)!;
|
||||
const config = targetConfig(target, rel, configs, text)!;
|
||||
return goFuzzConfig(config, target);
|
||||
};
|
||||
|
||||
it("adds -fuzz with the -run pattern of a Fuzz function", () => {
|
||||
const config = fuzzOf("parse/parse_test.go", "FuzzParse")!;
|
||||
expect(config.args).toEqual([
|
||||
"test",
|
||||
"-tags",
|
||||
"demo",
|
||||
"./parse",
|
||||
"-run",
|
||||
"^FuzzParse$",
|
||||
"-fuzz",
|
||||
"^FuzzParse$",
|
||||
"-args",
|
||||
"-test.short",
|
||||
]);
|
||||
// A temporary configuration of its own, beside the plain run of the fuzz target.
|
||||
expect(config.id).not.toBe(
|
||||
targetConfig(detectRunTargets(text, "parse/parse_test.go")[2]!, "parse/parse_test.go", [base], text)!.id,
|
||||
);
|
||||
expect(config.name).toBe("FuzzParse (fuzzing)");
|
||||
});
|
||||
|
||||
it("runs a fuzz target at the module root and in nested package directories", () => {
|
||||
expect(fuzzOf("parse_test.go", "FuzzParse")!.args.slice(3, 4)).toEqual(["."]);
|
||||
expect(fuzzOf("internal/text/parse/parse_test.go", "FuzzParse")!.args.slice(3, 4)).toEqual([
|
||||
"./internal/text/parse",
|
||||
]);
|
||||
});
|
||||
|
||||
it("is offered for Fuzz functions only", () => {
|
||||
for (const name of ["TestParse", "BenchmarkParse", "ExampleParse"])
|
||||
expect(fuzzOf("parse/parse_test.go", name)).toBeNull();
|
||||
const npm = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"] });
|
||||
const js: RunTarget = { line: 0, kind: "test", name: "Fuzz it", path: ["Fuzz it"] };
|
||||
expect(goFuzzConfig(targetConfig(js, "src/a.test.ts", [npm])!, js)).toBeNull();
|
||||
});
|
||||
|
||||
it("escapes the name and replaces a saved selection", () => {
|
||||
const saved = cfg({
|
||||
id: "go:saved",
|
||||
kind: "go",
|
||||
args: ["test", "-fuzz=Old", "-run", "Old", "-bench", ".", "./parse", "-fuzztime", "30s"],
|
||||
});
|
||||
const target: RunTarget = { line: 0, kind: "test", name: "Fuzz.Δ+", path: ["Fuzz.Δ+"] };
|
||||
expect(goFuzzConfig(saved, target)!.args).toEqual([
|
||||
"test",
|
||||
"-fuzztime",
|
||||
"30s",
|
||||
"./parse",
|
||||
"-run",
|
||||
"^Fuzz\\.Δ\\+$",
|
||||
"-fuzz",
|
||||
"^Fuzz\\.Δ\\+$",
|
||||
]);
|
||||
});
|
||||
|
||||
it("needs exactly one package: -fuzz cannot match across packages", () => {
|
||||
const target: RunTarget = { line: 0, kind: "test", name: "FuzzParse", path: ["FuzzParse"] };
|
||||
const go = (args: string[]) => cfg({ id: "go:x", kind: "go", args });
|
||||
expect(goFuzzConfig(go(["test", "./..."]), target)).toBeNull();
|
||||
expect(goFuzzConfig(go(["test", "./a", "./b"]), target)).toBeNull();
|
||||
expect(goFuzzConfig(go(["run", "."]), target)).toBeNull();
|
||||
expect(goFuzzConfig(go(["test", "./a"]), target)).not.toBeNull();
|
||||
});
|
||||
|
||||
it("keeps a Go Test configuration's form in step", () => {
|
||||
const typed = cfg({
|
||||
id: "go:typed",
|
||||
kind: "go",
|
||||
args: ["test", "-tags", "demo", "."],
|
||||
params: { goKind: "test", scope: "package", target: ".", toolArgs: "-tags demo" },
|
||||
});
|
||||
const config = fuzzOf("parse/parse_test.go", "FuzzParse", [typed])!;
|
||||
expect(config.params).toMatchObject({ pattern: "^FuzzParse$", toolArgs: "-tags demo -fuzz '^FuzzParse$'" });
|
||||
});
|
||||
});
|
||||
it("uses the module and overrides a saved filter before binary arguments", () => {
|
||||
const base = cfg({
|
||||
id: "go:typed",
|
||||
|
||||
@@ -415,6 +415,29 @@ function withLast(args: string[], f: (last: string) => string): string[] {
|
||||
return args.length ? [...args.slice(0, -1), f(args[args.length - 1]!)] : args;
|
||||
}
|
||||
|
||||
/**
|
||||
* GoLand's "Run with Fuzzing" of a `Fuzz` function: its `go test` configuration with
|
||||
* `-fuzz` added. Null for other targets, and when the configuration doesn't test one
|
||||
* package (`go test -fuzz` refuses several).
|
||||
*/
|
||||
export function goFuzzConfig(config: RunConfig, target: RunTarget): RunConfig | null {
|
||||
if (target.kind !== "test" || target.path.length !== 1 || !/^Fuzz/.test(target.name)) return null;
|
||||
if (config.kind !== "go" || config.args[0] !== "test") return null;
|
||||
const parts = goTestParts(config.args);
|
||||
if (parts.targets.length !== 1 || /(^|\/)\.\.\.$/.test(parts.targets[0]!)) return null;
|
||||
const pattern = `^${escapeRegExp(target.name)}$`;
|
||||
const flags = withoutGoSelection(parts.flags);
|
||||
return {
|
||||
...config,
|
||||
id: `${config.id}:fuzz`,
|
||||
name: `${config.name} (fuzzing)`,
|
||||
args: ["test", ...flags, ...parts.targets, "-run", pattern, "-fuzz", pattern, ...withoutGoSelection(parts.program)],
|
||||
...(config.params?.goKind
|
||||
? { params: { ...config.params, pattern, toolArgs: formatArgs([...flags, "-fuzz", pattern]) } }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Run configuration for one target, or null when the project has no matching runner. */
|
||||
export function targetConfig(
|
||||
target: RunTarget,
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
/** Context key: the test results tree has focus. */
|
||||
export const TEST_TREE_FOCUS = "testTreeFocus";
|
||||
|
||||
/** Set while a test results tree is shown: Expand All / Collapse All act on it. */
|
||||
export const testTree: { expandAll: (() => void) | null; collapseAll: (() => void) | null } = {
|
||||
expandAll: null,
|
||||
collapseAll: null,
|
||||
};
|
||||
@@ -167,6 +167,30 @@ describe("rerunFailedConfig", () => {
|
||||
expect(new Set(configs.map((config) => config.id)).size).toBe(2);
|
||||
});
|
||||
|
||||
it("zig: --test-filter per failed test, straight for `zig test` and via the module root for `zig build`", async () => {
|
||||
expect(
|
||||
(await rerunFailedConfig(cfg("zig", "zig", ["test", "src/calc.zig"]), [
|
||||
["calc", "adds"],
|
||||
["calc", "subs"],
|
||||
]))!.args,
|
||||
).toEqual(["test", "src/calc.zig", "--test-filter", "adds", "--test-filter", "subs"]);
|
||||
// Existing filters are replaced, not stacked.
|
||||
expect(
|
||||
(await rerunFailedConfig(cfg("zig", "zig", ["test", "src/calc.zig", "--test-filter", "adds"]), [
|
||||
["calc", "subs"],
|
||||
]))!.args,
|
||||
).toEqual(["test", "src/calc.zig", "--test-filter", "subs"]);
|
||||
// `zig build` forwards no args to the test binary: rerun goes through the module root
|
||||
// the detection recorded.
|
||||
expect(
|
||||
(await rerunFailedConfig({ ...cfg("zig", "zig", ["build", "test"]), params: { testRoot: "src/tally.zig" } }, [
|
||||
["tally", "subs"],
|
||||
]))!.args,
|
||||
).toEqual(["test", "src/tally.zig", "--test-filter", "subs"]);
|
||||
// Without a recorded root a build-based run can't narrow.
|
||||
expect(await rerunFailedConfig(cfg("zig", "zig", ["build", "test"]), [["tally", "subs"]])).toBeNull();
|
||||
});
|
||||
|
||||
it("gradle and maven filters", async () => {
|
||||
expect((await rerunFailedConfig(cfg("gradle", "./gradlew", ["test"]), [["com.a.FooTest", "bar()"]]))!.args).toEqual(
|
||||
["test", "--tests", "com.a.FooTest.bar"],
|
||||
|
||||
@@ -250,18 +250,17 @@ function builtinTestsConfig(config: RunConfig, paths: string[][], name: string):
|
||||
args = goArgs(config.args, paths, config.params?.scope === "file" ? config.params.target : undefined);
|
||||
break;
|
||||
case "zig": {
|
||||
// Only a standalone `zig test <file>` can filter: `zig build` forwards no args to the test binary.
|
||||
const file = config.args[0] === "test" ? config.args[1] : undefined;
|
||||
// `zig test <file>` filters directly. A build-based run (`zig build test`) forwards no
|
||||
// args to the test binary, so it re-runs through the module root the detection recorded
|
||||
// — exact for projects whose tests live in one module's import graph.
|
||||
const file = config.args[0] === "test" ? config.args[1] : config.params?.testRoot;
|
||||
const names = unique(paths.map((p) => p[p.length - 1]!).filter(Boolean));
|
||||
args =
|
||||
file && names.length
|
||||
? [
|
||||
config.args[0]!,
|
||||
file,
|
||||
...dropFlag(config.args.slice(2), ["--test-filter"]),
|
||||
...names.flatMap((n) => ["--test-filter", n]),
|
||||
]
|
||||
: null;
|
||||
if (!file || !names.length) {
|
||||
args = null;
|
||||
break;
|
||||
}
|
||||
const rest = dropFlag(config.args[0] === "test" ? config.args.slice(2) : [], ["--test-filter"]);
|
||||
args = ["test", file, ...rest, ...names.flatMap((n) => ["--test-filter", n])];
|
||||
break;
|
||||
}
|
||||
case "jvm":
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { provideToolWindowService, type ToolWindowService } from "@/workbench/contributions";
|
||||
import type { FileMatches, SearchQuery } from "@/platform/ipc";
|
||||
import { buildFindTree } from "../find/FindToolWindow";
|
||||
import type { FindDeps } from "../find/session";
|
||||
import {
|
||||
closeFindTab,
|
||||
disposeFindWindow,
|
||||
openEditorResults,
|
||||
openInFindWindow,
|
||||
@@ -38,6 +40,18 @@ const file = (rel: string): FileMatches => ({
|
||||
afterEach(disposeFindWindow);
|
||||
|
||||
describe("Find tool window tabs", () => {
|
||||
it("take the tool window and its stripe button away with the last one", () => {
|
||||
const hide = vi.fn();
|
||||
provideToolWindowService({ show: vi.fn(), hide } as unknown as ToolWindowService);
|
||||
const a = openInFindWindow(q("a"), "a", { deps });
|
||||
pinFindTab(a, true);
|
||||
const b = openInFindWindow(q("b"), "b", { deps });
|
||||
closeFindTab(a);
|
||||
expect(hide).not.toHaveBeenCalled();
|
||||
closeFindTab(b);
|
||||
expect(hide).toHaveBeenCalledWith("find", { removeFromStripe: true });
|
||||
});
|
||||
|
||||
it("reuses the selected tab unless it is pinned", () => {
|
||||
const a = openInFindWindow(q("a"), "a", { deps });
|
||||
const b = openInFindWindow(q("b"), "b", { deps });
|
||||
|
||||
@@ -134,6 +134,8 @@ export function closeFindTab(id: number) {
|
||||
const active = s.active === id ? (tabs[Math.min(i, tabs.length - 1)]?.id ?? null) : s.active;
|
||||
return { tabs, active };
|
||||
});
|
||||
// As in IDEA, the tool window and its stripe button go away with its last tab.
|
||||
if (!useFindWindow.getState().tabs.length) maybeToolWindowService()?.hide("find", { removeFromStripe: true });
|
||||
}
|
||||
|
||||
export function disposeFindWindow() {
|
||||
|
||||
@@ -71,6 +71,7 @@ import {
|
||||
setCommitDiffPreview,
|
||||
setDiffPreview,
|
||||
setGroupByDir,
|
||||
setGroupByRepo,
|
||||
setGroupByStaging,
|
||||
useCommit,
|
||||
type CommitTab,
|
||||
@@ -567,6 +568,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
const root = useVcs((s) => s.root) ?? "";
|
||||
const groupByDir = useCommit((s) => s.groupByDir);
|
||||
const groupByStaging = useCommit((s) => s.groupByStaging);
|
||||
const groupByRepo = useCommit((s) => s.groupByRepo);
|
||||
const diffPreview = useCommit((s) => s.diffPreview);
|
||||
const commitDiffPreview = useCommit((s) => s.commitDiffPreview);
|
||||
const doubleClickOpensDiff = useWorkflowSettings((s) => s.vcs.commit.doubleClickOpensDiff);
|
||||
@@ -584,8 +586,8 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
const heads = useVcs((s) => s.heads);
|
||||
const projectRoots = useEffectiveRoots();
|
||||
const roots = useMemo(
|
||||
() => buildChangeTree(status, root, groupByDir, lists, repos, groupByStaging, heads),
|
||||
[status, root, groupByDir, lists, repos, groupByStaging, heads],
|
||||
() => buildChangeTree(status, root, groupByDir, lists, repos, groupByStaging, heads, groupByRepo),
|
||||
[status, root, groupByDir, lists, repos, groupByStaging, heads, groupByRepo],
|
||||
);
|
||||
const [byKey, parents] = useMemo(() => {
|
||||
const m = new Map<string, ChangeNode>();
|
||||
@@ -703,6 +705,10 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
showContextMenu(bottomLeft(viewRef.current), [
|
||||
{ kind: "header", label: "Group By" },
|
||||
{ label: "Directory", checked: groupByDir, run: () => setGroupByDir(!groupByDir) },
|
||||
// IDEA offers it once the project has several repositories.
|
||||
...(repos.length > 1
|
||||
? [{ label: "Repository", checked: groupByRepo, run: () => setGroupByRepo(!groupByRepo) }]
|
||||
: []),
|
||||
{ label: "Staging State", checked: groupByStaging, run: () => setGroupByStaging(!groupByStaging) },
|
||||
...(mode === "local"
|
||||
? [
|
||||
|
||||
@@ -10,12 +10,23 @@ const mocks = vi.hoisted(() => ({
|
||||
restoreBranch: vi.fn(),
|
||||
branches: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
ask: vi.fn(),
|
||||
checkout: vi.fn(),
|
||||
executeAction: vi.fn(),
|
||||
}));
|
||||
vi.mock("../dialogs", async (original) => ({
|
||||
...(await original<typeof import("../dialogs")>()),
|
||||
promptText: mocks.prompt,
|
||||
confirmDialog: mocks.confirm,
|
||||
}));
|
||||
vi.mock("@/workbench/messages", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/messages")>()),
|
||||
ask: mocks.ask,
|
||||
}));
|
||||
vi.mock("@/platform/actions", async (original) => ({
|
||||
...(await original<typeof import("@/platform/actions")>()),
|
||||
executeAction: mocks.executeAction,
|
||||
}));
|
||||
vi.mock("@/workbench/contributions", () => ({ notifications: () => ({ notify: mocks.notify, expire: vi.fn() }) }));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
@@ -29,10 +40,11 @@ vi.mock("@/platform/ipc", async (original) => {
|
||||
vcsRestoreBranch: mocks.restoreBranch,
|
||||
vcsBranches: mocks.branches,
|
||||
vcsRenameBranch: mocks.rename,
|
||||
vcsCheckout: mocks.checkout,
|
||||
},
|
||||
};
|
||||
});
|
||||
import { deleteBranch, deleteBranches, newBranch, newBranchInRepos, renameBranch } from "../branchOps";
|
||||
import { checkoutBranch, deleteBranch, deleteBranches, newBranch, newBranchInRepos, renameBranch } from "../branchOps";
|
||||
import { useVcs } from "../store";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
@@ -175,6 +187,38 @@ it("deletes a worktree holding the branch before deleting it", async () => {
|
||||
expect(mocks.deleteBranch).toHaveBeenCalledWith("/p/front", "feature/wt");
|
||||
});
|
||||
|
||||
it("offers to open the worktree that has the branch checked out", async () => {
|
||||
mocks.checkout.mockResolvedValue(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path: "/p/front-wt" }));
|
||||
mocks.ask.mockResolvedValue({ button: "open" });
|
||||
await checkoutBranch("feature/wt");
|
||||
expect(mocks.checkout).toHaveBeenCalledWith("/p/front", "feature/wt", false, { mode: "normal", diverged: null });
|
||||
expect(mocks.ask.mock.calls[0]?.[0].title).toBe("Worktree Conflict");
|
||||
expect(mocks.ask.mock.calls[0]?.[0].body).toContain("already checked out in a worktree at:\n/p/front-wt");
|
||||
expect(mocks.executeAction).toHaveBeenCalledWith("file.openProjectPath", "/p/front-wt");
|
||||
expect(mocks.checkout).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("checks the branch out anyway when asked, alongside the other worktree", async () => {
|
||||
mocks.checkout
|
||||
.mockResolvedValueOnce(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path: "/p/front-wt" }))
|
||||
.mockResolvedValueOnce(ok({ kind: "done" }));
|
||||
mocks.ask.mockResolvedValue({ button: "anyway" });
|
||||
await checkoutBranch("feature/wt");
|
||||
expect(mocks.checkout).toHaveBeenLastCalledWith("/p/front", "feature/wt", false, {
|
||||
mode: "normal",
|
||||
diverged: null,
|
||||
ignoreOtherWorktrees: true,
|
||||
});
|
||||
expect(mocks.executeAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not open the worktree when the checkout offer is declined", async () => {
|
||||
mocks.checkout.mockResolvedValue(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path: "/p/front-wt" }));
|
||||
mocks.ask.mockResolvedValue({ button: "cancel" });
|
||||
await checkoutBranch("feature/wt");
|
||||
expect(mocks.executeAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the branch when the worktree question is turned down", async () => {
|
||||
mocks.worktrees.mockResolvedValue(ok([worktree("/p/front-feature-wt", "feature/wt")]));
|
||||
mocks.confirm.mockResolvedValue(false);
|
||||
|
||||
@@ -229,6 +229,97 @@ describe("several repositories", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Group By › Repository off", () => {
|
||||
const at = (path: string, unstaged: FileStatus["unstaged"] = "modified", staged: FileStatus["staged"] = null) => ({
|
||||
path,
|
||||
relPath: path.split("/").slice(3).join("/"),
|
||||
staged,
|
||||
unstaged,
|
||||
renamedFrom: null,
|
||||
});
|
||||
// Two repositories holding the same repository-relative path.
|
||||
const repos = ["/w/api", "/w/sdk"];
|
||||
const twins = [at("/w/api/src/config.ts"), at("/w/sdk/src/config.ts"), at("/w/sdk/src/client.ts")];
|
||||
const keys = (nodes: readonly ChangeNode[]): string[] => nodes.flatMap((n) => [n.key, ...keys(n.children ?? [])]);
|
||||
const files = (nodes: readonly ChangeNode[]) =>
|
||||
changeFileNodes(nodes).map((n) => `${n.label} ${n.path} ${n.detail || "-"}`);
|
||||
|
||||
it("lists the files of all repositories together, told apart by their directory", () => {
|
||||
const tree = buildChangeTree(twins, "/w", false, undefined, repos, false, {}, false);
|
||||
expect(shape(tree)).toEqual(["Changes", " client.ts", " config.ts", " config.ts"]);
|
||||
expect(files(tree)).toEqual([
|
||||
"client.ts /w/sdk/src/client.ts sdk/src",
|
||||
"config.ts /w/api/src/config.ts api/src",
|
||||
"config.ts /w/sdk/src/config.ts sdk/src",
|
||||
]);
|
||||
const all = keys(tree);
|
||||
expect(new Set(all).size).toBe(all.length);
|
||||
});
|
||||
|
||||
it("keeps directory grouping, with each repository's directories apart", () => {
|
||||
const tree = buildChangeTree(twins, "/w", true, undefined, repos, false, {}, false);
|
||||
expect(shape(tree)).toEqual([
|
||||
"Changes",
|
||||
" api/src",
|
||||
" config.ts",
|
||||
" sdk/src",
|
||||
" client.ts",
|
||||
" config.ts",
|
||||
]);
|
||||
expect(tree[0]!.children!.map((n) => [n.path, n.files.length])).toEqual([
|
||||
["/w/api/src", 1],
|
||||
["/w/sdk/src", 2],
|
||||
]);
|
||||
const all = keys(tree);
|
||||
expect(new Set(all).size).toBe(all.length);
|
||||
});
|
||||
|
||||
it("shows a repository outside the project by its absolute directory", () => {
|
||||
const outside = [at("/w/README.md"), at("/x/lib/src/Lib.kt")];
|
||||
const flat = buildChangeTree(outside, "/w", false, undefined, ["/w", "/x/lib"], false, {}, false);
|
||||
expect(files(flat)).toEqual(["Lib.kt /x/lib/src/Lib.kt /x/lib/src", "README.md /w/README.md -"]);
|
||||
const dirs = buildChangeTree(outside, "/w", true, undefined, ["/w", "/x/lib"], false, {}, false);
|
||||
expect(shape(dirs)).toEqual(["Changes", " /x/lib/src", " Lib.kt", " README.md"]);
|
||||
expect(dirs[0]!.children![0]!.path).toBe("/x/lib/src");
|
||||
});
|
||||
|
||||
it("applies to every group, staging groups and change lists included", () => {
|
||||
const mixed = [...twins, at("/w/api/new.txt", "untracked"), at("/w/sdk/src/both.ts", "modified", "modified")];
|
||||
const noRepoNodes = (tree: ChangeNode[]) =>
|
||||
tree.every((g) => g.children!.every((n) => n.type === "file" && !repos.includes(n.path!)));
|
||||
expect(noRepoNodes(buildChangeTree(mixed, "/w", false, undefined, repos, false, {}, false))).toBe(true);
|
||||
expect(noRepoNodes(buildChangeTree(mixed, "/w", false, undefined, repos, true, {}, false))).toBe(true);
|
||||
const lists = { active: "default", lists: [{ id: "default", name: "Changes", comment: "" }], files: {} };
|
||||
const listed = buildChangeTree(mixed, "/w", false, lists as never, repos, false, {}, false);
|
||||
expect(noRepoNodes(listed)).toBe(true);
|
||||
expect(changeFileNodes(listed).every((n) => n.changelist === "default" || n.group === "unversioned")).toBe(true);
|
||||
});
|
||||
|
||||
it("checks and commits files of every repository from the one flat group", () => {
|
||||
const [changes] = buildChangeTree(twins, "/w", false, undefined, repos, false, {}, false);
|
||||
expect(aggregateCheck(changes!.files, new Map())).toMatchObject({ checked: true, on: 3 });
|
||||
const checks = new Map<string, CheckState>([["/w/api/src/config.ts", "none"]]);
|
||||
expect(aggregateCheck(changes!.files, checks)).toMatchObject({ checked: false, indeterminate: true, on: 2 });
|
||||
const plan = planCommit(twins, checks);
|
||||
expect(plan.included.map((f) => f.path)).toEqual(["/w/sdk/src/config.ts", "/w/sdk/src/client.ts"]);
|
||||
expect(commitRepos(planCommit(twins, new Map()).included, repos, "/w/api")).toEqual(["/w/sdk", "/w/api"]);
|
||||
});
|
||||
|
||||
it("is on by default: a repository level as before", () => {
|
||||
expect(buildChangeTree(twins, "/w", true, undefined, repos, false, {})).toEqual(
|
||||
buildChangeTree(twins, "/w", true, undefined, repos, false, {}, true),
|
||||
);
|
||||
expect(shape(buildChangeTree(twins, "/w", false, undefined, repos))).toEqual([
|
||||
"Changes",
|
||||
" api",
|
||||
" config.ts",
|
||||
" sdk",
|
||||
" client.ts",
|
||||
" config.ts",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ignore targets", () => {
|
||||
const group = (roots: ChangeNode[], id: string) => roots.find((n) => n.group === id)!;
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return { ...real, call: vi.fn() };
|
||||
});
|
||||
|
||||
vi.mock("../DiffEditor", () => ({ DiffEditor: () => <div /> }));
|
||||
|
||||
import { ChangesTree } from "../CommitView";
|
||||
import { setGroupByRepo, useCommit } from "../commitStore";
|
||||
import { useVcs } from "../store";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { useContextMenuStore, type MenuItem } from "@/ui/Menu";
|
||||
|
||||
const change = (path: string) => ({
|
||||
path,
|
||||
relPath: path.split("/").slice(3).join("/"),
|
||||
staged: null,
|
||||
unstaged: "modified" as const,
|
||||
renamedFrom: null,
|
||||
});
|
||||
|
||||
/** The Group By items of the View Options menu: label → checked. */
|
||||
function groupByItems(): Record<string, boolean> {
|
||||
act(() => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "View Options" }));
|
||||
});
|
||||
const items = useContextMenuStore.getState().menu!.items as Array<MenuItem & { label?: string; checked?: boolean }>;
|
||||
act(() => useContextMenuStore.setState({ menu: null }));
|
||||
const end = items.findIndex((i) => i.kind === "separator");
|
||||
return Object.fromEntries(
|
||||
items
|
||||
.slice(0, end < 0 ? undefined : end)
|
||||
.filter((i) => i.kind !== "header" && i.label)
|
||||
.map((i) => [i.label!, !!i.checked]),
|
||||
);
|
||||
}
|
||||
|
||||
function runItem(label: string) {
|
||||
act(() => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "View Options" }));
|
||||
});
|
||||
const item = useContextMenuStore.getState().menu!.items.find((i) => "label" in i && i.label === label) as {
|
||||
run: () => void;
|
||||
};
|
||||
act(() => {
|
||||
item.run();
|
||||
useContextMenuStore.setState({ menu: null });
|
||||
});
|
||||
}
|
||||
|
||||
describe("Group By › Repository in the changes tree", () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
useCommit.setState({
|
||||
groupByDir: false,
|
||||
groupByStaging: false,
|
||||
groupByRepo: true,
|
||||
checks: new Map(),
|
||||
selection: [],
|
||||
});
|
||||
useProject.setState({
|
||||
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
|
||||
settings: {} as never,
|
||||
});
|
||||
useVcs.setState({
|
||||
root: "/p",
|
||||
repo: "/p",
|
||||
roots: ["/p", "/p/orders"],
|
||||
status: [change("/p/src/App.kt"), change("/p/orders/src/App.kt")],
|
||||
heads: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("is offered, checked, with several repositories", () => {
|
||||
render(<ChangesTree mode="commit" />);
|
||||
expect(groupByItems()).toEqual({ Directory: false, Repository: true, "Staging State": false });
|
||||
});
|
||||
|
||||
it("is not offered with one repository", () => {
|
||||
useVcs.setState({ roots: ["/p"], status: [change("/p/src/App.kt")] });
|
||||
render(<ChangesTree mode="commit" />);
|
||||
expect(groupByItems()).toEqual({ Directory: false, "Staging State": false });
|
||||
});
|
||||
|
||||
it("unchecked, lists both repositories' files together and remembers the choice", () => {
|
||||
render(<ChangesTree mode="commit" />);
|
||||
expect(screen.getByText("orders")).toBeTruthy();
|
||||
runItem("Repository");
|
||||
expect(useCommit.getState().groupByRepo).toBe(false);
|
||||
expect(localStorage.getItem("openidea.vcs.groupByRepo")).toBe("false");
|
||||
expect(screen.queryByText("orders")).toBeNull();
|
||||
expect(screen.getAllByText("App.kt")).toHaveLength(2);
|
||||
expect(screen.getByText("orders/src")).toBeTruthy();
|
||||
expect(groupByItems().Repository).toBe(false);
|
||||
// Each file keeps its own checkbox.
|
||||
const boxes = screen.getAllByRole("checkbox", { name: "Include App.kt in commit" });
|
||||
expect(boxes).toHaveLength(2);
|
||||
act(() => {
|
||||
fireEvent.mouseDown(boxes[0]!);
|
||||
});
|
||||
expect([...useCommit.getState().checks]).toEqual([["/p/orders/src/App.kt", "none"]]);
|
||||
runItem("Repository");
|
||||
expect(localStorage.getItem("openidea.vcs.groupByRepo")).toBe("true");
|
||||
expect(screen.getByText("orders")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Group By › Repository persistence", () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("starts on when nothing is stored", async () => {
|
||||
const { useCommit: fresh } = await import("../commitStore");
|
||||
expect(fresh.getState().groupByRepo).toBe(true);
|
||||
});
|
||||
|
||||
it("starts with the stored choice", async () => {
|
||||
setGroupByRepo(false);
|
||||
const { useCommit: fresh } = await import("../commitStore");
|
||||
expect(fresh.getState().groupByRepo).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
pushes: [] as Array<{ repo: string | null; message: string | null; paths: string[] | null }>,
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data });
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsBranchInfo: (repo: string | null) =>
|
||||
ok({
|
||||
head: repo === "/p/b" ? "dev" : "main",
|
||||
headCommit: "c1",
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
operation: null,
|
||||
}),
|
||||
vcsStashPush: (
|
||||
repo: string | null,
|
||||
message: string | null,
|
||||
_untracked: boolean,
|
||||
_keepIndex: boolean,
|
||||
paths: string[] | null,
|
||||
) => {
|
||||
mocks.pushes.push({ repo, message, paths });
|
||||
return ok(null);
|
||||
},
|
||||
vcsStashes: () => ok([]),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { VcsDialogHost } from "../dialogs";
|
||||
import { stashChanges } from "../changeOps";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.pushes = [];
|
||||
useVcs.setState({
|
||||
root: "/p",
|
||||
roots: ["/p/a", "/p/b"],
|
||||
repo: "/p/a",
|
||||
branch: { head: "main", headCommit: "c1", upstream: null, ahead: 0, behind: 0, operation: null },
|
||||
available: false,
|
||||
});
|
||||
});
|
||||
|
||||
const pick = async (combo: string, option: string) => {
|
||||
fireEvent.click(screen.getByRole("button", { name: combo }));
|
||||
fireEvent.click(await screen.findByRole("option", { name: option }));
|
||||
};
|
||||
|
||||
it("offers no repository choice when the project has one repository", async () => {
|
||||
useVcs.setState({ roots: ["/p"], repo: null });
|
||||
render(<VcsDialogHost />);
|
||||
let done!: Promise<void>;
|
||||
act(() => {
|
||||
done = stashChanges();
|
||||
});
|
||||
expect(await screen.findByText("Current branch: main")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Repository" })).toBeNull();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Stash" }));
|
||||
await done;
|
||||
expect(mocks.pushes).toEqual([{ repo: null, message: null, paths: null }]);
|
||||
});
|
||||
|
||||
it("stashes the repository picked in the dialog and shows its branch", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
let done!: Promise<void>;
|
||||
act(() => {
|
||||
done = stashChanges();
|
||||
});
|
||||
expect(await screen.findByText("Current branch: main")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Repository" })).toHaveTextContent("a");
|
||||
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Message" }), { target: { value: "wip b" } });
|
||||
await pick("Repository", "b");
|
||||
expect(await screen.findByText("Current branch: dev")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Current branch: main")).toBeNull();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Stash" }));
|
||||
await done;
|
||||
expect(mocks.pushes).toEqual([{ repo: "/p/b", message: "wip b", paths: null }]);
|
||||
});
|
||||
|
||||
it("starts on the repository it was given and can switch back", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
let done!: Promise<void>;
|
||||
act(() => {
|
||||
done = stashChanges([], "/p/b");
|
||||
});
|
||||
expect(await screen.findByText("Current branch: dev")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Repository" })).toHaveTextContent("b");
|
||||
|
||||
await pick("Repository", "a");
|
||||
expect(await screen.findByText("Current branch: main")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Stash" }));
|
||||
await done;
|
||||
expect(mocks.pushes).toEqual([{ repo: "/p/a", message: null, paths: null }]);
|
||||
});
|
||||
|
||||
it("offers no repository choice when stashing selected files, which pick their own repositories", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
let done!: Promise<void>;
|
||||
act(() => {
|
||||
done = stashChanges(["/p/a/x.ts", "/p/b/y.ts"]);
|
||||
});
|
||||
expect(await screen.findByText("Current branch: main")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Repository" })).toBeNull();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Stash" }));
|
||||
await done;
|
||||
expect(mocks.pushes).toEqual([{ repo: "/p/a", message: null, paths: ["/p/a/x.ts", "/p/b/y.ts"] }]);
|
||||
});
|
||||
|
||||
it("stashes nothing when cancelled after picking another repository", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
let done!: Promise<void>;
|
||||
act(() => {
|
||||
done = stashChanges();
|
||||
});
|
||||
await pick("Repository", "b");
|
||||
expect(await screen.findByText("Current branch: dev")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
await done;
|
||||
await waitFor(() => expect(screen.queryByRole("button", { name: "Repository" })).toBeNull());
|
||||
expect(mocks.pushes).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
created: [] as Array<{ repo: string | null; name: string; commit: string; message: string | null; force: boolean }>,
|
||||
tags: {} as Record<string, Promise<string[]> | string[]>,
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data });
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsTags: async (repo: string | null) => ({ status: "ok" as const, data: await (mocks.tags[repo ?? ""] ?? []) }),
|
||||
vcsCreateTag: (repo: string | null, name: string, commit: string, message: string | null, force: boolean) => {
|
||||
mocks.created.push({ repo, name, commit, message, force });
|
||||
return ok(null);
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { VcsDialogHost } from "../dialogs";
|
||||
import { showTagDialog } from "../operations";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.created = [];
|
||||
mocks.tags = { "/p/a": ["v1.0"], "/p/b": ["v2.0"], "/p": ["v1.0"] };
|
||||
useVcs.setState({
|
||||
root: "/p",
|
||||
roots: ["/p/a", "/p/b"],
|
||||
repo: "/p/a",
|
||||
branch: { head: "main", headCommit: "c1", upstream: null, ahead: 0, behind: 0, operation: null },
|
||||
available: false,
|
||||
});
|
||||
});
|
||||
|
||||
const pick = async (combo: string, option: string) => {
|
||||
fireEvent.click(screen.getByRole("button", { name: combo }));
|
||||
fireEvent.click(await screen.findByRole("option", { name: option }));
|
||||
};
|
||||
|
||||
const typeName = (value: string) => fireEvent.change(screen.getByLabelText("Tag name:"), { target: { value } });
|
||||
|
||||
it("offers no repository choice when the project has one repository", async () => {
|
||||
useVcs.setState({ roots: ["/p"], repo: null });
|
||||
mocks.tags = { "": ["v1.0"] };
|
||||
render(<VcsDialogHost />);
|
||||
await act(() => showTagDialog());
|
||||
expect(await screen.findByText("Tag")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Repository" })).toBeNull();
|
||||
|
||||
typeName("v1.0");
|
||||
expect(await screen.findByText("Tag 'v1.0' already exists")).toBeInTheDocument();
|
||||
typeName("v1.1");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Tag" }));
|
||||
await waitFor(() => expect(mocks.created).toHaveLength(1));
|
||||
expect(mocks.created[0]).toMatchObject({ repo: null, name: "v1.1", commit: "HEAD" });
|
||||
});
|
||||
|
||||
it("creates the tag in the repository picked in the dialog", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
await act(() => showTagDialog());
|
||||
expect(screen.getByRole("button", { name: "Repository" })).toHaveTextContent("a");
|
||||
|
||||
await pick("Repository", "b");
|
||||
expect(screen.getByRole("button", { name: "Repository" })).toHaveTextContent("b");
|
||||
typeName("v3.0");
|
||||
fireEvent.change(screen.getByLabelText("Message:"), { target: { value: "Release" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Tag" }));
|
||||
await waitFor(() => expect(mocks.created).toHaveLength(1));
|
||||
expect(mocks.created[0]).toEqual({ repo: "/p/b", name: "v3.0", commit: "HEAD", message: "Release", force: false });
|
||||
});
|
||||
|
||||
it("checks the name against the tags of the picked repository", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
await act(() => showTagDialog());
|
||||
|
||||
typeName("v1.0");
|
||||
expect(await screen.findByText("Tag 'v1.0' already exists")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Create Tag" })).toBeDisabled();
|
||||
|
||||
// v1.0 exists only in a: the name is free in b, and b's own v2.0 is taken.
|
||||
await pick("Repository", "b");
|
||||
await waitFor(() => expect(screen.queryByText("Tag 'v1.0' already exists")).toBeNull());
|
||||
expect(screen.getByRole("button", { name: "Create Tag" })).toBeEnabled();
|
||||
typeName("v2.0");
|
||||
expect(await screen.findByText("Tag 'v2.0' already exists")).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
expect(mocks.created).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores the tags of a repository that is no longer picked", async () => {
|
||||
let resolveA: (tags: string[]) => void = () => undefined;
|
||||
mocks.tags["/p/a"] = new Promise<string[]>((resolve) => (resolveA = resolve));
|
||||
render(<VcsDialogHost />);
|
||||
await act(() => showTagDialog());
|
||||
|
||||
await pick("Repository", "b");
|
||||
typeName("v1.0");
|
||||
// a's tags arrive after b was picked: they must not mark v1.0 as taken in b.
|
||||
await act(async () => resolveA(["v1.0"]));
|
||||
expect(screen.queryByText("Tag 'v1.0' already exists")).toBeNull();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Tag" }));
|
||||
await waitFor(() => expect(mocks.created).toHaveLength(1));
|
||||
expect(mocks.created[0]).toMatchObject({ repo: "/p/b", name: "v1.0" });
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { Stash } from "@/bindings";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
stashes: new Map<string | null, Stash[]>(),
|
||||
drops: [] as Array<{ repo: string | null; index: number }>,
|
||||
diffs: [] as Array<{ repo: string | null; from: string; to: string }>,
|
||||
applies: [] as Array<{ repo: string | null; index: number }>,
|
||||
confirm: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data });
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsStashes: (repo: string | null) => ok(mocks.stashes.get(repo) ?? []),
|
||||
vcsStashDrop: (repo: string | null, index: number) => {
|
||||
mocks.drops.push({ repo, index });
|
||||
const list = mocks.stashes.get(repo) ?? [];
|
||||
mocks.stashes.set(
|
||||
repo,
|
||||
list.filter((s) => s.index !== index).map((s) => (s.index > index ? { ...s, index: s.index - 1 } : s)),
|
||||
);
|
||||
return ok(null);
|
||||
},
|
||||
vcsStashApply: (repo: string | null, index: number) => {
|
||||
mocks.applies.push({ repo, index });
|
||||
return ok(null);
|
||||
},
|
||||
vcsDiffRevisions: (repo: string | null, from: string, to: string) => {
|
||||
mocks.diffs.push({ repo, from, to });
|
||||
return ok([{ path: "src/a.ts", kind: "modified", oldPath: null }]);
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../dialogs", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../dialogs")>()),
|
||||
confirmDialog: mocks.confirm,
|
||||
}));
|
||||
|
||||
import { VcsDialogHost } from "../dialogs";
|
||||
import { showUnstashDialog } from "../changeOps";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const stash = (index: number, message: string): Stash => ({ index, message, timeMs: null });
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.stashes = new Map([
|
||||
["/p/a", [stash(0, "On main: a0")]],
|
||||
["/p/b", [stash(0, "On dev: first"), stash(1, "On dev: second"), stash(2, "On dev: third")]],
|
||||
]);
|
||||
mocks.drops = [];
|
||||
mocks.diffs = [];
|
||||
mocks.applies = [];
|
||||
mocks.confirm.mockReset().mockResolvedValue(true);
|
||||
useVcs.setState({ root: "/p", roots: ["/p/a", "/p/b"], repo: "/p/a", available: false });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Dialogs live in a module store: close what a test left open.
|
||||
for (let open = screen.queryAllByRole("dialog"); open.length; open = screen.queryAllByRole("dialog")) {
|
||||
const before = open.length;
|
||||
fireEvent.keyDown(open[open.length - 1]!, { key: "Escape" });
|
||||
if (screen.queryAllByRole("dialog").length === before) break;
|
||||
}
|
||||
});
|
||||
|
||||
const radio = (name: string) => screen.getByRole("radio", { name: new RegExp(name.replace(/[{}@]/g, "\\$&")) });
|
||||
|
||||
it("disables Show Changes and Drop Stash when there is no stash", async () => {
|
||||
mocks.stashes.set("/p/a", []);
|
||||
render(<VcsDialogHost />);
|
||||
act(() => showUnstashDialog(0, "/p/a"));
|
||||
expect(await screen.findByText("No stashes")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Show Changes" })).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "Drop Stash" })).toBeDisabled();
|
||||
});
|
||||
|
||||
it("views the changes of the selected stash in the dialog's repository", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
act(() => showUnstashDialog(0, "/p/b"));
|
||||
await screen.findByText("stash@{0}: On dev: first");
|
||||
fireEvent.click(radio("stash@{1}"));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Show Changes" }));
|
||||
|
||||
await waitFor(() => expect(mocks.diffs).toEqual([{ repo: "/p/b", from: "stash@{1}^", to: "stash@{1}" }]));
|
||||
expect(await screen.findByText(/Changes between stash@\{1\}\^ and stash@\{1\}/)).toBeInTheDocument();
|
||||
// The Unstash dialog stays open behind the changes, nothing applied or dropped.
|
||||
expect(screen.getByText("stash@{2}: On dev: third")).toBeInTheDocument();
|
||||
expect(mocks.applies).toEqual([]);
|
||||
expect(mocks.drops).toEqual([]);
|
||||
});
|
||||
|
||||
it("drops the selected stash after confirming, refreshes the list and selects the next one", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
act(() => showUnstashDialog(0, "/p/b"));
|
||||
await screen.findByText("stash@{0}: On dev: first");
|
||||
fireEvent.click(radio("stash@{1}"));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Drop Stash" }));
|
||||
|
||||
await waitFor(() => expect(mocks.drops).toEqual([{ repo: "/p/b", index: 1 }]));
|
||||
expect(mocks.confirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Drop Stash", danger: true }));
|
||||
await waitFor(() => expect(screen.queryByText("stash@{1}: On dev: second")).toBeNull());
|
||||
// The older stash moved up into the dropped one's place and is selected.
|
||||
expect(screen.getByText("stash@{1}: On dev: third")).toBeInTheDocument();
|
||||
expect(radio("stash@{1}")).toBeChecked();
|
||||
expect(radio("stash@{0}")).not.toBeChecked();
|
||||
|
||||
// The dialog stays open and acts on the refreshed list.
|
||||
fireEvent.click(screen.getByRole("button", { name: "Apply Stash" }));
|
||||
await waitFor(() => expect(mocks.applies).toEqual([{ repo: "/p/b", index: 1 }]));
|
||||
});
|
||||
|
||||
it("selects the new last stash after dropping the last one, and disables both when none is left", async () => {
|
||||
mocks.stashes.set("/p/b", [stash(0, "On dev: first"), stash(1, "On dev: second")]);
|
||||
render(<VcsDialogHost />);
|
||||
act(() => showUnstashDialog(1, "/p/b"));
|
||||
await screen.findByText("stash@{1}: On dev: second");
|
||||
expect(radio("stash@{1}")).toBeChecked();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Drop Stash" }));
|
||||
await waitFor(() => expect(screen.queryByText("stash@{1}: On dev: second")).toBeNull());
|
||||
expect(radio("stash@{0}")).toBeChecked();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Drop Stash" }));
|
||||
expect(await screen.findByText("No stashes")).toBeInTheDocument();
|
||||
expect(mocks.drops).toEqual([
|
||||
{ repo: "/p/b", index: 1 },
|
||||
{ repo: "/p/b", index: 0 },
|
||||
]);
|
||||
expect(screen.getByRole("button", { name: "Show Changes" })).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "Drop Stash" })).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "Apply Stash" })).toBeDisabled();
|
||||
});
|
||||
|
||||
it("keeps the stash when the drop is not confirmed", async () => {
|
||||
mocks.confirm.mockResolvedValue(false);
|
||||
render(<VcsDialogHost />);
|
||||
act(() => showUnstashDialog(0, "/p/a"));
|
||||
await screen.findByText("stash@{0}: On main: a0");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Drop Stash" }));
|
||||
await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.drops).toEqual([]);
|
||||
expect(screen.getByText("stash@{0}: On main: a0")).toBeInTheDocument();
|
||||
expect(radio("stash@{0}")).toBeChecked();
|
||||
});
|
||||
@@ -431,6 +431,8 @@ export function registerVcsActions(): () => void {
|
||||
useChangelists.getState().state,
|
||||
state.roots,
|
||||
useCommit.getState().groupByStaging,
|
||||
undefined,
|
||||
useCommit.getState().groupByRepo,
|
||||
);
|
||||
// The modal interface has one front diff window (#1863): a file with its group
|
||||
// as the F7 chain, or several selected files as the chain.
|
||||
|
||||
@@ -132,6 +132,24 @@ async function performCheckout(
|
||||
options = { ...options, diverged: r.button };
|
||||
continue;
|
||||
}
|
||||
case "checkedOutInWorktree": {
|
||||
const { branch, path } = outcome;
|
||||
const r = await ask({
|
||||
title: "Worktree Conflict",
|
||||
body: tx`Branch '${branch}' is already checked out in a worktree at:\n${path}`,
|
||||
buttons: [
|
||||
{ id: "anyway", label: "Checkout Anyway", primary: true },
|
||||
{ id: "open", label: "Open Existing Worktree" },
|
||||
{ id: "cancel", label: "Cancel" },
|
||||
],
|
||||
});
|
||||
if (r.button === "anyway") {
|
||||
options = { ...options, ignoreOtherWorktrees: true };
|
||||
continue;
|
||||
}
|
||||
if (r.button === "open") await executeAction("file.openProjectPath", path);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { FileStatus, Stash } from "@/bindings";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { Checkbox, Dialog, Icon, Input, T, fileIconName } from "@/ui";
|
||||
import { Checkbox, Dialog, Icon, IconButton, Input, T, fileIconName } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { groupOf, remainingOverrides, renamedFromPath } from "./changes";
|
||||
import { runCommitChecks } from "./commitChecks";
|
||||
@@ -11,8 +11,10 @@ import { forgetAmendDraft, keepMessageAfterCommit, rememberMessage, useCommit }
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { notifyFileOperation } from "@/platform/fileOps";
|
||||
import { confirmDialog, openDialog } from "./dialogs";
|
||||
import { RepoPicker, useBranchInfo } from "./gitMenuDialogs";
|
||||
import { KIND_COLOR, baseName, dirName, effectiveKind, relTo, stripSlash } from "./model";
|
||||
import { logConsole, runOp, saveAll } from "./ops";
|
||||
import { showCompareRevisions } from "./operations";
|
||||
import { currentRepo, loadStashes, refreshNow, useVcs } from "./store";
|
||||
import styles from "./common.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -304,11 +306,16 @@ export async function addToVcs(paths: readonly string[]) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Stash Changes dialog: message, Keep index (staged changes stay), include untracked files. */
|
||||
/**
|
||||
* Stash Changes dialog: message, Keep index (staged changes stay), include untracked files.
|
||||
* `repo`: the repository it starts on; selected `paths` stash in the repositories holding them.
|
||||
*/
|
||||
export function stashChanges(paths: readonly string[] = [], repo = currentRepo()): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const close = openDialog(() => (
|
||||
<StashDialog
|
||||
initialRepo={repo}
|
||||
pickRepo={!paths.length}
|
||||
onDone={async (r) => {
|
||||
close();
|
||||
if (r) {
|
||||
@@ -318,7 +325,7 @@ export function stashChanges(paths: readonly string[] = [], repo = currentRepo()
|
||||
() =>
|
||||
call(
|
||||
commands.vcsStashPush(
|
||||
repo,
|
||||
r.repo,
|
||||
r.message || null,
|
||||
r.includeUntracked,
|
||||
r.keepIndex,
|
||||
@@ -337,15 +344,20 @@ export function stashChanges(paths: readonly string[] = [], repo = currentRepo()
|
||||
}
|
||||
|
||||
function StashDialog({
|
||||
initialRepo,
|
||||
pickRepo,
|
||||
onDone,
|
||||
}: {
|
||||
onDone: (r: { message: string; keepIndex: boolean; includeUntracked: boolean } | null) => void;
|
||||
initialRepo: string | null;
|
||||
pickRepo: boolean;
|
||||
onDone: (r: { repo: string | null; message: string; keepIndex: boolean; includeUntracked: boolean } | null) => void;
|
||||
}) {
|
||||
const [repo, setRepo] = useState(initialRepo);
|
||||
const [message, setMessage] = useState("");
|
||||
const [keepIndex, setKeepIndex] = useState(false);
|
||||
const [includeUntracked, setIncludeUntracked] = useState(false);
|
||||
const branch = useVcs((s) => s.branch?.head ?? null);
|
||||
const submit = () => onDone({ message: message.trim(), keepIndex, includeUntracked });
|
||||
const branch = useBranchInfo(repo)?.head ?? null;
|
||||
const submit = () => onDone({ repo, message: message.trim(), keepIndex, includeUntracked });
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
@@ -364,6 +376,7 @@ function StashDialog({
|
||||
submit();
|
||||
}}
|
||||
>
|
||||
{pickRepo && <RepoPicker repo={repo} onChange={setRepo} />}
|
||||
{branch && <div className={styles.hint}>{tx`Current branch: ${branch}`}</div>}
|
||||
<label className={styles.fieldLabel}>
|
||||
<T>Message:</T>
|
||||
@@ -415,13 +428,14 @@ export function applyStash(index: number, pop: boolean, repo = currentRepo()) {
|
||||
return unstash({ index, pop, reinstateIndex: false, branch: null }, repo);
|
||||
}
|
||||
|
||||
/** Unstash Changes dialog: pick a stash; Pop, Reinstate index, or As new branch. */
|
||||
/** Unstash Changes dialog: pick a stash; Pop, Reinstate index, or As new branch; view or drop it. */
|
||||
export function showUnstashDialog(index = 0, repo = currentRepo()) {
|
||||
openDialog((close) => <UnstashDialog initial={index} repo={repo} onClose={close} />);
|
||||
}
|
||||
|
||||
function UnstashDialog({ initial, repo, onClose }: { initial: number; repo: string | null; onClose: () => void }) {
|
||||
const [stashes, setStashes] = useState<Stash[]>([]);
|
||||
const [tick, setTick] = useState(0);
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
void call(commands.vcsStashes(repo))
|
||||
@@ -430,13 +444,24 @@ function UnstashDialog({ initial, repo, onClose }: { initial: number; repo: stri
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [repo]);
|
||||
}, [repo, tick]);
|
||||
const [index, setIndex] = useState(initial);
|
||||
const [pop, setPop] = useState(false);
|
||||
const [reinstateIndex, setReinstateIndex] = useState(false);
|
||||
const [branch, setBranch] = useState("");
|
||||
const asBranch = branch.trim();
|
||||
const chosen = stashes.find((s) => s.index === index) ?? stashes[0];
|
||||
const view = () => {
|
||||
if (!chosen) return;
|
||||
const ref = `stash@{${chosen.index}}`;
|
||||
showCompareRevisions(`${ref}^`, ref, `${ref}^`, ref, repo);
|
||||
};
|
||||
const drop = async () => {
|
||||
if (!chosen || !(await dropStash(chosen.index, chosen.message, repo))) return;
|
||||
// The older stashes move up: the next one takes the dropped one's index, else the new last one.
|
||||
setIndex(Math.max(0, Math.min(chosen.index, stashes.length - 2)));
|
||||
setTick((n) => n + 1);
|
||||
};
|
||||
const submit = () => {
|
||||
if (!chosen) return;
|
||||
onClose();
|
||||
@@ -465,6 +490,10 @@ function UnstashDialog({ initial, repo, onClose }: { initial: number; repo: stri
|
||||
submit();
|
||||
}}
|
||||
>
|
||||
<div className={styles.manageBar} role="toolbar" aria-label={tx("Stashes")}>
|
||||
<IconButton icon="diff" title="Show Changes" size="small" disabled={!chosen} onClick={view} />
|
||||
<IconButton icon="trash" title="Drop Stash" size="small" disabled={!chosen} onClick={() => void drop()} />
|
||||
</div>
|
||||
<div className={styles.choiceList} role="radiogroup" aria-label={tx("Stashes")}>
|
||||
{stashes.length === 0 && (
|
||||
<div className={styles.hint}>
|
||||
@@ -496,7 +525,8 @@ function UnstashDialog({ initial, repo, onClose }: { initial: number; repo: stri
|
||||
);
|
||||
}
|
||||
|
||||
export async function dropStash(index: number, message: string, repo = currentRepo()) {
|
||||
/** Drops the stash once confirmed; whether it was confirmed. */
|
||||
export async function dropStash(index: number, message: string, repo = currentRepo()): Promise<boolean> {
|
||||
const ok = await confirmDialog({
|
||||
title: "Drop Stash",
|
||||
message: message
|
||||
@@ -505,9 +535,10 @@ export async function dropStash(index: number, message: string, repo = currentRe
|
||||
okLabel: "Drop",
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
if (!ok) return false;
|
||||
await runOp(tx`Drop ${`stash@{${index}}`}`, () => call(commands.vcsStashDrop(repo, index)), {
|
||||
success: tx`Dropped ${`stash@{${index}}`}`,
|
||||
});
|
||||
void loadStashes().catch((e) => logConsole("err", String(e)));
|
||||
return true;
|
||||
}
|
||||
@@ -122,6 +122,8 @@ function fileNode(fs: FileStatus, root: string, group: GroupId, flat: boolean, s
|
||||
interface Trie {
|
||||
dirs: Map<string, Trie>;
|
||||
files: FileStatus[];
|
||||
/** Absolute path of the directory. */
|
||||
path?: string;
|
||||
}
|
||||
|
||||
function dirNodes(trie: Trie, prefix: string, root: string, group: GroupId, scope: string = group): ChangeNode[] {
|
||||
@@ -147,7 +149,7 @@ function dirNodes(trie: Trie, prefix: string, root: string, group: GroupId, scop
|
||||
group,
|
||||
children,
|
||||
files,
|
||||
path: `${root}/${rel}`,
|
||||
path: node.path!,
|
||||
});
|
||||
}
|
||||
const files = [...trie.files].sort((a, b) => baseName(a.path).localeCompare(baseName(b.path)));
|
||||
@@ -165,13 +167,18 @@ function childNodes(files: readonly FileStatus[], root: string, group: GroupId,
|
||||
if (groupByDir) {
|
||||
const trie: Trie = { dirs: new Map(), files: [] };
|
||||
for (const f of files) {
|
||||
const rel = relTo(root, stripSlash(f.path));
|
||||
const path = stripSlash(f.path);
|
||||
const rel = relTo(root, path);
|
||||
const parts = rel.split("/");
|
||||
parts.pop();
|
||||
// Outside the root (a repository elsewhere, not grouped by repository): from its absolute path.
|
||||
if (rel === path && parts[0] === "" && parts.length > 1) parts.splice(0, 2, `/${parts[1]}`);
|
||||
let t = trie;
|
||||
let at = rel === path ? "" : `${root}/`;
|
||||
for (const p of parts) {
|
||||
at += t === trie ? p : `/${p}`;
|
||||
let next = t.dirs.get(p);
|
||||
if (!next) t.dirs.set(p, (next = { dirs: new Map(), files: [] }));
|
||||
if (!next) t.dirs.set(p, (next = { dirs: new Map(), files: [], path: at }));
|
||||
t = next;
|
||||
}
|
||||
t.files.push(f);
|
||||
@@ -236,8 +243,8 @@ function tagList(nodes: ChangeNode[], id: string): ChangeNode[] {
|
||||
* children. With change lists, "Changes" is split into one group per list
|
||||
* (`ChangelistState.files` keys are project-relative paths). With several
|
||||
* repositories (`repos`), each group's files are grouped by repository first, with
|
||||
* each repository's branch (`heads`) beside its name. With `byStaging`, "Changes"
|
||||
* becomes "Staged Changes" and "Unstaged Changes" instead.
|
||||
* each repository's branch (`heads`) beside its name, unless `byRepo` is off. With
|
||||
* `byStaging`, "Changes" becomes "Staged Changes" and "Unstaged Changes" instead.
|
||||
*/
|
||||
export function buildChangeTree(
|
||||
status: readonly FileStatus[],
|
||||
@@ -247,7 +254,9 @@ export function buildChangeTree(
|
||||
repos: readonly string[] = [],
|
||||
byStaging = false,
|
||||
heads: Readonly<Record<string, RepoHead>> = {},
|
||||
byRepo = true,
|
||||
): ChangeNode[] {
|
||||
const repoRoots = byRepo ? repos : [];
|
||||
const byGroup = new Map<GroupId, FileStatus[]>();
|
||||
for (const fs of status) {
|
||||
const g = groupOf(fs);
|
||||
@@ -267,7 +276,7 @@ export function buildChangeTree(
|
||||
];
|
||||
for (const [side, own] of sides) {
|
||||
if (!own.length) continue;
|
||||
const children = repoNodes(own, root, side, groupByDir, side, repos, heads);
|
||||
const children = repoNodes(own, root, side, groupByDir, side, repoRoots, heads);
|
||||
roots.push({
|
||||
key: `group:${side}`,
|
||||
type: "group",
|
||||
@@ -295,7 +304,7 @@ export function buildChangeTree(
|
||||
type: "group",
|
||||
label: l.name,
|
||||
group: g,
|
||||
children: tagList(repoNodes(own, root, g, groupByDir, scope, repos, heads), l.id),
|
||||
children: tagList(repoNodes(own, root, g, groupByDir, scope, repoRoots, heads), l.id),
|
||||
files: own,
|
||||
changelist: l.id,
|
||||
active: l.id === lists.active,
|
||||
@@ -305,7 +314,7 @@ export function buildChangeTree(
|
||||
continue;
|
||||
}
|
||||
if (!files.length) continue;
|
||||
const children = repoNodes(files, root, g, groupByDir, g, repos, heads);
|
||||
const children = repoNodes(files, root, g, groupByDir, g, repoRoots, heads);
|
||||
roots.push({ key: `group:${g}`, type: "group", label: GROUP_LABEL[g], group: g, children, files });
|
||||
}
|
||||
return roots;
|
||||
|
||||
@@ -17,6 +17,8 @@ interface CommitState {
|
||||
groupByDir: boolean;
|
||||
/** Group the changes into Staged / Unstaged instead of one "Changes" group. */
|
||||
groupByStaging: boolean;
|
||||
/** With several repositories, a node per repository above their files. */
|
||||
groupByRepo: boolean;
|
||||
/** Whether the Git window's Local Changes tab previews the selection's diff. */
|
||||
diffPreview: boolean;
|
||||
/** Whether the Commit tool window previews the selection's diff beside the changes (#1599). */
|
||||
@@ -54,6 +56,7 @@ export const useCommit = create<CommitState>(() => ({
|
||||
runHooks: true,
|
||||
groupByDir: readBool("openidea.vcs.groupByDir", false),
|
||||
groupByStaging: readBool("openidea.vcs.groupByStaging", false),
|
||||
groupByRepo: readBool("openidea.vcs.groupByRepo", true),
|
||||
diffPreview: readBool("openidea.vcs.diffPreview", true),
|
||||
commitDiffPreview: readBool("openidea.vcs.commitDiffPreview", false),
|
||||
checks: new Map(),
|
||||
@@ -104,6 +107,15 @@ export function setGroupByStaging(v: boolean) {
|
||||
}
|
||||
}
|
||||
|
||||
export function setGroupByRepo(v: boolean) {
|
||||
useCommit.setState({ groupByRepo: v });
|
||||
try {
|
||||
localStorage.setItem("openidea.vcs.groupByRepo", String(v));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export function setDiffPreview(v: boolean) {
|
||||
useCommit.setState({ diffPreview: v });
|
||||
try {
|
||||
|
||||
@@ -135,7 +135,7 @@ export function showPullDialog(repo?: string | null) {
|
||||
}
|
||||
|
||||
/** IDEA's Git Root choice: shown only when the project holds several repositories. */
|
||||
function RepoPicker({ repo, onChange }: { repo: string | null; onChange: (root: string) => void }) {
|
||||
export function RepoPicker({ repo, onChange }: { repo: string | null; onChange: (root: string) => void }) {
|
||||
const [roots] = useState(() => useVcs.getState().roots);
|
||||
if (roots.length < 2) return null;
|
||||
return (
|
||||
@@ -149,7 +149,7 @@ function RepoPicker({ repo, onChange }: { repo: string | null; onChange: (root:
|
||||
}
|
||||
|
||||
/** The repository's branch info: the store's for the selected repository, else read from git. */
|
||||
function useBranchInfo(repo: string | null) {
|
||||
export function useBranchInfo(repo: string | null) {
|
||||
const [initial] = useState(() => ({ repo: currentRepo(), info: useVcs.getState().branch }));
|
||||
const [loaded, setLoaded] = useState<{ repo: string | null; info: BranchInfo | null } | null>(null);
|
||||
useEffect(() => {
|
||||
|
||||
@@ -27,6 +27,7 @@ import { buildFileTree, type FileTreeNode } from "./fileTree";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { displayPath } from "./compareData";
|
||||
import { repositoryPath } from "./repositoryPaths";
|
||||
import { RepoPicker } from "./gitMenuDialogs";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Operation in progress
|
||||
@@ -437,15 +438,27 @@ export function showTagDialog() {
|
||||
}
|
||||
|
||||
function TagDialog({ onClose }: { onClose: () => void }) {
|
||||
const [repo] = useState(currentRepo);
|
||||
const [repo, setRepo] = useState(currentRepo);
|
||||
const [name, setName] = useState("");
|
||||
const [commit, setCommit] = useState("HEAD");
|
||||
const [message, setMessage] = useState("");
|
||||
const [force, setForce] = useState(false);
|
||||
const [existing, setExisting] = useState<string[]>([]);
|
||||
useEffect(() => {
|
||||
void call(commands.vcsTags(repo)).then(setExisting, () => undefined);
|
||||
}, []);
|
||||
let live = true;
|
||||
void call(commands.vcsTags(repo)).then(
|
||||
(tags) => live && setExisting(tags),
|
||||
() => undefined,
|
||||
);
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [repo]);
|
||||
const chooseRepo = (root: string) => {
|
||||
if (root === repo) return;
|
||||
setRepo(root);
|
||||
setExisting([]);
|
||||
};
|
||||
const error = validateTagName(name, force ? [] : existing);
|
||||
const run = async () => {
|
||||
if (error) return;
|
||||
@@ -470,6 +483,7 @@ function TagDialog({ onClose }: { onClose: () => void }) {
|
||||
]}
|
||||
>
|
||||
<div className={styles.form}>
|
||||
<RepoPicker repo={repo} onChange={chooseRepo} />
|
||||
<label className={styles.fieldLabel} htmlFor="openidea-tag-name">
|
||||
<T>Tag name:</T>
|
||||
</label>
|
||||
@@ -518,21 +532,21 @@ export function showCompareVersions(older: Commit, newer: Commit) {
|
||||
showComparison({ rev: older.id, label: short(older.id) }, { rev: newer.id, label: short(newer.id) });
|
||||
}
|
||||
|
||||
/** Files that differ between two revisions (e.g. two branches from Compare with Current). */
|
||||
export function showCompareRevisions(from: string, to: string, fromLabel = from, toLabel = to) {
|
||||
showComparison({ rev: from, label: fromLabel }, { rev: to, label: toLabel });
|
||||
/** Files that differ between two revisions (e.g. two branches from Compare with Current) of `repo`. */
|
||||
export function showCompareRevisions(from: string, to: string, fromLabel = from, toLabel = to, repo = currentRepo()) {
|
||||
showComparison({ rev: from, label: fromLabel }, { rev: to, label: toLabel }, undefined, repo);
|
||||
}
|
||||
|
||||
export function showPathComparison(paths: string[], rev: string, repositories: string[] | null) {
|
||||
showComparison({ rev, label: rev }, null, { paths, repositories });
|
||||
}
|
||||
|
||||
function showComparison(from: Revision, to: Revision | null, scope?: ScopedComparison) {
|
||||
function showComparison(from: Revision, to: Revision | null, scope?: ScopedComparison, repo = currentRepo()) {
|
||||
if (!isTauri()) {
|
||||
openDialog((close) => <ChangesBetweenDialog from={from} to={to} scope={scope} onClose={close} />);
|
||||
openDialog((close) => <ChangesBetweenDialog from={from} to={to} scope={scope} repo={repo} onClose={close} />);
|
||||
return;
|
||||
}
|
||||
const comparison = { from, to, scope: scope ?? null, repo: currentRepo() };
|
||||
const comparison = { from, to, scope: scope ?? null, repo };
|
||||
void call(commands.windowOpenComparison(comparison, windowBackgroundHex())).catch((error) =>
|
||||
notifications().notify({ level: "error", title: "Could not open comparison", body: String(error) }),
|
||||
);
|
||||
@@ -596,6 +610,7 @@ export function ChangesBetweenDialog({
|
||||
from,
|
||||
to,
|
||||
scope,
|
||||
repo: givenRepo,
|
||||
onClose,
|
||||
native = false,
|
||||
onCaption,
|
||||
@@ -607,6 +622,8 @@ export function ChangesBetweenDialog({
|
||||
from: Revision;
|
||||
to: Revision | null;
|
||||
scope?: ScopedComparison;
|
||||
/** The repository compared (the selected one when omitted). */
|
||||
repo?: string | null;
|
||||
onClose: () => void;
|
||||
/** Content of the comparison window rather than a dialog: its caption goes to `onCaption`. */
|
||||
native?: boolean;
|
||||
@@ -619,8 +636,8 @@ export function ChangesBetweenDialog({
|
||||
/** Files only, each diff opening in the editor (the Compare tool window's narrow sidebar). */
|
||||
listOnly?: boolean;
|
||||
}) {
|
||||
const [root] = useState(currentRepoRoot);
|
||||
const [repo] = useState(currentRepo);
|
||||
const [repo] = useState(() => (givenRepo === undefined ? currentRepo() : givenRepo));
|
||||
const [root] = useState(() => repo ?? currentRepoRoot());
|
||||
const [files, setFiles] = useState<ComparisonFile[] | null>(null);
|
||||
const [result, setResult] = useState<CompareResult | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -130,7 +130,11 @@
|
||||
margin: 1.5em 0;
|
||||
}
|
||||
.preview :global(img) {
|
||||
max-width: 100%;
|
||||
max-width: calc(100% * var(--markdown-zoom-scale, 1));
|
||||
}
|
||||
.preview :global(img[data-natural-width]) {
|
||||
width: calc(min(var(--image-width), 100%) * var(--markdown-zoom-scale, 1));
|
||||
height: auto;
|
||||
}
|
||||
.preview :global(ul.contains-task-list) {
|
||||
list-style: none;
|
||||
@@ -155,10 +159,18 @@
|
||||
display: none;
|
||||
}
|
||||
.preview :global(.mermaid-output) {
|
||||
overflow: hidden;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
text-align: center;
|
||||
}
|
||||
.preview :global(.mermaid-output svg[data-natural-width]) {
|
||||
display: block;
|
||||
margin: 0 auto;
|
||||
width: calc(min(var(--diagram-width), 100%) * var(--markdown-zoom-scale, 1));
|
||||
height: auto;
|
||||
}
|
||||
.preview :global(.mermaid-output[data-zoomed="true"]) {
|
||||
overflow: hidden;
|
||||
cursor: grab;
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
|
||||
@@ -51,6 +51,7 @@ import {
|
||||
resolveLink,
|
||||
slugify,
|
||||
} from "./render";
|
||||
import { applyImageZoomWidth, svgDataUrlSize } from "./svgSize";
|
||||
import styles from "./Markdown.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -110,6 +111,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
const text = useLiveMarkdown((s) => s[path]?.text);
|
||||
const fontZoom = useLiveMarkdown((s) => s[path]?.fontZoom ?? 0);
|
||||
const fontSize = useMarkdownPreviewFontSize();
|
||||
const zoomScale = Number((Math.max(4, fontSize + fontZoom) / fontSize).toFixed(4));
|
||||
const topLine = useLiveMarkdown((s) => s[path]?.topLine ?? 0);
|
||||
const scrollSeq = useLiveMarkdown((s) => s[path]?.scrollSeq ?? 0);
|
||||
const caretLine = useLiveMarkdown((s) => s[path]?.caretLine ?? 0);
|
||||
@@ -161,10 +163,32 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
const root = ref.current;
|
||||
if (!root) return;
|
||||
let live = true;
|
||||
root.querySelectorAll<HTMLImageElement>("img[data-src]").forEach((img) => {
|
||||
const bindImageUrl = (img: HTMLImageElement, url: string, asyncLoad: boolean) => {
|
||||
const svgSize = svgDataUrlSize(url);
|
||||
if (svgSize && applyImageZoomWidth(img, svgSize) && asyncLoad) {
|
||||
setDiagramsDrawn((n) => n + 1);
|
||||
}
|
||||
img.onload = () => {
|
||||
if (!live) return;
|
||||
if (!img.hasAttribute("data-natural-width") && img.naturalWidth > 0 && img.naturalHeight > 0) {
|
||||
if (applyImageZoomWidth(img, { w: img.naturalWidth, h: img.naturalHeight })) {
|
||||
setDiagramsDrawn((n) => n + 1);
|
||||
}
|
||||
} else if (asyncLoad) {
|
||||
setDiagramsDrawn((n) => n + 1);
|
||||
}
|
||||
};
|
||||
img.src = url;
|
||||
if (!img.hasAttribute("data-natural-width") && img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
|
||||
applyImageZoomWidth(img, { w: img.naturalWidth, h: img.naturalHeight });
|
||||
}
|
||||
};
|
||||
const imgs = [...root.querySelectorAll<HTMLImageElement>("img[data-src]")];
|
||||
imgs.forEach((img) => {
|
||||
applyImageZoomWidth(img);
|
||||
const src = img.dataset.src ?? "";
|
||||
if (/^data:image\//i.test(src)) {
|
||||
img.src = src;
|
||||
bindImageUrl(img, src, false);
|
||||
return;
|
||||
}
|
||||
const target = resolveLink(path, src);
|
||||
@@ -174,7 +198,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
return;
|
||||
}
|
||||
imageUrl(target.path).then(
|
||||
(url) => live && (img.src = url),
|
||||
(url) => live && bindImageUrl(img, url, true),
|
||||
() => live && img.classList.add(styles.blocked!),
|
||||
);
|
||||
});
|
||||
@@ -187,6 +211,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
});
|
||||
return () => {
|
||||
live = false;
|
||||
for (const img of imgs) img.onload = null;
|
||||
};
|
||||
}, [html, path]);
|
||||
|
||||
@@ -195,7 +220,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
const root = ref.current;
|
||||
if (!root || !sync) return;
|
||||
root.scrollTop = topLine <= 0 ? 0 : previewOffsetForLine(blocksOf(root), topLine, root.scrollHeight);
|
||||
}, [html, topLine, scrollSeq, sync, diagramsDrawn]);
|
||||
}, [html, topLine, scrollSeq, sync, diagramsDrawn, fontZoom, fontSize]);
|
||||
|
||||
// The preview's own scroll offset: tab switches and mode toggles unmount the
|
||||
// preview, so Preview Only would otherwise start over at the top. Writes made
|
||||
@@ -376,6 +401,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
{
|
||||
"--markdown-preview-font-size": `${fontSize}px`,
|
||||
"--markdown-font-zoom": `${fontZoom}px`,
|
||||
"--markdown-zoom-scale": String(zoomScale),
|
||||
} as CSSProperties
|
||||
}
|
||||
tabIndex={-1}
|
||||
|
||||
@@ -396,6 +396,15 @@ describe("mermaid in the markdown preview", () => {
|
||||
expect(root.querySelector("[data-mermaid]")?.getAttribute("data-mermaid-state")).toBe("pending");
|
||||
});
|
||||
|
||||
it("records a diagram's natural width so preview font zoom scales it without clamping", async () => {
|
||||
const svg = await renderedSvg(
|
||||
'<svg id="openidea-mermaid-1" width="100%" style="max-width: 540px;" viewBox="0 0 540 320"><text>flow</text></svg>',
|
||||
);
|
||||
expect(svg.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(svg.style.getPropertyValue("--diagram-width")).toBe("540px");
|
||||
expect(svg.style.maxWidth).toBe("calc(min(var(--diagram-width), 100%) * var(--markdown-zoom-scale, 1))");
|
||||
});
|
||||
|
||||
it("puts full-screen and download tools on a drawn diagram", async () => {
|
||||
const root = preview(SEQ);
|
||||
await renderMermaidIn(root).done;
|
||||
|
||||
@@ -11,6 +11,7 @@ import { attachPanZoom } from "../panZoom";
|
||||
import { attachDiagramTools, TOOLS_ATTR } from "./mermaidTools";
|
||||
import { localSvg } from "./localSvg";
|
||||
import { reid } from "./svgIds";
|
||||
import { svgElementSize } from "./svgSize";
|
||||
|
||||
export const MERMAID_SELECTOR = "[data-mermaid]";
|
||||
const OUTPUT_CLASS = "mermaid-output";
|
||||
@@ -250,7 +251,15 @@ function show(block: HTMLElement, result: Result | null, stale?: Node) {
|
||||
if (block.getAttribute(RENDERED_ATTR) === "ok") {
|
||||
attachPanZoom(out);
|
||||
const svg = out.querySelector("svg");
|
||||
if (svg) attachDiagramTools(block, svg);
|
||||
if (svg) {
|
||||
const size = svgElementSize(svg);
|
||||
if (size) {
|
||||
svg.dataset.naturalWidth = "";
|
||||
svg.style.setProperty("--diagram-width", `${Number(size.w.toFixed(2))}px`);
|
||||
svg.style.maxWidth = "calc(min(var(--diagram-width), 100%) * var(--markdown-zoom-scale, 1))";
|
||||
}
|
||||
attachDiagramTools(block, svg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import { openLayer, trapTab } from "@/ui/popupState";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { attachPanZoom } from "../panZoom";
|
||||
import { reid } from "./svgIds";
|
||||
import { svgElementSize } from "./svgSize";
|
||||
import styles from "./MermaidTools.module.css";
|
||||
|
||||
/** Marks the tool strip, so a redrawing block replaces it rather than stacking one. */
|
||||
@@ -161,11 +162,8 @@ function fittedCopy(svg: SVGSVGElement, availW: number, availH: number): SVGSVGE
|
||||
}
|
||||
|
||||
function naturalSize(svg: SVGSVGElement): { w: number; h: number } {
|
||||
const box = (svg as SVGSVGElement & { viewBox?: SVGAnimatedRect }).viewBox?.baseVal;
|
||||
if (box && box.width > 0 && box.height > 0) return { w: box.width, h: box.height };
|
||||
const width = Number(svg.getAttribute("width"));
|
||||
const height = Number(svg.getAttribute("height"));
|
||||
if (width > 0 && height > 0) return { w: width, h: height };
|
||||
const declared = svgElementSize(svg);
|
||||
if (declared) return declared;
|
||||
const rect = svg.getBoundingClientRect();
|
||||
return { w: rect.width > 0 ? rect.width : 800, h: rect.height > 0 ? rect.height : 600 };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Intrinsic CSS pixel dimensions of SVGs and Markdown preview images, so
|
||||
* diagrams and embedded `.svg` / raster assets scale with `--markdown-zoom-scale`.
|
||||
*/
|
||||
|
||||
const UNIT_PX: Record<string, number> = {
|
||||
"": 1,
|
||||
px: 1,
|
||||
pt: 96 / 72,
|
||||
pc: 16,
|
||||
in: 96,
|
||||
cm: 96 / 2.54,
|
||||
mm: 96 / 25.4,
|
||||
};
|
||||
|
||||
/** Parses an absolute SVG/HTML length into CSS pixels (ignoring `%`, `em`, etc.). */
|
||||
export function parseLengthPx(raw: string | null | undefined): number | null {
|
||||
if (!raw) return null;
|
||||
const m = /^\s*(\d+(?:\.\d+)?|\.\d+)\s*([a-z%]*)\s*$/i.exec(raw);
|
||||
if (!m) return null;
|
||||
const factor = UNIT_PX[m[2]!.toLowerCase()];
|
||||
if (!factor) return null;
|
||||
const n = Number(m[1]) * factor;
|
||||
return Number.isFinite(n) && n > 0 ? n : null;
|
||||
}
|
||||
|
||||
function parsePercent(raw: string | null | undefined): number | null {
|
||||
if (!raw) return null;
|
||||
const m = /^\s*(\d+(?:\.\d+)?|\.\d+)%\s*$/.exec(raw);
|
||||
if (!m) return null;
|
||||
const n = Number(m[1]);
|
||||
return Number.isFinite(n) && n > 0 ? n : null;
|
||||
}
|
||||
|
||||
/** Parses `viewBox="minX minY width height"` into `{ w, h }`. */
|
||||
export function parseViewBoxSize(raw: string | null | undefined): { w: number; h: number } | null {
|
||||
if (!raw) return null;
|
||||
const parts = raw
|
||||
.trim()
|
||||
.split(/[\s,]+/)
|
||||
.map(Number);
|
||||
if (parts.length !== 4) return null;
|
||||
const w = parts[2]!;
|
||||
const h = parts[3]!;
|
||||
return Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0 ? { w, h } : null;
|
||||
}
|
||||
|
||||
function resolveSvgDims(
|
||||
style: string | null | undefined,
|
||||
widthAttr: string | null | undefined,
|
||||
heightAttr: string | null | undefined,
|
||||
viewBoxAttr: string | null | undefined,
|
||||
): { w: number; h: number } | null {
|
||||
const vb = parseViewBoxSize(viewBoxAttr);
|
||||
const storedW = parseLengthPx(/(?:^|;)\s*--diagram-width\s*:\s*([^;]+)/i.exec(style ?? "")?.[1]);
|
||||
const inlineMaxW = parseLengthPx(/(?:^|;)\s*max-width\s*:\s*([^;]+)/i.exec(style ?? "")?.[1]);
|
||||
const attrW = parseLengthPx(widthAttr);
|
||||
const attrH = parseLengthPx(heightAttr);
|
||||
|
||||
const w = storedW ?? inlineMaxW ?? attrW ?? (attrH && vb ? (attrH * vb.w) / vb.h : (vb?.w ?? null));
|
||||
if (!w) return null;
|
||||
const h = attrH ?? (vb ? (w * vb.h) / vb.w : w * 0.75);
|
||||
return { w, h };
|
||||
}
|
||||
|
||||
/** Intrinsic CSS pixel size of an in-DOM `<svg>`, when declared on the element. */
|
||||
export function svgElementSize(svg: SVGSVGElement): { w: number; h: number } | null {
|
||||
const fromAttrs = resolveSvgDims(
|
||||
svg.getAttribute("style"),
|
||||
svg.getAttribute("width"),
|
||||
svg.getAttribute("height"),
|
||||
svg.getAttribute("viewBox"),
|
||||
);
|
||||
if (fromAttrs) return fromAttrs;
|
||||
const box = (svg as SVGSVGElement & { viewBox?: SVGAnimatedRect }).viewBox?.baseVal;
|
||||
if (box && box.width > 0 && box.height > 0) return { w: box.width, h: box.height };
|
||||
return null;
|
||||
}
|
||||
|
||||
function readAttr(tag: string, name: string): string | null {
|
||||
const re = new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i");
|
||||
const m = re.exec(tag);
|
||||
return m ? (m[1] ?? m[2] ?? m[3] ?? null) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Intrinsic CSS pixel size of a `data:image/svg+xml` URL from its `<svg>` header.
|
||||
* Decodes only the leading chunk so large `.excalidraw.svg` scenes stay cheap.
|
||||
*/
|
||||
export function svgDataUrlSize(url: string): { w: number; h: number } | null {
|
||||
const comma = url.indexOf(",");
|
||||
if (comma < 0) return null;
|
||||
const header = url.slice(0, comma);
|
||||
if (!/^data:image\/svg\+xml\b/i.test(header)) return null;
|
||||
const payload = url.slice(comma + 1, comma + 1 + 16384);
|
||||
let head: string;
|
||||
try {
|
||||
if (/;base64\b/i.test(header)) {
|
||||
const clean = payload.replace(/\s+/g, "");
|
||||
const aligned = clean.slice(0, clean.length - (clean.length % 4));
|
||||
head = atob(aligned);
|
||||
} else {
|
||||
const safe = payload.replace(/%[0-9a-f]?$/i, "");
|
||||
head = decodeURIComponent(safe);
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const withoutComments = head.replace(/<!--[\s\S]*?-->/g, "");
|
||||
const open = /<svg\b((?:"[^"]*"|'[^']*'|[^'">])*)>/i.exec(withoutComments);
|
||||
if (!open) return null;
|
||||
const attrs = open[1]!;
|
||||
return resolveSvgDims(
|
||||
readAttr(attrs, "style"),
|
||||
readAttr(attrs, "width"),
|
||||
readAttr(attrs, "height"),
|
||||
readAttr(attrs, "viewBox"),
|
||||
);
|
||||
}
|
||||
|
||||
const formatPx = (n: number) => `${Number(n.toFixed(2))}px`;
|
||||
|
||||
/**
|
||||
* Sets an `<img>`'s 1× base width so CSS scales it by `--markdown-zoom-scale`,
|
||||
* respecting explicit HTML `width` / `height` attributes when present.
|
||||
*/
|
||||
export function applyImageZoomWidth(img: HTMLImageElement, intrinsic?: { w: number; h: number } | null): boolean {
|
||||
const rawWidth = img.getAttribute("width");
|
||||
const pct = parsePercent(rawWidth);
|
||||
if (pct !== null) {
|
||||
img.style.width = `calc(${pct}% * var(--markdown-zoom-scale, 1))`;
|
||||
img.style.height = "auto";
|
||||
return true;
|
||||
}
|
||||
const attrW = parseLengthPx(rawWidth);
|
||||
if (attrW !== null) {
|
||||
img.style.setProperty("--image-width", formatPx(attrW));
|
||||
img.dataset.naturalWidth = "";
|
||||
return true;
|
||||
}
|
||||
if (!intrinsic || intrinsic.w <= 0 || intrinsic.h <= 0) return false;
|
||||
const attrH = parseLengthPx(img.getAttribute("height"));
|
||||
const baseW = attrH !== null ? (attrH * intrinsic.w) / intrinsic.h : intrinsic.w;
|
||||
img.style.setProperty("--image-width", formatPx(baseW));
|
||||
img.dataset.naturalWidth = "";
|
||||
return true;
|
||||
}
|
||||
@@ -101,14 +101,102 @@ describe("editor font size actions", () => {
|
||||
);
|
||||
const preview = screen.getByRole("document", { name: "Markdown preview" });
|
||||
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("0px");
|
||||
expect(preview.style.getPropertyValue("--markdown-zoom-scale")).toBe("1");
|
||||
|
||||
await act(() => executeAction("editor.increaseFontSize"));
|
||||
await act(() => executeAction("editor.increaseFontSize"));
|
||||
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("2px");
|
||||
expect(preview.style.getPropertyValue("--markdown-zoom-scale")).toBe("1.1538");
|
||||
|
||||
await act(() => executeAction("editor.decreaseFontSize"));
|
||||
await act(() => executeAction("editor.decreaseFontSize"));
|
||||
await act(() => executeAction("editor.decreaseFontSize"));
|
||||
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("-1px");
|
||||
expect(preview.style.getPropertyValue("--markdown-zoom-scale")).toBe("0.9231");
|
||||
|
||||
await act(() => executeAction("editor.resetFontSize"));
|
||||
expect(zoom(md)).toBe(0);
|
||||
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("0px");
|
||||
expect(preview.style.getPropertyValue("--markdown-zoom-scale")).toBe("1");
|
||||
});
|
||||
|
||||
it("sizes embedded excalidraw.svg, graph SVGs and raster images so they scale with font zoom", async () => {
|
||||
const excalidrawSvg =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 940" width="1280" height="940"><!-- svg-source:excalidraw --></svg>';
|
||||
const excalidrawUrl = `data:image/svg+xml;base64,${btoa(excalidrawSvg)}`;
|
||||
const graphvizUrl = `data:image/svg+xml;utf8,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="300pt" height="150pt" viewBox="0 0 300 150"></svg>')}`;
|
||||
const wordmarkUrl = `data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 280 56"></svg>')}`;
|
||||
const pngUrl = "data:image/png;base64,iVBORw0KGgo=";
|
||||
|
||||
const ipc = await import("@/platform/ipc");
|
||||
const fsReadImage = vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (p: string) => {
|
||||
if (p.endsWith("architecture.excalidraw.svg")) return { status: "ok", data: excalidrawUrl };
|
||||
if (p.endsWith("wordmark.svg")) return { status: "ok", data: wordmarkUrl };
|
||||
if (p.endsWith("shot.png")) return { status: "ok", data: pngUrl };
|
||||
return { status: "error", error: { kind: "notFound", message: p } } as never;
|
||||
});
|
||||
|
||||
try {
|
||||
const doc = [
|
||||
"",
|
||||
"",
|
||||
``,
|
||||
"",
|
||||
'<img src="./wordmark.svg" alt="Wordmark" height="56">',
|
||||
"",
|
||||
'<img src="./wordmark.svg" alt="Icon" width="80">',
|
||||
"",
|
||||
"",
|
||||
].join("\n");
|
||||
const live = editorContributions().find((c) => c.id === "viewers.markdownLive")!;
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc, extensions: [fontZoom, live.extensions(mdCtx)] }),
|
||||
});
|
||||
const handle = { view, ctx: mdCtx };
|
||||
_addEditor(handle);
|
||||
disposers.push(() => _removeEditor(handle));
|
||||
views.push(view);
|
||||
activate(view);
|
||||
|
||||
act(() => useMarkdownModes.setState((s) => ({ byPath: { ...s.byPath, [mdCtx.path]: "preview" } })));
|
||||
render(
|
||||
<MarkdownEditor path={mdCtx.path} tabId="t">
|
||||
<div />
|
||||
</MarkdownEditor>,
|
||||
);
|
||||
const preview = screen.getByRole("document", { name: "Markdown preview" });
|
||||
await vi.waitFor(() => {
|
||||
const arch = preview.querySelector<HTMLImageElement>('img[alt="Architecture"]');
|
||||
expect(arch?.getAttribute("src")).toBe(excalidrawUrl);
|
||||
});
|
||||
|
||||
const arch = preview.querySelector<HTMLImageElement>('img[alt="Architecture"]')!;
|
||||
expect(arch.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(arch.style.getPropertyValue("--image-width")).toBe("1280px");
|
||||
|
||||
const graph = preview.querySelector<HTMLImageElement>('img[alt="Graph"]')!;
|
||||
expect(graph.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(graph.style.getPropertyValue("--image-width")).toBe("400px");
|
||||
|
||||
const wordmark = preview.querySelector<HTMLImageElement>('img[alt="Wordmark"]')!;
|
||||
expect(wordmark.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(wordmark.style.getPropertyValue("--image-width")).toBe("280px");
|
||||
|
||||
const icon = preview.querySelector<HTMLImageElement>('img[alt="Icon"]')!;
|
||||
expect(icon.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(icon.style.getPropertyValue("--image-width")).toBe("80px");
|
||||
|
||||
const shot = preview.querySelector<HTMLImageElement>('img[alt="Shot"]')!;
|
||||
Object.defineProperty(shot, "naturalWidth", { value: 960, configurable: true });
|
||||
Object.defineProperty(shot, "naturalHeight", { value: 600, configurable: true });
|
||||
act(() => {
|
||||
shot.dispatchEvent(new Event("load"));
|
||||
});
|
||||
expect(shot.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(shot.style.getPropertyValue("--image-width")).toBe("960px");
|
||||
} finally {
|
||||
fsReadImage.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("scales a configured editor font size", () => {
|
||||
|
||||
@@ -50,6 +50,11 @@ export function attachPanZoom(viewport: HTMLElement, options: PanZoomOptions = {
|
||||
(e) => {
|
||||
if (!(e.metaKey || e.ctrlKey) || !e.deltaY) return;
|
||||
e.preventDefault();
|
||||
if (view.z === origin.z && (viewport.scrollLeft || viewport.scrollTop)) {
|
||||
view = { ...view, x: view.x - viewport.scrollLeft, y: view.y - viewport.scrollTop };
|
||||
viewport.scrollLeft = 0;
|
||||
viewport.scrollTop = 0;
|
||||
}
|
||||
const rect = viewport.getBoundingClientRect();
|
||||
// One wheel notch (~100 px, 3 lines or a page) zooms about 15%; a trackpad
|
||||
// sends small pixel deltas, so zooming follows the gesture continuously.
|
||||
|
||||
@@ -94,6 +94,18 @@ export const CLIENT_SETTINGS_KEYS = [
|
||||
"vcs.commit.nonModal",
|
||||
"vcs.commit.doubleClickOpensDiff",
|
||||
"vcs.commit.showRightMargin",
|
||||
"agents.showContextUsage",
|
||||
"agents.showWorkTime",
|
||||
"agents.showUsageLimits",
|
||||
"agents.showCost",
|
||||
"agents.foldTurns",
|
||||
"agents.smoothText",
|
||||
"agents.fitWindowWidth",
|
||||
"agents.thinking",
|
||||
"agents.toolCalls",
|
||||
"agents.expandToolOutput",
|
||||
"agents.sendWith",
|
||||
"agents.whileRunning",
|
||||
] as const;
|
||||
|
||||
export function isClientSetting(key: string): boolean {
|
||||
|
||||
@@ -20,6 +20,7 @@ export const eclipseMacos: Record<string, string[]> = {
|
||||
"editor.closeAllTabs": ["Meta+Shift+W"],
|
||||
"analyze.inspectFile": [],
|
||||
"project.collapseAll": ["Meta+Shift+NumpadDivide"],
|
||||
"run.collapseAllTests": ["Meta+Shift+NumpadDivide"],
|
||||
"code.foldAll": ["Meta+Shift+NumpadDivide"],
|
||||
"code.fold": ["Meta+NumpadSubtract"],
|
||||
"code.commentBlock": ["Shift+Meta+/"],
|
||||
@@ -39,6 +40,7 @@ export const eclipseMacos: Record<string, string[]> = {
|
||||
"code.shrinkSelection": ["Shift+Ctrl+Down"],
|
||||
"debug.evaluate": ["Meta+U"],
|
||||
"project.expandAll": ["Meta+Shift+NumpadMultiply"],
|
||||
"run.expandAllTests": ["Meta+Shift+NumpadMultiply"],
|
||||
"code.unfoldAll": ["Meta+NumpadMultiply"],
|
||||
"code.unfold": ["Meta+NumpadAdd"],
|
||||
"code.expandAllToLevel1": [],
|
||||
|
||||
@@ -20,6 +20,7 @@ export const eclipseWindows: Record<string, string[]> = {
|
||||
"editor.closeAllTabs": ["Shift+Ctrl+F4", "Shift+Ctrl+W"],
|
||||
"analyze.inspectFile": [],
|
||||
"project.collapseAll": ["Ctrl+Shift+NumpadDivide"],
|
||||
"run.collapseAllTests": ["Ctrl+Shift+NumpadDivide"],
|
||||
"code.foldAll": ["Ctrl+Shift+NumpadDivide"],
|
||||
"code.fold": ["Ctrl+NumpadSubtract"],
|
||||
"code.commentBlock": ["Shift+Ctrl+/"],
|
||||
@@ -41,6 +42,7 @@ export const eclipseWindows: Record<string, string[]> = {
|
||||
"code.shrinkSelection": ["Shift+Alt+Down"],
|
||||
"debug.evaluate": ["Ctrl+U"],
|
||||
"project.expandAll": ["Ctrl+Shift+NumpadMultiply"],
|
||||
"run.expandAllTests": ["Ctrl+Shift+NumpadMultiply"],
|
||||
"code.unfoldAll": ["Ctrl+NumpadMultiply"],
|
||||
"code.unfold": ["Ctrl+NumpadAdd"],
|
||||
"code.expandAllToLevel1": [],
|
||||
|
||||
@@ -53,7 +53,8 @@ const shared = [
|
||||
["code.optimizeImports", "project.optimizeImports"],
|
||||
["code.deleteLine", "db.duplicateSource", "project.compareWith", "vcs.showDiff", "vcs.log.changes.showDiff"],
|
||||
["code.moveStatementDown", "find.field.recentSearches", "find.popup.recentSearches"],
|
||||
["code.foldAll", "project.collapseAll"],
|
||||
["code.foldAll", "project.collapseAll", "run.collapseAllTests"],
|
||||
["project.expandAll", "run.expandAllTests"],
|
||||
["refactor.rename", "project.rename", "db.rename", "vcs.changelist.edit", "vcs.log.editMessage", "vcs.shelf.rename"],
|
||||
["refactor.changeSignature", "db.modifyTable"],
|
||||
["refactor.move", "project.move"],
|
||||
|
||||
@@ -35,6 +35,8 @@ describe("IDEA keymap parity", () => {
|
||||
["project.reloadFromDisk", ["Meta+Alt+Y"], ["Ctrl+Alt+Y"]],
|
||||
["project.expandAll", ["Meta+="], ["Ctrl+="]],
|
||||
["project.collapseAll", ["Meta+-"], ["Ctrl+-"]],
|
||||
["run.expandAllTests", ["Meta+="], ["Ctrl+="]],
|
||||
["run.collapseAllTests", ["Meta+-"], ["Ctrl+-"]],
|
||||
["navigate.searchText", ["Meta+Alt+Shift+E"], ["Ctrl+Alt+Shift+E"]],
|
||||
["window.next", ["Meta+Alt+`"], ["Ctrl+Alt+]"]],
|
||||
["window.previous", ["Meta+Alt+Shift+`"], ["Ctrl+Alt+["]],
|
||||
@@ -101,6 +103,8 @@ describe("IDEA keymap parity", () => {
|
||||
order(km, "file.reloadFromDisk", "project.reloadFromDisk");
|
||||
order(km, "code.unfold", "project.expandAll");
|
||||
order(km, "code.fold", "project.collapseAll");
|
||||
order(km, "code.unfold", "run.expandAllTests");
|
||||
order(km, "code.fold", "run.collapseAllTests");
|
||||
order(km, "navigate.nextError", "vcs.changelist.edit");
|
||||
order(km, "debug.setValue", "vcs.changelist.edit");
|
||||
order(km, "find.replaceInFile", "find.rerun");
|
||||
|
||||
@@ -218,6 +218,9 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
"project.reloadFromDisk": ["Meta+Alt+Y"],
|
||||
"project.expandAll": ["Meta+="],
|
||||
"project.collapseAll": ["Meta+-"],
|
||||
// In the test results tree (keyWhen).
|
||||
"run.expandAllTests": ["Meta+="],
|
||||
"run.collapseAllTests": ["Meta+-"],
|
||||
|
||||
// Tool windows
|
||||
"toolwindow.project": ["Meta+1"],
|
||||
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача