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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 2aa46f21bf test(settings): include agentButton in the commit settings defaults shape 2026-11-20 13:29:14 +08:00
l0ng-ai 7310d0ab01 feat(vcs): setting to hide the Generate Commit Message with Agent button
Version Control › Commit › Commit Message Generation gets "Show the Generate Commit Message
with Agent button" (on by default). Off, the button above the commit message is hidden in
the Commit tool window and dialog; the action stays available from Find Action and its
shortcut.
2026-11-20 13:21:55 +08:00
l0ng-ai 2c6329012a fix(vcs): keep each repository's branch submenu expansion separate (#4694)
In multi-repository projects every repository's branch submenu read and wrote the same expansion state, so expanding Remote or a folder in one (e.g. to check out a remote branch) expanded it in all others. Each repository's submenu now keeps its own expansion (keys scoped by repository root); the single-repository popup keeps its saved state.
2026-11-20 12:57:30 +08:00
l0ng-ai f40bcd747f fix(database): complete columns of custom JDBC data sources (#4692)
SQL completion for custom JDBC data sources knew tables but no columns: the JDBC completion model left every table's columns empty (no alias. members, no WHERE columns, no SELECT * expansion). The bridge returns a namespace's columns in one DatabaseMetaData.getColumns call (schemaColumns) and the model fills each table; a driver refusing it still completes tables.
2026-11-20 12:27:41 +08:00
l0ng-ai c752f007be fix(run): show the compile errors when Update Application's build fails (#4691)
A failed Spring Boot / Tomcat update build only said "Application update build failed" and the Run tool window returned to the app's tab, hiding the reason. The notification now lists the compiler errors: from the Java language server's build, and from the Maven/Gradle update build's output (Maven, javac and Kotlin error lines, ANSI-stripped, de-duplicated, first ten). Notification bodies keep their line breaks.
2026-11-20 12:23:04 +08:00
l0ng-ai bcdff6886f fix(settings): organize editor appearance controls (#4687)
Editor > General > Appearance gets four titled sections (caret behavior, code structure, presentation, code assistance): line numbers and indent guides sit together, whitespace controls stay indented under their toggle, using the existing Settings section typography and spacing.
2026-11-20 12:21:02 +08:00
Deng Liuтаdengliu b7e9276b0f feat(agents): open model settings from the picker and composer (#4689)
The model picker showed settings only for the active model. Clicking the effort/context summary beside the model name now edits the current model directly, and each model row has an arrow that opens that model's settings without selecting it; changing a setting there selects the model and keeps the panel open, Back/Escape without an edit leaves the selection alone. Works in New Task and existing chats without sending the draft.

Co-authored-by: dengliu <[email protected]>
2026-11-20 12:19:53 +08:00
Muuтаmuutot 6023e391bc fix(editor): keep line-end annotations clear of a folded chip (#4688)
A header-line fold's chip is drawn at the same position as the zero-width anchors of line-end annotations, so the Code Vision hint, plugin line-end messages and inline blame painted over the chip and took its clicks. A shared foldChipWidth helper measures a chip drawn after an anchor and all three consumers step past it (Code Vision gains the MutationObserver the others already had).

Co-authored-by: muutot <[email protected]>
2026-11-20 12:15:57 +08:00
l0ng-ai 3d80e661b7 fix(search): keep Find results usable in narrow docks (#4681)
The pinned Find tool window moves its result actions to a vertical toolbar and the replacement controls to a wrapping footer. Wide docks show results beside the source preview, narrow docks stack them and remember the divider per layout; result rows use the editor code size and truncate long paths before file names and match counts.
2026-11-20 11:52:49 +08:00
zhzhsxтаzhzhsx b66439ceda fix(editor): keep the hover documentation from moving as it opens (#4682)
The hover documentation was placed twice: create() returned a popup holding only its toolbar, CodeMirror measured and placed it, and it moved once the text arrived. The body is now built in a layout effect and rendered before create() returns (flushSync), so the tooltip is measured once at its final size; the F1 popup and Documentation tool window share DocView and lose their empty first frame too.

Co-authored-by: zhzhsx <[email protected]>
2026-11-20 11:50:04 +08:00
l0ng-ai 899fe888b7 fix(docker): show container logs, processes and image layers without the docker CLI (#4686)
Engine API connections (SSH tunnel, socket, TCP) still ran docker logs / top / image history, failing on machines without the docker CLI. These now use the Engine API when the CLI is missing: logs stream and follow over their own connection (chunked encoding and per-stream frames, or a TTY's raw stream, cancellable); processes and image layers come from /top and /history. Refs #4648.
2026-11-20 11:46:36 +08:00
l0ng-ai e7de2aaf6d fix(docker): disable a container's actions while one runs on it (#4685)
Container actions gave no feedback while a slow (remote) daemon worked, inviting repeated or conflicting clicks. A container is now held busy from the request until the following snapshot: its actions are disabled in the dashboard, Services toolbar and context menu, the running one shows a spinner, and a second request is ignored. Compose actions are disabled while a Docker task runs. Refs #4648.
2026-11-20 11:46:30 +08:00
l0ng-ai 9293b13737 feat(vcs): show the Rollback Changes files as a checkable tree (#4684)
Rollback Changes listed the files flat. It now uses the checkable change tree of the Shelve and Create Patch dialogs: files grouped by directory under the repository, with tri-state boxes on repository and directory rows; the summary follows the selection.
2026-11-20 11:45:27 +08:00
l0ng-ai d1f79d05b3 fix(project-tree): add Manage Remotes and Clone to the Project view's Git menu (#4680)
The Project view's Git submenu stopped at Stash / Unstash; it now ends with Manage Remotes… and Clone…, like the editor's Git submenu and IDEA's Git context menu. Covered by a new e2e test in editorGitMenu.spec.ts.
2026-11-20 11:39:28 +08:00
l0ng-ai 176c43c908 fix(editor): make the paste history preview resizable (#4677)
Paste from History gives the preview more room by default and remembers the divider position (a resizable split). Delete moves beside the filter as a toolbar button; the snippets and preview use the active editor's font and zoom, and the preview drops line numbers to use its full width.
2026-11-20 11:33:27 +08:00
Nc 20b6b0aed5 fix(maven): sort sidebar profiles by ID (#4679)
The Maven sidebar listed profiles in model order. Profiles within each project group now sort by ID ignoring case, as IntelliJ's Maven tool window does; the -P argument keeps the model order.

Co-authored-by: qiany-sui <[email protected]>
2026-11-20 11:30:31 +08:00
l0ng-ai 101a0862e4 fix(database): reconnect a custom JDBC data source whose session was lost (#4675)
When a proxy or tunnel dropped an idle custom JDBC connection, every later statement failed and the source still showed Connected: the cached pool was only marked closed when the IDE closed it. After a failed statement the bridge now checks Connection.isValid (new valid op); an invalid or orphaned session closes the pool so the next statement or Connect reconnects. Keep-alive for JDBC uses the same check (and its option shows in the dialog); failures log at info.
2026-11-20 11:29:35 +08:00
Bin b48f0b6071 fix(vcs): enlarge deleted line marker hit area (#4669)
The deleted-lines marker is drawn above its gutter row, but clicks were resolved from the pointer's row, so clicking the triangle near the line boundary could miss the deletion. The marker gets a 12x12 transparent hit area (same triangle) with a pointer cursor, and clicks on it resolve to the deletion's row. Verified with vcs hunks and editor cm vitest, typecheck, and in the app (clicking the marker's upper half opens the Deleted lines popup).

Co-authored-by: ffgenius <[email protected]>
2026-11-20 11:23:37 +08:00
l0ng-ai a9b16c3e06 fix(debugger): keep call stack locations visible in narrow docks (#4671)
Call stack locations stay visible in narrow debug docks. Verified with e2e debugStackLayout, debugger vitest and typecheck.
2026-11-20 11:13:32 +08:00
74 змінених файлів з 2392 додано та 580 видалено

No files matched your search

+3
Переглянути файл
@@ -176,6 +176,8 @@ pub struct CommitSettings {
pub agent_model: String,
/// That model's thinking level for commit messages; empty keeps the agent's.
pub agent_effort: String,
/// Show the Generate Commit Message with Agent button above the commit message.
pub agent_button: bool,
}
impl Default for CommitSettings {
@@ -201,6 +203,7 @@ impl Default for CommitSettings {
agent: String::new(),
agent_model: String::new(),
agent_effort: String::new(),
agent_button: true,
}
}
}
+8
Переглянути файл
@@ -749,6 +749,14 @@ impl Pool {
}
/// The keep-alive ping (Oracle needs a FROM clause).
/// Keep-alive: one cheap round trip on the session.
pub async fn ping(&self) -> IdeResult<()> {
match self {
Pool::Jdbc(p) => p.ping().await,
_ => self.rows(self.ping_sql(), 1).await.map(|_| ()),
}
}
pub fn ping_sql(&self) -> &'static str {
match self {
Pool::Oracle(_) => "SELECT 1 FROM DUAL",
+91 -1
Переглянути файл
@@ -5,6 +5,7 @@ use crate::{DataSource, DbManager, QueryResult, ResultColumn};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::io::{Cursor, Read};
use std::path::{Path, PathBuf};
use std::process::Stdio;
@@ -458,6 +459,44 @@ impl JdbcPool {
}
async fn request(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult<QueryResult> {
let result = self.exchange_once(fields, sql, cancel).await;
if let Err(e) = &result
&& fields.first() != Some(&"open")
&& e.kind != ide_core::error::ErrorKind::Cancelled
&& !self.is_closed()
&& !self.session_valid().await
{
// The session is gone (a proxy or tunnel dropped the idle TCP connection): close the
// pool so the next statement or Connect starts a new one instead of failing forever.
self.close().await;
}
result
}
/// Keep-alive: checks the session (any SQL would be dialect-specific) and closes a dead one.
pub(crate) async fn ping(&self) -> IdeResult<()> {
if self.session_valid().await {
return Ok(());
}
self.close().await;
Err(IdeError::new(ide_core::error::ErrorKind::Io, "JDBC connection was lost"))
}
/// Whether the JDBC session still works, asked after a failed statement.
async fn session_valid(&self) -> bool {
if self.bridge.lock().await.is_none() {
return false;
}
let cancel = CancellationToken::new();
match tokio::time::timeout(Duration::from_secs(10), self.exchange_once(&["valid"], "", &cancel)).await {
Ok(Ok(result)) => {
result.rows.first().and_then(|row| row.first()).cloned().flatten().as_deref() != Some("false")
}
Ok(Err(_)) | Err(_) => false,
}
}
async fn exchange_once(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult<QueryResult> {
let mut slot = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
@@ -562,14 +601,26 @@ fn decode(data: &[u8], sql: &str, elapsed_ms: f64) -> IdeResult<QueryResult> {
impl DbManager {
pub(crate) async fn jdbc_completion(&self, id: &str, pool: &JdbcPool) -> IdeResult<crate::CompletionModel> {
let mut tables = vec![];
let mut column_count = 0;
let schemas = self.schemas(id).await?;
for schema in &schemas {
// Columns of the whole namespace in one call; a driver that refuses it still completes tables.
let mut columns = if column_count < crate::MAX_META_ROWS {
pool.metadata(&["schemaColumns", schema]).await.map(schema_columns).unwrap_or_else(|e| {
tracing::warn!("JDBC columns of {schema}: {}", e.message);
HashMap::new()
})
} else {
HashMap::new()
};
for table in self.tables(id, schema).await? {
let columns = columns.remove(&table.name).unwrap_or_default();
column_count += columns.len();
tables.push(crate::CompletionTable {
schema: schema.clone(),
name: table.name,
kind: table.kind,
columns: vec![],
columns,
});
if tables.len() >= crate::MAX_META_ROWS {
break;
@@ -594,10 +645,49 @@ impl DbManager {
}
}
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default) by table.
fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::CompletionColumn>> {
let mut by_table: HashMap<String, Vec<crate::CompletionColumn>> = HashMap::new();
for row in rows {
let mut it = row.into_iter();
let (Some(Some(table)), Some(Some(name))) = (it.next(), it.next()) else { continue };
let data_type = it.next().flatten().unwrap_or_default();
let nullable = it.next().flatten().as_deref() != Some("0");
let has_default = it.next().flatten().is_some();
by_table.entry(table).or_default().push(crate::CompletionColumn {
name,
data_type,
nullable,
primary_key: false,
has_default,
});
}
by_table
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn schema_columns_group_by_table() {
let row = |t: &str, n: &str, null: &str, def: Option<&str>| {
vec![Some(t.into()), Some(n.into()), Some("INT".into()), Some(null.into()), def.map(Into::into)]
};
let by_table = schema_columns(vec![
row("orders", "id", "0", None),
row("orders", "note", "1", Some("'none'")),
row("items", "sku", "1", None),
vec![None, Some("orphan".into())],
]);
let orders = &by_table["orders"];
assert_eq!(orders.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "note"]);
assert_eq!((orders[0].nullable, orders[0].has_default), (false, false));
assert_eq!((orders[1].nullable, orders[1].has_default), (true, true));
assert_eq!(by_table["items"].len(), 1);
assert_eq!(by_table.len(), 2);
}
#[tokio::test]
async fn frame_codec_checks_both_16_mib_boundaries() {
assert_eq!(encode(7, &["a"]).unwrap(), [0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 1, b'a']);
+12 -7
Переглянути файл
@@ -379,8 +379,8 @@ pub(crate) fn keep_alive(pool: &Arc<Pool>, every: Duration) {
loop {
tick.tick().await;
let Some(p) = pool.upgrade().filter(|p| !p.is_closed()) else { break };
if let Err(e) = p.rows(p.ping_sql(), 1).await {
tracing::debug!("keep-alive: {}", e.message);
if let Err(e) = p.ping().await {
tracing::info!("keep-alive: {}", e.message);
}
}
});
@@ -847,12 +847,12 @@ impl DbManager {
}
pub fn is_connected(&self, id: &str) -> bool {
self.pools.lock().contains_key(id)
self.pools.lock().get(id).is_some_and(|p| !p.is_closed())
}
/// Connected targets (data source ids, `<id>:<database>`).
pub fn connected(&self) -> Vec<String> {
self.pools.lock().keys().cloned().collect()
self.pools.lock().iter().filter(|(_, p)| !p.is_closed()).map(|(id, _)| id.clone()).collect()
}
/// The pool of target `id`, connecting first if needed.
@@ -862,8 +862,13 @@ impl DbManager {
if self.tunnels.lock().get(source_id).is_some_and(|t| t.is_closed()) {
self.disconnect_source(source_id).await;
}
if let Some(p) = self.pools.lock().get(id) {
return Ok(p.clone());
let cached = self.pools.lock().get(id).cloned();
if let Some(p) = cached {
if !p.is_closed() {
return Ok(p);
}
// The connection broke (a custom JDBC session whose TCP connection was dropped): reconnect.
self.disconnect(id).await;
}
let source = self.source(id)?;
let password = self.password(&source).await;
@@ -917,7 +922,7 @@ impl DbManager {
/// Disconnects every database of data source `id`.
pub async fn disconnect_source(&self, id: &str) {
let targets: Vec<String> = self.connected().into_iter().filter(|t| split_target(t).0 == id).collect();
let targets: Vec<String> = self.pools.lock().keys().filter(|t| split_target(t).0 == id).cloned().collect();
for t in targets {
self.disconnect(&t).await;
}
+37 -1
Переглянути файл
@@ -90,7 +90,10 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
assert!(result.has_more);
assert_eq!(result.rows, vec![vec![Some("1".into()), None]]);
assert_eq!(result.columns[1].name, "label");
assert_eq!(db.completion("test").await?.default_schema, "main");
let completion = db.completion("test").await?;
assert_eq!(completion.default_schema, "main");
let items = completion.tables.iter().find(|t| t.schema == "main" && t.name == "items").expect("items");
assert_eq!(items.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "label"]);
db.execute("test", "create temporary table session_marker as select 42 as id", 1, &c).await?;
let stop = CancellationToken::new();
let (cancelled, ()) =
@@ -213,3 +216,36 @@ async fn unresponsive_driver_closes_before_reconnect() -> IdeResult<()> {
db.disconnect("test").await;
Ok(())
}
#[tokio::test]
#[ignore = "requires JDBC_FIXTURE_JAR (java/jdbc-bridge/build.py --test --out fixture.jar) and Java 17+"]
async fn a_lost_session_reconnects_on_the_next_statement() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
db.save_jdbc_driver(DbJdbcDriver {
id: "fixture".into(),
name: "Fixture".into(),
jars: vec![std::env::var("JDBC_FIXTURE_JAR").unwrap()],
class_name: "ai.openidea.jdbc.SelfTest$Fixture".into(),
url_template: String::new(),
})?;
let source = DataSource {
id: "test".into(),
name: "Fixture".into(),
driver: DbDriver::Jdbc,
global: true,
jdbc_driver: "fixture".into(),
url: "jdbc:fixture:".into(),
..Default::default()
};
db.save_sources(vec![source]).await?;
let cancel = CancellationToken::new();
db.execute("test", "first", 1, &cancel).await?;
// The fixture's session reports itself invalid after "drop", like a connection a proxy reset.
assert!(db.execute("test", "drop", 1, &cancel).await.unwrap_err().message.contains("connection reset"));
assert!(!db.is_connected("test"), "a lost session is no longer listed as connected");
assert_eq!(db.execute("test", "after reconnect", 1, &cancel).await?.affected, Some(1.0));
assert!(db.is_connected("test"));
db.disconnect("test").await;
Ok(())
}
+382 -9
Переглянути файл
@@ -7,9 +7,10 @@
use crate::{
COMPOSE_DIR, COMPOSE_FILES, COMPOSE_PROJECT, COMPOSE_SERVICE, ContainerOp, DockerAvailability, DockerContainer,
DockerEndpoint, DockerImage, DockerNetwork, DockerObject, DockerSnapshot, DockerVolume, split_csv,
DockerEndpoint, DockerImage, DockerImageLayer, DockerLogLine, DockerNetwork, DockerObject, DockerProcessList,
DockerSnapshot, DockerVolume, split_csv,
};
use ide_core::{IdeError, IdeResult};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::Deserialize;
use std::collections::BTreeMap;
use std::io::{Read, Write};
@@ -193,9 +194,15 @@ fn request(addr: &Address, method: &str, path: &str, timeout: Duration) -> IdeRe
read_response(&mut conn)
}
/// Reads an HTTP/1.1 response: head until `\r\n\r\n`, then the body per its
/// framing (chunked, `Content-Length`, or until the connection closes).
fn read_response(stream: &mut impl Read) -> IdeResult<Response> {
/// A response's status line and body framing.
struct Head {
status: u16,
chunked: bool,
length: Option<usize>,
}
/// Reads an HTTP/1.1 response head until `\r\n\r\n`.
fn read_head(stream: &mut impl Read) -> IdeResult<Head> {
let mut head: Vec<u8> = Vec::new();
let mut byte = [0u8; 1];
loop {
@@ -228,16 +235,27 @@ fn read_response(stream: &mut impl Read) -> IdeResult<Response> {
length = value.parse().ok();
}
}
let body = if chunked {
Ok(Head { status, chunked, length })
}
/// Reads an HTTP/1.1 response: its head, then the body per its framing
/// (chunked, `Content-Length`, or until the connection closes).
fn read_response(stream: &mut impl Read) -> IdeResult<Response> {
let head = read_head(stream)?;
let body = read_body(stream, &head)?;
Ok(Response { status: head.status, body })
}
fn read_body(stream: &mut impl Read, head: &Head) -> IdeResult<Vec<u8>> {
Ok(if head.chunked {
read_chunked(stream)?
} else if let Some(n) = length {
} else if let Some(n) = head.length {
read_exact_n(stream, n)?
} else {
let mut body = Vec::new();
stream.read_to_end(&mut body)?;
body
};
Ok(Response { status, body })
})
}
/// Reads one `\n`-terminated line (returned without it).
@@ -482,6 +500,292 @@ pub(crate) fn inspect(
})())
}
/// The processes running in a container (`docker top`).
pub(crate) fn container_top(ep: &DockerEndpoint, id: &str, timeout: Duration) -> Option<IdeResult<DockerProcessList>> {
let addr = address(ep)?;
Some((|| {
let body = check(request(&addr, "GET", &format!("/containers/{}/top", path_segment(id)), timeout)?)?;
serde_json::from_str::<ApiTop>(&body)
.map(|t| DockerProcessList { titles: t.titles, processes: t.processes })
.map_err(|e| IdeError::internal(format!("the Docker daemon's process list is not JSON: {e}")))
})())
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiTop {
titles: Vec<String>,
processes: Vec<Vec<String>>,
}
/// An image's layers, newest first (`docker image history`).
pub(crate) fn image_history(
ep: &DockerEndpoint,
id: &str,
timeout: Duration,
) -> Option<IdeResult<Vec<DockerImageLayer>>> {
let addr = address(ep)?;
Some((|| {
let body = check(request(&addr, "GET", &format!("/images/{}/history", path_segment(id)), timeout)?)?;
let layers = serde_json::from_str::<Vec<ApiLayer>>(&body)
.map_err(|e| IdeError::internal(format!("the Docker daemon's image history is not JSON: {e}")))?;
Ok(map_layers(layers, unix_now()))
})())
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiLayer {
id: String,
created: i64,
created_by: String,
size: i64,
comment: String,
}
fn map_layers(layers: Vec<ApiLayer>, now: i64) -> Vec<DockerImageLayer> {
layers
.into_iter()
.map(|l| DockerImageLayer {
id: l.id,
created_by: l.created_by,
size: human_size(l.size),
created_since: human_duration((now - l.created).max(0)),
created_at: unix_utc(l.created),
comment: l.comment,
})
.collect()
}
fn unix_now() -> i64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
}
/// How often a log stream that has nothing to read checks for cancellation.
const LOG_POLL: Duration = Duration::from_millis(200);
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiContainerInspect {
config: ApiContainerConfig,
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiContainerConfig {
tty: bool,
}
/// Streams a container's logs (`tail` last lines, then follows while `follow`)
/// from `ep`'s daemon until they end or `cancel` fires.
#[allow(clippy::too_many_arguments)]
pub(crate) fn logs(
ep: &DockerEndpoint,
id: &str,
tail: u32,
follow: bool,
timestamps: bool,
timeout: Duration,
cancel: &CancellationToken,
on_line: &dyn Fn(DockerLogLine),
) -> Option<IdeResult<()>> {
let addr = address(ep)?;
Some((|| {
// A TTY container's log is one raw stream; otherwise it is framed per stream.
let body = check(request(&addr, "GET", &format!("/containers/{}/json", path_segment(id)), timeout)?)?;
let tty = serde_json::from_str::<ApiContainerInspect>(&body).map(|c| c.config.tty).unwrap_or(false);
let path = format!(
"/containers/{}/logs?stdout=1&stderr=1&tail={tail}&follow={}&timestamps={}",
path_segment(id),
u8::from(follow),
u8::from(timestamps),
);
let mut conn = Conn::connect(&addr, timeout)?;
conn.write_all(
format!("GET {path} HTTP/1.1\r\nHost: docker\r\nUser-Agent: openidea\r\nConnection: close\r\n\r\n")
.as_bytes(),
)?;
let head = read_head(&mut conn)?;
if !(200..300).contains(&head.status) {
let body = read_body(&mut conn, &head)?;
check(Response { status: head.status, body })?;
}
conn.set_timeouts(LOG_POLL);
let mut decoder = LogDecoder::new(&head, tty);
let mut buf = [0u8; 8192];
while !decoder.done() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
match conn.read(&mut buf) {
Ok(0) => break,
Ok(n) => decoder.feed(&buf[..n], &mut |line| on_line(line))?,
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut | std::io::ErrorKind::Interrupted
) => {}
Err(e) => return Err(e.into()),
}
}
decoder.finish(&mut |line| on_line(line));
Ok(())
})())
}
/// Turns a log response body, as it arrives, into lines: undoes the chunked
/// transfer encoding, then the per-stream frames (8-byte header: stream, 3 zero
/// bytes, big-endian length) unless the container has a TTY.
struct LogDecoder {
body: BodyFraming,
tty: bool,
header: Vec<u8>,
frame_left: usize,
frame_stderr: bool,
/// Partial lines of stdout and stderr.
partial: [Vec<u8>; 2],
}
enum BodyFraming {
Chunked { state: ChunkState, line: Vec<u8> },
Length(usize),
Close,
}
#[derive(Clone, Copy, PartialEq)]
enum ChunkState {
Size,
Data(usize),
DataEnd,
Trailer,
Done,
}
impl LogDecoder {
fn new(head: &Head, tty: bool) -> Self {
let body = if head.chunked {
BodyFraming::Chunked { state: ChunkState::Size, line: Vec::new() }
} else if let Some(n) = head.length {
BodyFraming::Length(n)
} else {
BodyFraming::Close
};
Self { body, tty, header: Vec::new(), frame_left: 0, frame_stderr: false, partial: [Vec::new(), Vec::new()] }
}
fn done(&self) -> bool {
matches!(self.body, BodyFraming::Chunked { state: ChunkState::Done, .. } | BodyFraming::Length(0))
}
fn feed(&mut self, mut bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) -> IdeResult<()> {
let mut payload = Vec::new();
match &mut self.body {
BodyFraming::Close => payload.extend_from_slice(bytes),
BodyFraming::Length(left) => {
let take = (*left).min(bytes.len());
payload.extend_from_slice(&bytes[..take]);
*left -= take;
}
BodyFraming::Chunked { state, line } => {
while !bytes.is_empty() {
match *state {
ChunkState::Done => break,
ChunkState::Data(n) => {
let take = n.min(bytes.len());
payload.extend_from_slice(&bytes[..take]);
bytes = &bytes[take..];
*state = if take == n { ChunkState::DataEnd } else { ChunkState::Data(n - take) };
}
_ => {
let b = bytes[0];
bytes = &bytes[1..];
if b != b'\n' {
if b != b'\r' {
line.push(b);
}
continue;
}
let text = String::from_utf8_lossy(line).into_owned();
line.clear();
*state = match *state {
ChunkState::Size => {
let size = text.split(';').next().unwrap_or_default().trim();
match usize::from_str_radix(size, 16) {
Ok(0) => ChunkState::Trailer,
Ok(n) => ChunkState::Data(n),
Err(_) => {
return Err(IdeError::internal(
"the Docker daemon answered with a malformed chunked response",
));
}
}
}
ChunkState::DataEnd => ChunkState::Size,
_ if text.is_empty() => ChunkState::Done,
other => other,
};
}
}
}
}
}
self.frames(&payload, emit);
Ok(())
}
fn frames(&mut self, mut bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) {
if self.tty {
self.lines(false, bytes, emit);
return;
}
while !bytes.is_empty() {
if self.frame_left == 0 {
let take = (8 - self.header.len()).min(bytes.len());
self.header.extend_from_slice(&bytes[..take]);
bytes = &bytes[take..];
if self.header.len() == 8 {
self.frame_stderr = self.header[0] == 2;
self.frame_left =
u32::from_be_bytes([self.header[4], self.header[5], self.header[6], self.header[7]]) as usize;
self.header.clear();
}
continue;
}
let take = self.frame_left.min(bytes.len());
self.lines(self.frame_stderr, &bytes[..take], emit);
self.frame_left -= take;
bytes = &bytes[take..];
}
}
fn lines(&mut self, stderr: bool, bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) {
let partial = &mut self.partial[usize::from(stderr)];
for &b in bytes {
if b == b'\n' {
emit(DockerLogLine { stderr, text: line_text(partial) });
partial.clear();
} else {
partial.push(b);
}
}
}
/// Emits the last lines that ended without a newline.
fn finish(&mut self, emit: &mut dyn FnMut(DockerLogLine)) {
for stderr in [false, true] {
let partial = &mut self.partial[usize::from(stderr)];
if !partial.is_empty() {
emit(DockerLogLine { stderr, text: line_text(partial) });
partial.clear();
}
}
}
}
fn line_text(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes.strip_suffix(b"\r").unwrap_or(bytes)).into_owned()
}
/// One URL path segment, percent-encoded so an id cannot change the path.
fn path_segment(id: &str) -> String {
let mut out = String::with_capacity(id.len());
@@ -817,6 +1121,75 @@ mod tests {
assert!(read_response(&mut &garbage[..]).is_err());
}
/// Feeds `body` one byte at a time, as a slow connection delivers it.
fn decode(head: Head, tty: bool, body: &[u8]) -> (Vec<(bool, String)>, bool) {
let mut lines = Vec::new();
let mut decoder = LogDecoder::new(&head, tty);
for b in body {
decoder.feed(std::slice::from_ref(b), &mut |l| lines.push((l.stderr, l.text))).unwrap();
}
let done = decoder.done();
decoder.finish(&mut |l| lines.push((l.stderr, l.text)));
(lines, done)
}
fn frame(stream: u8, text: &str) -> Vec<u8> {
let mut f = vec![stream, 0, 0, 0];
f.extend((text.len() as u32).to_be_bytes());
f.extend(text.as_bytes());
f
}
#[test]
fn engine_image_history_reads_like_the_cli() {
let layers: Vec<ApiLayer> = serde_json::from_str(
r#"[{"Id":"sha256:abc","Created":1000,"CreatedBy":"CMD [\"python3\"]","Size":20500,"Comment":"buildkit","Tags":["py:3"]},
{"Id":"<missing>","Created":940,"CreatedBy":"RUN x","Size":0,"Comment":""}]"#,
)
.unwrap();
let rows = map_layers(layers, 1000 + 2 * 7 * 86_400);
assert_eq!(
rows.iter().map(|l| (l.id.as_str(), l.size.as_str(), l.created_since.as_str())).collect::<Vec<_>>(),
[("sha256:abc", "20.5kB", "2 weeks ago"), ("<missing>", "0B", "2 weeks ago")]
);
assert_eq!(rows[0].created_by, "CMD [\"python3\"]");
let top: ApiTop = serde_json::from_str(r#"{"Titles":["PID","CMD"],"Processes":[["1","sh"]]}"#).unwrap();
assert_eq!(
(top.titles, top.processes),
(vec!["PID".to_owned(), "CMD".to_owned()], vec![vec!["1".to_owned(), "sh".to_owned()]])
);
}
#[test]
fn container_logs_split_into_stream_lines_across_chunks_and_frames() {
// Frames split mid-line, a CRLF line, and a stderr line between stdout parts.
let mut framed = frame(1, "tick 1\r\ntick");
framed.extend(frame(2, "oops\n"));
framed.extend(frame(1, " 2\nlast"));
let mut chunked = Vec::new();
for part in framed.chunks(7) {
chunked.extend(format!("{:x}\r\n", part.len()).as_bytes());
chunked.extend(part);
chunked.extend(b"\r\n");
}
chunked.extend(b"0\r\n\r\n");
let (lines, done) = decode(Head { status: 200, chunked: true, length: None }, false, &chunked);
assert!(done);
let expected = [(false, "tick 1"), (true, "oops"), (false, "tick 2"), (false, "last")];
assert_eq!(lines, expected.map(|(e, t)| (e, t.to_owned())));
// A TTY container's log is one raw stream; the body may end with the connection.
let (lines, done) = decode(Head { status: 200, chunked: false, length: None }, true, b"a\r\nb\n");
assert!(!done);
assert_eq!(lines, [(false, "a".to_owned()), (false, "b".to_owned())]);
// A Content-Length body ends after its length.
let body = frame(1, "one\n");
let (lines, done) = decode(Head { status: 200, chunked: false, length: Some(body.len()) }, false, &body);
assert!(done);
assert_eq!(lines, [(false, "one".to_owned())]);
}
#[test]
fn daemon_errors_carry_their_message() {
let resp = Response { status: 404, body: br#"{"message":"No such container: missing"}"#.to_vec() };
+15
Переглянути файл
@@ -287,6 +287,11 @@ fn check_id(id: &str) -> IdeResult<&str> {
/// `docker image history --no-trunc --format '{{json .}}'` of one image.
pub fn image_history(ep: &DockerEndpoint, id: &str) -> IdeResult<Vec<DockerImageLayer>> {
let id = check_id(id)?;
if docker_executable().is_none()
&& let Some(layers) = engine::image_history(ep, id, QUICK)
{
return layers;
}
let out = run(ep, &["image", "history", "--no-trunc", "--format", "{{json .}}", id], QUICK)?;
Ok(parse_image_history(&out))
}
@@ -294,6 +299,11 @@ pub fn image_history(ep: &DockerEndpoint, id: &str) -> IdeResult<Vec<DockerImage
/// `docker top <id>` of a running container.
pub fn container_top(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerProcessList> {
let id = check_id(id)?;
if docker_executable().is_none()
&& let Some(processes) = engine::container_top(ep, id, QUICK)
{
return processes;
}
let out = run(ep, &["top", id], QUICK)?;
Ok(parse_container_top(&out))
}
@@ -316,6 +326,11 @@ pub fn logs(
cancel: &CancellationToken,
on_line: &dyn Fn(DockerLogLine),
) -> IdeResult<()> {
if docker_executable().is_none()
&& let Some(streamed) = engine::logs(ep, id, tail, follow, timestamps, QUICK, cancel, on_line)
{
return streamed;
}
let tail = tail.to_string();
let mut args = vec!["logs", "--tail", &tail];
if follow {
+1
Переглянути файл
@@ -850,6 +850,7 @@ mod tests {
"agent": "",
"agentModel": "",
"agentEffort": "",
"agentButton": true,
})
);
}
+3 -1
Переглянути файл
@@ -55,7 +55,9 @@ Codex keeps its own project trust decision. If it disables the current project's
<Step title="Pick the agent and its settings">
Choose the agent, and its model, mode and other options when it offers them. Cached models appear immediately; the selected agent's catalog refreshes in the background when it is more than 15 minutes old, without sending a prompt or attaching project MCP servers.
Model-specific effort levels and context options are looked up when you select a model whose settings are not cached, even before its first task. **Loading model settings…** appears beside the model during this short-lived lookup; no prompt is sent and existing tasks are not changed. Each model keeps its own choices, and models that report no effort control do not borrow another model's levels.
Click the model name to switch models, or click the settings beside it (for example **High · 1M**) to change effort or context size directly. In the model list, use the arrow on a model's row to see its settings without selecting it. Changing a setting selects that model; going back without an edit keeps the previous selection. These controls are also available in an existing chat.
If settings aren't cached, OpenIDEA looks them up when you select or inspect the model. No prompt is sent. Each model keeps its own draft choices, and models that report no effort control do not borrow another model's levels.
After changing the agent CLI or account, open the model picker and choose **Refresh models**. Refreshes share one lookup and have a 30-second cooldown after completion, including failures. Selecting an uncached model's settings does not wait for another model's cooldown. Cached choices remain usable while refreshing or after a failure; use **Refresh models** to retry a failed lookup after its cooldown.
+3 -1
Переглянути файл
@@ -55,7 +55,9 @@ Codex 有自己的项目信任设置。如果它禁用了当前项目的 `.codex
<Step title="选择 agent 及其设置">
选择 agent,以及它提供的模型、模式等选项。缓存的模型会立即显示;所选 agent 的模型列表超过 15 分钟未更新时,会在后台刷新,不发送提示词,也不接入项目 MCP 服务器。
选择尚未缓存设置的模型时,会按需查询该模型的思考强度和上下文选项,无需先运行任务。短暂查询期间,模型旁会显示**正在加载模型设置…**;查询不发送提示词,也不更改现有任务。每个模型分别保留你选择的设置;明确不提供思考强度的模型不会沿用其他模型的强度选项。
点击模型名称可切换模型;点击旁边的设置(如 **High · 1M**)可直接调整思考强度或上下文大小。在模型列表中,点击一行右侧的箭头可以先查看该模型的设置。修改设置时才会选中该模型,直接返回则保留原来的选择。在已有对话中也可以这样操作。
选择模型或查看其设置时,如果还没有缓存,OpenIDEA 会按需查询,无需发送提示词。草稿分别保留各模型的选择;未提供思考强度的模型不会沿用其他模型的选项。
更改 agent CLI 或账号后,打开模型选择器并单击 **刷新模型**。并发刷新会共用一次查询;每次查询完成后(包括失败)都有 30 秒冷却时间。查询其他未缓存模型的设置无需等待前一个模型的冷却时间。刷新中或刷新失败后,缓存选项仍可使用;查询失败后,可在冷却结束后用**刷新模型**重试。
+50 -6
Переглянути файл
@@ -109,6 +109,7 @@ async function seed(
model = "atlas",
status: AgentTask["status"] = "ready",
catalogOnly = false,
offered = provider,
) {
await stubDesktop(page);
await page.evaluate(
@@ -218,7 +219,7 @@ async function seed(
if (surface === "new") store.openHome();
else store.openTask(firstTask.id);
},
{ placement, surface, provider, firstTask, secondTask, subagent, model, status, modelId, catalogOnly },
{ placement, surface, provider: offered, firstTask, secondTask, subagent, model, status, modelId, catalogOnly },
);
await expect(box(page)).toBeVisible();
await page.evaluate(() => document.fonts.ready);
@@ -233,9 +234,8 @@ function history(page: Page) {
function modelButton(page: Page) {
return page.getByRole("button", { name: "Model", exact: true }).filter({ visible: true });
}
/** The effort is shown on the model button, after the model's name. */
function effortLabel(page: Page) {
return modelButton(page).locator("[class*='modelDetail']");
return page.getByRole("button", { name: /^Model settings:/ }).filter({ visible: true });
}
async function expectEffort(page: Page, name: string) {
await expect(effortLabel(page)).toHaveText(name);
@@ -284,6 +284,50 @@ async function expectNoSubmission(page: Page) {
expect(await ipcCalls(page, "agent_create")).toEqual([]);
}
for (const surface of ["new", "task"] as const) {
test(`${surface}: configure another model from its row, then edit its context from the composer`, async ({
workbench: page,
}) => {
const context = option(
"context_tier",
"model_config",
[
["default", "200K"],
["long_context", "1M"],
],
"default",
);
const offered = {
...provider,
thoughtLevels: { ...provider.thoughtLevels, atlas: [atlas, context], swift: [swift, context] },
};
await seed(page, "editor", surface, "atlas", "ready", false, offered);
await box(page).fill("Review the project structure");
await modelButton(page).click();
const row = page.getByRole("option", { name: /^Swift\b/ });
await row.hover();
const configure = row.getByRole("button", { name: "Configure Swift…" });
if (surface === "task") await configure.press("Enter");
else await configure.click();
await expect(modelButton(page)).toHaveText("Atlas");
await expect(page.getByRole("radio", { name: "Gentle" })).toHaveCount(0);
await page.getByRole("radio", { name: "Thorough" }).click();
await expect(modelButton(page)).toHaveText("Swift");
await expect(page.getByRole("radio", { name: "Thorough" })).toBeChecked();
await page.keyboard.press("Escape");
const settings = page.getByRole("button", { name: /^Model settings:/ });
await expect(settings).toHaveText("Thorough · 200K");
await settings.click();
await page.getByRole("radio", { name: "1M" }).click();
await expect(settings).toHaveText("Thorough · 1M");
await page.getByRole("button", { name: "Back to models" }).click();
await expect(page.getByRole("listbox", { name: "Model", exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(box(page)).toHaveText("Review the project structure");
await expectNoSubmission(page);
});
}
for (const placement of ["editor", "toolWindow"] as const) {
test(`${placement}: existing task cycles advertised values and wraps without editing, moving focus or scrolling`, async ({
workbench: page,
@@ -379,7 +423,7 @@ test("Settings and effort popup exclude the agent shortcut", async ({ workbench:
await expect(search).toBeFocused();
await expect(search).toHaveValue("keymap");
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await modelButton(page).click();
await effortLabel(page).click();
const popup = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(popup).toBeVisible();
await page.keyboard.press("Alt+t");
@@ -603,7 +647,7 @@ test("New Task discovers uncached model effort before the first prompt", async (
await page.screenshot({ path: testInfo.outputPath("model-settings-loading.png") });
await page.evaluate(() => document.dispatchEvent(new Event("test:model-settings-ready")));
await expectEffort(page, "Quick");
await modelButton(page).click();
await effortLabel(page).click();
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("radio", { name: "Quick", exact: true })).toBeVisible();
await expect(efforts.getByRole("radio", { name: "Thorough", exact: true })).toBeVisible();
@@ -636,7 +680,7 @@ test("an existing chat can choose effort for a refreshed model before sending",
await expect(loading).toHaveCount(0);
await expect(modelButton(page)).toHaveAttribute("title", /^Model: Swift\b/);
await expectEffort(page, "Quick");
await modelButton(page).click();
await effortLabel(page).click();
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("radio", { name: "Gentle", exact: true })).toHaveCount(0);
await efforts.getByRole("radio", { name: "Thorough", exact: true }).click();
+75
Переглянути файл
@@ -0,0 +1,75 @@
import { expect, stubDesktop, test } from "./fixtures";
const functionName = "calculateRegionalSettlementFromExternalOrderBeforeReconciliation";
const sourcePath = "/dev/acme-api/build.gradle.kts";
test("keeps frame sources and the keyboard selection visible in a narrow debug dock", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 540 });
await stubDesktop(page);
await page.evaluate(
async ({ functionName, sourcePath }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const servicesModule = "/src/workbench/contributions.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
const { toolWindowService } = await import(/* @vite-ignore */ servicesModule);
const workerFrame = {
id: 51,
name: "processOrder",
path: sourcePath,
line: 5,
column: 0,
presentationHint: null,
};
window.__ipc.handlers.debug_scopes = () => [];
window.__ipc.handlers.debug_stack_trace = () => [workerFrame];
adoptSession(91, {
name: "Reconciliation",
adapter: "debugpy",
status: "paused",
stoppedThread: 1,
selectedThread: 1,
threads: [
{ id: 1, name: "MainThread" },
{ id: 2, name: "Order worker" },
],
selectedFrame: 1,
frames: Array.from({ length: 32 }, (_, index) => ({
id: index + 1,
name: index === 0 ? functionName : index === 1 ? "runBatch" : `reconcile(${index})`,
path: sourcePath,
line: index === 0 ? 41 : index,
column: 0,
presentationHint: null,
})),
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 420);
toolWindowService().show("debug", true);
},
{ functionName, sourcePath },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
const thread = debug.getByRole("button", { name: "Thread", exact: true });
const frames = debug.getByRole("listbox", { name: "Frames", exact: true });
const first = frames.getByRole("option", { selected: true });
await expect(first.getByText(functionName, { exact: true })).toBeVisible();
expect(await frames.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(first.getByText(":42", { exact: true })).toBeInViewport({ ratio: 1 });
expect(await first.getByText(/build\.gradle\.kts/).evaluate((el) => el.clientWidth)).toBeGreaterThan(25);
const shortName = frames.getByText("runBatch", { exact: true });
expect(await shortName.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await frames.focus();
for (let i = 0; i < 25; i++) await page.keyboard.press("ArrowDown");
const selected = frames.getByRole("option", { selected: true });
await expect(selected.getByText("reconcile(25)", { exact: true })).toBeInViewport({ ratio: 0.95 });
expect(await frames.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
await thread.click();
await page.getByRole("option", { name: "Order worker", exact: true }).click();
await expect(thread).toContainText("Order worker");
await expect(frames.getByRole("option", { selected: true })).toContainText("processOrder");
});
+12
Переглянути файл
@@ -64,3 +64,15 @@ test("editor Git submenu keeps repository actions disabled without Git", async (
}
await expect(page.getByRole("menuitem", { name: "Clone…", exact: true })).toBeEnabled();
});
test("Project view Git submenu ends with Manage Remotes and Clone", async ({ workbench: page }) => {
await page.getByRole("treeitem", { name: /README\.md/ }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Git", exact: true }).hover();
const git = page.getByRole("menu").filter({ has: page.getByRole("menuitem", { name: "Clone…", exact: true }) });
const items = git.locator('[role="menuitem"], [role="menuitemcheckbox"]');
await expect(items.nth(-3)).toHaveText(/Unstash Changes…/);
await expect(items.nth(-2)).toHaveText(/Manage Remotes…/);
await expect(items.nth(-1)).toHaveText(/Clone…/);
await git.getByRole("menuitem", { name: "Manage Remotes…", exact: true }).click();
await expect(page.getByRole("dialog", { name: "Git Remotes" })).toBeVisible();
});
+59
Переглянути файл
@@ -0,0 +1,59 @@
import { expect, openFromTree, test } from "./fixtures";
test("Paste from History keeps the list and preview usable in a short dialog", async ({ workbench: page }) => {
const editor = await openFromTree(page, "App.tsx");
const content = editor.locator(".cm-content");
await content.focus();
const baseFont = Number.parseFloat(await content.evaluate((el) => getComputedStyle(el).fontSize));
await page.evaluate(async () => {
const source = await (await fetch("/src/editor/core/extras.ts")).text();
const imports = [...source.matchAll(/["'](\/src\/[^"']+)["']/g)].map((match) => match[1]!);
const activePath = (path: string) => imports.find((url) => url.split("?")[0] === path) ?? path;
const historyPath = activePath("/src/editor/core/clipboardHistory.ts");
const actionsPath = activePath("/src/platform/actions.ts");
const { recordClipboard } = await import(/* @vite-ignore */ historyPath);
const { executeAction } = await import(/* @vite-ignore */ actionsPath);
recordClipboard("const older = 2;");
recordClipboard("const newest = 1;\n// paste marker");
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText: async () => {} } });
for (let i = 0; i < 5; i++) await executeAction("editor.increaseFontSize");
});
const fontSize = `${baseFont + 5}px`;
await expect(content).toHaveCSS("font-size", fontSize);
await page.keyboard.press("Meta+Shift+v");
const dialog = page.getByRole("dialog", { name: "Choose Content to Paste" });
const divider = dialog.getByRole("separator", { name: "Resize paste preview" });
const list = dialog.getByRole("listbox", { name: "Clipboard history" });
const preview = dialog.getByLabel("Paste preview", { exact: true });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
await expect(list.getByText("const newest = 1;", { exact: true })).toHaveCSS("font-size", fontSize);
await expect(preview).toHaveCSS("font-size", fontSize);
await expect(dialog.locator(".cm-gutters")).toHaveCount(0);
await page.setViewportSize({ width: 420, height: 440 });
const search = dialog.getByRole("textbox", { name: "Filter clipboard history" });
const remove = dialog.getByRole("button", { name: "Delete" });
await expect(search).toBeInViewport({ ratio: 1 });
await expect(remove).toBeInViewport({ ratio: 1 });
expect((await remove.boundingBox())!.y).toBeLessThan((await list.boundingBox())!.y);
const previous = Number(await divider.getAttribute("aria-valuenow"));
await divider.press("ArrowDown");
await expect.poll(async () => Number(await divider.getAttribute("aria-valuenow"))).toBeGreaterThan(previous);
const resized = await divider.getAttribute("aria-valuenow");
await expect(dialog.getByRole("button", { name: "Paste" })).toBeInViewport({ ratio: 1 });
await expect(preview).toContainText("// paste marker");
await search.fill("older");
await remove.click();
await expect(dialog.getByText("No matches", { exact: true })).toBeVisible();
await dialog.getByRole("button", { name: "Clear", exact: true }).click();
await expect(search).toHaveValue("");
await search.press("Enter");
await expect(dialog).toBeHidden();
await expect(content).toContainText("const newest = 1;");
await page.keyboard.press("Meta+Shift+v");
await expect(divider).toHaveAttribute("aria-valuenow", resized!);
await page.keyboard.press("Escape");
});
+83
Переглянути файл
@@ -159,3 +159,86 @@ test("Find in Files streams matches by file and opens the chosen one at its line
}, `Editor for ${ROOT}/build.gradle.kts`);
await expect.poll(caretLine).toBe("import com.acme.orders.service.OrderService");
});
test("the Find tool window keeps the selected preview and replacement actions when narrowed", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1500, height: 820 });
await stubDesktop(page);
await page.evaluate(
({ path, relPath }) => {
window.__ipc.handlers.search_validate = () => null;
window.__ipc.handlers.search_start = ({ query, onEvent }) => {
if ((query as SearchQuery).pattern !== "OrderService") return null;
setTimeout(() => {
window.__ipc.send(onEvent, {
type: "file",
file: {
path,
relPath,
matches: [
{
line: 2,
text: "import com.acme.orders.service.OrderService",
ranges: [[31, 43]],
textOffset: 0,
},
],
},
});
window.__ipc.send(onEvent, {
type: "done",
summary: { files: 1, matches: 1, limitHit: false, cancelled: false, elapsedMs: 1 },
});
}, 20);
return null;
};
},
{ path: `${ROOT}/build.gradle.kts`, relPath: "build.gradle.kts" },
);
await page.keyboard.press("Meta+Shift+r");
const popup = page.getByRole("dialog", { name: "Replace in Files" });
await popup.getByRole("textbox", { name: "Text to find" }).fill("OrderService");
await popup.getByRole("textbox", { name: "Replace with" }).fill("OrdersApi");
await expect(popup.getByRole("listbox", { name: "Matches" }).getByRole("option")).toHaveCount(1);
await popup.getByRole("button", { name: "Open in Find Window", exact: true }).click();
const find = page.getByRole("region", { name: "Find", exact: true });
await find.getByRole("button", { name: "Options", exact: true }).click();
await page.getByRole("menuitem", { name: "Move To", exact: true }).hover();
await page.getByRole("menuitem", { name: "Right Top", exact: true }).click();
const dockDivider = page.getByRole("separator", { name: "Resize right tool window", exact: true });
const resizeDock = async (width: number) => {
await expect(dockDivider).toBeVisible();
const handle = (await dockDivider.boundingBox())!;
const dock = (await find.boundingBox())!;
const x = handle.x + handle.width / 2;
const y = handle.y + handle.height / 2;
await page.mouse.move(x, y);
await page.mouse.down();
await page.mouse.move(x + dock.width - width, y, { steps: 5 });
await page.mouse.up();
};
await resizeDock(690);
const row = find.getByRole("treeitem", { name: /OrderService.*OrdersApi/ });
await row.click();
const preview = find.getByRole("region", { name: "Preview", exact: true });
await expect(preview.locator(".cm-content")).toContainText("OrderService");
const divider = find.getByRole("separator", { name: "Resize find preview" });
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await resizeDock(325);
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
await expect(row).toHaveAttribute("aria-selected", "true");
await expect(preview.locator(".cm-content")).toContainText("OrderService");
await expect(find.getByRole("toolbar", { name: "Find actions" })).toHaveAttribute("aria-orientation", "vertical");
for (const label of ["Preview", "Replace Selected", "Replace All"]) {
await expect(find.getByRole("button", { name: label, exact: true })).toBeInViewport({ ratio: 1 });
}
await find.getByRole("button", { name: "Replace All", exact: true }).click();
const confirmation = page.getByRole("dialog", { name: "Replace All" });
await expect(confirmation).toBeVisible();
await confirmation.getByRole("button", { name: "Cancel" }).click();
await expect(confirmation).toBeHidden();
});
+23
Переглянути файл
@@ -80,6 +80,29 @@ test("⌘, opens Settings with the page tree; Escape closes", async ({ workbench
await expect(dialog).toBeHidden();
});
test("editor appearance groups related controls and keeps whitespace options editable", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await settings.getByRole("textbox", { name: "Search settings" }).fill("Show whitespaces");
await settings.getByRole("treeitem", { name: "Appearance", exact: true }).click();
const section = (name: string) => settings.getByRole("region", { name, exact: true });
await expect(section("Caret").getByRole("checkbox", { name: "Use block caret" })).toBeVisible();
await expect(section("Code Structure").getByRole("checkbox", { name: "Show line numbers" })).toBeVisible();
await expect(section("Code Assistance").getByRole("checkbox", { name: "Show intention bulb" })).toBeVisible();
const presentation = section("Presentation");
await expect(presentation.getByRole("checkbox", { name: "Render documentation comments" })).toBeVisible();
await expect(presentation.getByRole("textbox", { name: "Distraction free mode text width:" })).toBeVisible();
const whitespace = presentation.getByRole("checkbox", { name: "Show whitespaces" });
const leading = presentation.getByRole("checkbox", { name: "Leading", exact: true });
if (await whitespace.isChecked()) await whitespace.uncheck();
await expect(leading).toBeDisabled();
await whitespace.check();
await expect(leading).toBeEnabled();
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(settings).toBeHidden();
});
test("Language Servers page installs a tool with progress (in-memory installer)", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings" });
Бінарний файл не відображається.
+26 -1
Переглянути файл
@@ -120,6 +120,17 @@ public final class OpenIdeaJdbc {
n++;
}
}
} else if (op.equals("schemaColumns")) {
// Every column of the namespace in one call (SQL completion), without primary keys.
header(out, "table", "name", "type", "nullable", "default");
try (ResultSet rs = m.getColumns(catalog, schema, "%", "%")) {
int n = 0;
while (rs.next() && n < 100000) {
row(out, rs.getString("TABLE_NAME"), rs.getString("COLUMN_NAME"), rs.getString("TYPE_NAME"),
rs.getInt("NULLABLE") == 0 ? "0" : "1", rs.getString("COLUMN_DEF"));
n++;
}
}
} else {
header(out, "name", "type", "nullable", "default", "primary");
String table = a.get(1);
@@ -233,7 +244,7 @@ public final class OpenIdeaJdbc {
switch (op) {
case "open" -> open(a, reply);
case "schemas" -> schemas(reply);
case "tables", "columns" -> metadata(op, a, reply);
case "tables", "columns", "schemaColumns" -> metadata(op, a, reply);
case "namespace" -> {
header(reply, "namespace");
String name = null;
@@ -243,6 +254,20 @@ public final class OpenIdeaJdbc {
} catch (SQLException | AbstractMethodError ignored) {}
row(reply, name);
}
case "valid" -> {
// After a failed statement: whether the session survived (a dropped TCP
// connection leaves every later statement failing until the IDE reconnects).
header(reply, "valid");
boolean valid;
try {
valid = connection != null && !connection.isClosed() && connection.isValid(5);
} catch (AbstractMethodError | SQLFeatureNotSupportedException e) {
valid = true; // A pre-JDBC 4 driver cannot tell: keep the session.
} catch (SQLException e) {
valid = false;
}
row(reply, Boolean.toString(valid));
}
case "page" -> execute(work, a, reply, true);
case "query" -> {
if (a.size() == 3 || a.get(3).isEmpty()) {
+32
Переглянути файл
@@ -14,6 +14,7 @@ import java.util.logging.Logger;
public class SelfTest {
public static class Fixture implements Driver {
private boolean readonly;
private boolean dropped;
private int changes;
private Path started;
@@ -29,6 +30,12 @@ public class SelfTest {
case "getDatabaseProductName" -> "Fixture";
case "getDatabaseProductVersion" -> "1";
case "getIdentifierQuoteString" -> "\"";
case "getSearchStringEscape" -> "\\";
case "getSchemas" -> rows(List.of(Map.of("TABLE_SCHEM", "app")));
case "getColumns" -> "app".equals(a[1]) && "%".equals(a[2]) ? rows(List.of(
Map.of("TABLE_NAME", "orders", "COLUMN_NAME", "id", "TYPE_NAME", "INT", "NULLABLE", 0),
Map.of("TABLE_NAME", "orders", "COLUMN_NAME", "note", "TYPE_NAME", "VARCHAR", "NULLABLE", 1,
"COLUMN_DEF", "'none'"))) : rows(List.of());
default -> throw new SQLFeatureNotSupportedException();
});
return proxy(Connection.class, (p, m, a) -> switch (m.getName()) {
@@ -36,6 +43,21 @@ public class SelfTest {
case "getMetaData" -> meta;
case "close" -> null;
case "createStatement" -> statement();
case "isClosed" -> false;
case "isValid" -> !dropped;
case "getCatalog" -> null;
default -> throw new SQLFeatureNotSupportedException();
});
}
/** A forward-only result set over `data`, read by column label. */
static ResultSet rows(List<Map<String, Object>> data) {
int[] at = {-1};
return proxy(ResultSet.class, (p, m, a) -> switch (m.getName()) {
case "next" -> ++at[0] < data.size();
case "getString" -> (String) data.get(at[0]).get((String) a[0]);
case "getInt" -> (Integer) data.get(at[0]).getOrDefault((String) a[0], 0);
case "close" -> null;
default -> throw new SQLFeatureNotSupportedException();
});
}
@@ -53,6 +75,7 @@ public class SelfTest {
throw new SQLException("statement cancelled");
}
if (sql.equals("write") && readonly) throw new SQLException("read-only");
if (sql.equals("drop")) { dropped = true; throw new SQLException("connection reset"); }
changes++;
yield false;
}
@@ -122,6 +145,15 @@ public class SelfTest {
send(out, 5, "query", "after cancel", "0", "2");
var result = reply(in);
assert result[0] == 1 && result[result.length - 1] == 2;
send(out, 6, "valid");
assert new String(reply(in), StandardCharsets.UTF_8).contains("true");
send(out, 7, "query", "drop", "0", "2");
assert reply(in)[0] == 0;
send(out, 8, "valid");
assert new String(reply(in), StandardCharsets.UTF_8).contains("false");
send(out, 9, "schemaColumns", "app");
var columns = new String(reply(in), StandardCharsets.UTF_8);
assert columns.contains("orders") && columns.contains("note") && columns.contains("'none'") : columns;
} finally {
child.destroyForcibly().waitFor();
}
+2
Переглянути файл
@@ -3770,6 +3770,8 @@ export type CommitSettings = {
agentModel?: string,
/** That model's thinking level for commit messages; empty keeps the agent's. */
agentEffort?: string,
/** Show the Generate Commit Message with Agent button above the commit message. */
agentButton?: boolean,
};
export type Commit_Deserialize = {
+49 -2
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { Compartment, EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
import { codeLenses } from "@/editor/api";
import { codeLensExtension, codeLensPositions, declarationStart, groupLenses, indentColumns } from "./codeLens";
@@ -95,3 +95,50 @@ describe("code lens position", () => {
v.destroy();
});
});
describe("inline lens against a folded chip", () => {
const doc = "def f():\n pass\n";
const lenses = [{ pos: 8, title: "1 usage", kind: "usages", order: 10 }];
class FakeChip extends WidgetType {
toDOM() {
const el = document.createElement("span");
el.className = "cm-foldPlaceholder";
el.getBoundingClientRect = () => ({ width: 18 }) as DOMRect;
return el;
}
override eq(other: WidgetType) {
return other instanceof FakeChip;
}
}
it("steps past a folded chip drawn after its anchor and back when it goes away", async () => {
vi.useFakeTimers();
const chip = new Compartment();
const chipDeco = () =>
EditorView.decorations.of(Decoration.set([Decoration.widget({ widget: new FakeChip(), side: 3 }).range(8)]));
const v = new EditorView({
state: EditorState.create({
doc,
extensions: [codeLensExtension, codeLenses.of(lenses), codeLensPositions.of({ usages: "right" }), chip.of([])],
}),
parent: document.body,
});
const inline = v.dom.querySelector<HTMLElement>(".cm-openidea-lensInline")!;
const inner = inline.firstElementChild as HTMLElement;
await vi.advanceTimersByTimeAsync(10);
expect(inner.style.left).toBe("");
// The fold appears after the lens mounted; side 3 mirrors the production DOM order, where
// CodeMirror draws the fold's replace widget after the side-1 line-end anchor.
v.dispatch({ effects: chip.reconfigure(chipDeco()) });
await vi.advanceTimersByTimeAsync(10);
expect(inner.style.left).toBe("calc(var(--openidea-hint-offset) + 18px)");
v.dispatch({ effects: chip.reconfigure([]) });
await vi.advanceTimersByTimeAsync(10);
expect(inner.style.left).toBe("");
v.destroy();
vi.useRealTimers();
});
});
+34
Переглянути файл
@@ -7,6 +7,7 @@
import { EditorState, Facet, RangeSetBuilder, type Extension } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view";
import { codeLenses, type CodeLens } from "@/editor/api";
import { foldChipWidth } from "./folding";
import { showContextMenu } from "@/ui";
import { codeVisionMenuItems } from "../codeVision";
import { LINE_INSET } from "./lineInset";
@@ -99,6 +100,21 @@ class LensWidget extends WidgetType {
return this.key === other.key && this.lenses.every((l, i) => l.run === other.lenses[i]?.run);
}
/** The box parks a fixed offset past its zero-width anchor; a folded chip drawn after the
anchor paints under the box, so the box also steps past the chip's width (folding.ts). */
private stepPastFoldChip(el: HTMLElement) {
const inner = this.inline ? (el.firstElementChild as HTMLElement | null) : el;
if (!inner) return;
const chip = foldChipWidth(el);
if (chip === this.appliedChip) return;
this.appliedChip = chip;
if (chip) inner.style.left = `calc(var(--openidea-hint-offset) + ${chip}px)`;
else inner.style.removeProperty("left");
}
private appliedChip = -1;
private observer: MutationObserver | undefined;
override toDOM(view: EditorView): HTMLElement {
// The inline one shares no class with the row, so none of the row's block styles reach into the line.
const dom: HTMLElement = document.createElement(this.inline ? "span" : "div");
@@ -111,6 +127,18 @@ class LensWidget extends WidgetType {
dom.appendChild(host);
}
this.fill(host, view);
if (this.inline) {
// The chip can appear (or go away) after this widget mounted, hence the observer; the
// element is only measurable once CodeMirror has inserted it, so defer like the blame does.
setTimeout(() => {
if (!dom.isConnected) return;
this.stepPastFoldChip(dom);
const line = dom.closest(".cm-line");
if (!line) return;
this.observer = new MutationObserver(() => this.stepPastFoldChip(dom));
this.observer.observe(line, { childList: true, subtree: true, characterData: true });
}, 0);
}
dom.addEventListener("contextmenu", (e) => {
e.preventDefault();
e.stopPropagation();
@@ -126,6 +154,7 @@ class LensWidget extends WidgetType {
const host = this.inline ? (dom.firstElementChild as HTMLElement | null) : dom;
if (!host) return false;
this.fill(host, view);
if (this.inline) this.stepPastFoldChip(dom);
return true;
}
@@ -174,6 +203,11 @@ class LensWidget extends WidgetType {
return this.inline ? -1 : 16;
}
override destroy(): void {
this.observer?.disconnect();
this.observer = undefined;
}
override ignoreEvent(): boolean {
return true;
}
+39
Переглянути файл
@@ -8,6 +8,7 @@ import {
backendFolds,
enclosingFoldRange,
expandToLevelEffects,
foldChipWidth,
foldSelectionEffects,
foldsFromRanges,
foldingExtension,
@@ -420,3 +421,41 @@ describe("comment placeholders", () => {
view.destroy();
});
});
describe("foldChipWidth", () => {
function editor(doc: string) {
return new EditorView({
state: EditorState.create({ doc, extensions: [foldingExtension()] }),
parent: document.body,
});
}
it("measures a folded chip drawn after the anchor", () => {
const view = editor("const a = 1\nconst b = 2");
view.dispatch({ effects: foldEffect.of({ from: view.state.doc.line(1).to, to: view.state.doc.line(2).to }) });
// jsdom has no layout: the chip's width is faked like the blame tests' hint boxes.
const chip = view.dom.querySelector(".cm-foldPlaceholder")!;
chip.getBoundingClientRect = () => ({ width: 18 }) as DOMRect;
// Production order: the zero-width anchor sits at the fold start, the chip after it.
const anchor = document.createElement("span");
chip.before(anchor);
expect(foldChipWidth(anchor)).toBe(18);
view.destroy();
});
it("is zero with no chip on the line, or when the chip precedes the anchor", () => {
const view = editor("const a = 1\nconst b = 2");
const other = document.createElement("span");
view.dom.querySelectorAll(".cm-line")[1]!.append(other);
expect(foldChipWidth(other)).toBe(0);
view.dispatch({ effects: foldEffect.of({ from: view.state.doc.line(1).to, to: view.state.doc.line(2).to }) });
// A chip earlier in the line (mid-line import folds) cannot overlap a later anchor;
// passing the chip itself as the anchor (nothing precedes itself) is also 0.
const chip = view.dom.querySelector(".cm-foldPlaceholder")!;
chip.getBoundingClientRect = () => ({ width: 18 }) as DOMRect;
const anchor = document.createElement("span");
chip.after(anchor);
expect(foldChipWidth(anchor)).toBe(0);
view.destroy();
});
});
+14
Переглянути файл
@@ -463,6 +463,20 @@ export function backendFoldingChanged(update: ViewUpdate): boolean {
return update.startState.field(backendFolds, false) !== update.state.field(backendFolds, false);
}
/**
* The folded chip is an in-flow widget drawn at the fold start, which for header-line folds is
* the same position as the zero-width anchors of the line-end annotations (`codeLens.ts`, inline
* blame, plugin messages). Their absolutely positioned boxes park a fixed offset past those
* anchors, so a chip drawn after them paints under (over) the hint. Each consumer measures the
* chip and steps past it, but only when the chip follows its anchor in the DOM — a chip earlier
* in the line (mid-line import folds) already sits before the anchor and cannot overlap.
*/
export function foldChipWidth(el: HTMLElement): number {
const chip = el.closest(".cm-line")?.querySelector(".cm-foldPlaceholder");
if (!chip || !(el.compareDocumentPosition(chip) & Node.DOCUMENT_POSITION_FOLLOWING)) return 0;
return Math.round(chip.getBoundingClientRect().width);
}
export function foldingExtension(showOutline = true): Extension {
return [
// The chevron column sits right of contributed icon gutters (IDEA new UI).
+12 -3
Переглянути файл
@@ -276,14 +276,23 @@ export const openideaTheme = EditorView.theme({
},
".cm-openidea-laneDeleted": {
position: "absolute",
left: "0",
top: "-3px",
left: "-4px",
top: "-6px",
width: "12px",
height: "12px",
cursor: "pointer",
zIndex: "1",
},
".cm-openidea-laneDeleted::after": {
content: '""',
position: "absolute",
left: "4px",
top: "3px",
width: "0",
height: "0",
borderTop: "3px solid transparent",
borderBottom: "3px solid transparent",
borderLeft: "6px solid var(--lane-color)",
zIndex: "1",
},
".cm-foldGutter": { width: "16px" },
".cm-foldGutter .cm-gutterElement": {
+33 -5
Переглянути файл
@@ -11,15 +11,37 @@
.body {
display: flex;
flex-direction: column;
gap: var(--space-2);
flex: 1;
min-height: 0;
padding: var(--space-3);
}
.split {
flex: 1;
}
.history {
display: flex;
flex-direction: column;
gap: var(--space-1);
height: 100%;
min-height: 0;
padding-bottom: var(--space-2);
}
.toolbar {
display: flex;
flex: none;
align-items: center;
gap: var(--space-2);
}
.filter {
flex: 1;
}
.list {
flex: 2;
min-height: 84px;
flex: 1;
}
.label {
@@ -27,7 +49,9 @@
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
font-family: var(--font-mono);
font-family: var(--paste-history-font-family, var(--font-mono));
font-size: var(--paste-history-font-size, var(--fs-code));
font-weight: var(--paste-history-font-weight, normal);
}
.detail {
@@ -36,8 +60,12 @@
font-size: var(--fs-small);
}
.previewPanel {
padding-top: var(--space-2);
}
.preview {
flex: 3;
height: 100%;
min-height: 0;
overflow: hidden;
border: 1px solid var(--border-strong);
+65 -40
Переглянути файл
@@ -1,7 +1,7 @@
import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
import { create } from "zustand";
import { EditorState } from "@codemirror/state";
import { EditorView, highlightSpecialChars, lineNumbers } from "@codemirror/view";
import { EditorView, highlightSpecialChars } from "@codemirror/view";
import { language, syntaxHighlighting } from "@codemirror/language";
import { tx } from "@/platform/i18n";
import { isImeKey } from "@/platform/ime";
@@ -9,11 +9,14 @@ import { executeAction, registerActions } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { bindingsFor, normalizeBinding, strokeOf } from "@/platform/keymap";
import {
Button,
Dialog,
IconButton,
List,
SearchField,
SINGLE_FIRST,
SplitGroup,
SplitHandle,
SplitPanel,
T,
isRowSelected,
listNavigate,
@@ -22,9 +25,11 @@ import {
selectableText,
selectedRows,
} from "@/ui";
import { useRowHeight } from "@/ui/density";
import { clipLabel, clipboardHistory, removeClipboardEntries } from "../clipboardHistory";
import { openideaHighlightStyle } from "../cm/highlight";
import { compartments } from "../cm/setup";
import { fontZoom } from "../cm/prefs";
import { openideaTheme } from "../cm/theme";
import styles from "./PasteHistoryDialog.module.css";
@@ -82,6 +87,11 @@ function PasteHistoryDialog({ view, paste, onClose }: Request & { onClose: () =>
const [entries, setEntries] = useState(clipboardHistory);
const [query, setQuery] = useState("");
const [selection, setSelection] = useState(SINGLE_FIRST);
const [editorFont] = useState(() => {
const { fontFamily, fontSize, fontWeight } = getComputedStyle(view.contentDOM);
return { fontFamily, fontSize, fontWeight };
});
const rowHeight = Math.max(useRowHeight(), Math.ceil(Number.parseFloat(editorFont.fontSize) || 0) + 8);
const search = useRef<HTMLInputElement>(null);
const rows = entries
.filter(({ text }) => text.toLocaleLowerCase().includes(query.toLocaleLowerCase()))
@@ -156,7 +166,7 @@ function PasteHistoryDialog({ view, paste, onClose }: Request & { onClose: () =>
title="Choose Content to Paste"
onClose={onClose}
className={styles.dialog}
width={680}
width={560}
resizable="both"
minWidth={360}
minHeight={320}
@@ -169,48 +179,63 @@ function PasteHistoryDialog({ view, paste, onClose }: Request & { onClose: () =>
},
{ label: "Cancel", role: "cancel" },
]}
footerStart={
<Button disabled={!selected.length} onClick={runRemove}>
<T>Delete</T>
</Button>
}
>
<div
className={styles.body}
style={
{
"--paste-history-font-family": editorFont.fontFamily,
"--paste-history-font-size": editorFont.fontSize,
"--paste-history-font-weight": editorFont.fontWeight,
} as CSSProperties
}
onKeyDown={onKeyDown}
onFocusCapture={(e) => setContext("pasteHistoryListFocus", !!e.target.closest('[role="listbox"]'))}
onBlurCapture={() => setContext("pasteHistoryListFocus", false)}
>
<SearchField
ref={search}
data-autofocus=""
aria-label="Filter clipboard history"
placeholder="Filter clipboard history"
value={query}
onChange={filter}
/>
<List
items={rows}
getKey={(row) => row.key}
activeIndex={selection.lead}
onSelect={(index, e) => setSelection(selectRow(rows, selection, index, rowSelectionMode(e)))}
isSelected={(row) => isRowSelected(selection, row.key)}
onActivate={(row, _index, e) => {
if (e.type === "keydown") runPaste();
else if (e.detail === 2) runPaste(row.key);
}}
rowHeight={28}
className={styles.list}
aria-label={tx("Clipboard history")}
empty={<T>{entries.length ? "No matches" : "Nothing to paste: the clipboard history is empty"}</T>}
renderItem={(row) => (
<>
<span className={styles.label}>{row.label}</span>
<span className={styles.detail}>{row.detail ?? tx("1 line")}</span>
</>
)}
/>
<PastePreview source={view} text={preview} />
<SplitGroup orientation="vertical" storageKey="openidea.editor.pasteHistory" className={styles.split}>
<SplitPanel id="clipboard" defaultSize="30%" minSize="96px">
<div className={styles.history}>
<div className={styles.toolbar}>
<IconButton icon="minus" size="small" title="Delete" disabled={!selected.length} onClick={runRemove} />
<SearchField
ref={search}
className={styles.filter}
data-autofocus=""
aria-label="Filter clipboard history"
placeholder="Filter clipboard history"
value={query}
onChange={filter}
/>
</div>
<List
items={rows}
getKey={(row) => row.key}
activeIndex={selection.lead}
onSelect={(index, e) => setSelection(selectRow(rows, selection, index, rowSelectionMode(e)))}
isSelected={(row) => isRowSelected(selection, row.key)}
onActivate={(row, _index, e) => {
if (e.type === "keydown") runPaste();
else if (e.detail === 2) runPaste(row.key);
}}
rowHeight={rowHeight}
className={styles.list}
aria-label={tx("Clipboard history")}
empty={<T>{entries.length ? "No matches" : "Nothing to paste: the clipboard history is empty"}</T>}
renderItem={(row) => (
<>
<span className={styles.label}>{row.label}</span>
<span className={styles.detail}>{row.detail ?? tx("1 line")}</span>
</>
)}
/>
</div>
</SplitPanel>
<SplitHandle aria-label={tx("Resize paste preview")} />
<SplitPanel id="preview" defaultSize="70%" minSize="100px" className={styles.previewPanel}>
<PastePreview source={view} text={preview} />
</SplitPanel>
</SplitGroup>
</div>
</Dialog>
);
@@ -228,11 +253,11 @@ function PastePreview({ source, text }: { source: EditorView; text: string }) {
syntaxHighlighting(openideaHighlightStyle),
source.state.facet(language)?.extension ?? [],
compartments.font.get(source.state) ?? [],
fontZoom.init(() => source.state.field(fontZoom, false) ?? 0),
EditorState.tabSize.of(source.state.tabSize),
EditorState.readOnly.of(true),
EditorView.editable.of(false),
EditorView.contentAttributes.of({ "aria-label": tx("Paste preview"), class: selectableText, tabindex: "0" }),
lineNumbers(),
highlightSpecialChars(),
],
}),
+8 -3
Переглянути файл
@@ -2,8 +2,9 @@
* The documentation view with its history toolbar, as IDEA's one documentation
* component: the F1 popup, the hover and the Documentation tool window show it.
*/
import { useEffect, useRef, type KeyboardEvent } from "react";
import { useLayoutEffect, useRef, type KeyboardEvent } from "react";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import clsx from "clsx";
import { useStore } from "zustand";
import { IconButton, selectableText } from "@/ui";
@@ -23,7 +24,9 @@ import styles from "./Popups.module.css";
export function DomContent({ build, className }: { build: () => HTMLElement; className?: string }) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
// Build the body before paint: the popup is measured as soon as it is created, so an empty first
// frame would be placed and then moved once the text appeared.
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
const node = build();
@@ -113,6 +116,8 @@ function HoverDocView({ doc }: { doc: HoverDoc }) {
/** Mounts a hover's documentation into its CodeMirror tooltip; returns its unmount. */
export function mountHoverDoc(el: HTMLElement, doc: HoverDoc): () => void {
const root = createRoot(el);
root.render(<HoverDocView doc={doc} />);
// Render before returning: CodeMirror measures the tooltip right after `create()`, so a popup
// that is still empty at that point is placed a second time when the text arrives.
flushSync(() => root.render(<HoverDocView doc={doc} />));
return () => queueMicrotask(() => root.unmount());
}
+6 -4
Переглянути файл
@@ -261,7 +261,7 @@ describe("hover documentation", () => {
const frame = (el: Element) => el.querySelector<HTMLElement>('[data-lsp-doc="hover"]')!;
afterEach(() => document.body.replaceChildren());
it("shows the hovered documentation in the same view as F1's", async () => {
it("shows the hovered documentation in the same view as F1's, laid out when create() returns", async () => {
const docHover: ContributedHover = (state, pos) => {
const w = state.wordAt(pos);
return w ? { from: w.from, to: w.to, markdown: "hovered docs" } : null;
@@ -275,11 +275,13 @@ describe("hover documentation", () => {
});
const tooltip = await hoverSource(view, 2);
let created!: { dom: HTMLElement; destroy: () => void };
await act(async () => {
// Asserted inside a synchronous act(): `create()` has to leave a laid-out popup behind, since
// CodeMirror places the tooltip in the measure pass that follows it.
act(() => {
created = tooltip!.create() as typeof created;
document.body.appendChild(created.dom);
expect(frame(created.dom).textContent).toContain("hovered docs");
});
expect(frame(created.dom).textContent).toContain("hovered docs");
await act(async () => void document.body.appendChild(created.dom));
expect(screen.getByRole("button", { name: "Back" })).toBeTruthy();
created.destroy();
view.destroy();
+46 -20
Переглянути файл
@@ -113,10 +113,18 @@
.spacer {
flex: 1;
}
.configPicker {
.configPicker,
.modelControl {
display: flex;
min-width: 0;
}
.modelControl {
align-items: center;
}
.modelDetail {
box-shadow: inset 1px 0 var(--border);
color: var(--fg-muted);
}
.configPicker > button {
max-width: 100%;
}
@@ -219,37 +227,39 @@
color: var(--fg-muted);
cursor: default;
}
/* The model popup's top: effort (and context size) as segmented controls. */
.quickSettings {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
padding: 4px 10px 10px;
margin-bottom: 4px;
border-bottom: 1px solid var(--border);
gap: var(--space-3);
padding: 4px 12px 10px;
}
.quickRow {
.modelSettingsHeader {
display: flex;
align-items: center;
gap: var(--space-2);
}
.quickRow > .segmented {
flex: 1;
min-width: 0;
.modelSettingsHeader strong {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.quickRow {
display: flex;
flex-direction: column;
gap: var(--space-1);
}
.quickLabel {
flex: none;
width: 72px;
color: var(--fg-muted);
color: var(--fg-secondary);
font-size: var(--fs-small);
font-weight: 600;
}
/* A model's configure button shows on its row's hover only. */
.modelEffortPopup [role="option"] .modelRowConfigure {
opacity: 0;
}
.modelEffortPopup [role="option"]:hover .modelRowConfigure,
.modelEffortPopup [role="option"][aria-selected="true"] .modelRowConfigure,
.modelEffortPopup .modelRowConfigure:focus-visible {
.modelEffortPopup [role="option"]:focus-within .modelRowConfigure,
.modelEffortPopup [role="option"] .currentRowSettings {
opacity: 1;
}
.modelRowConfigure {
@@ -264,6 +274,23 @@
color: var(--fg-muted);
cursor: pointer;
}
.modelRowSettings {
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
width: auto;
max-width: 120px;
padding-inline: 4px;
font-size: var(--fs-small);
}
.modelRowSettings span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.modelRowSettings svg {
flex: none;
}
.modelRowConfigure:hover,
.modelRowConfigure:focus-visible {
outline: none;
@@ -326,7 +353,7 @@
outline-offset: -2px;
}
.segmentActive {
background: var(--bg-floating-toolbar);
background: var(--bg-toolbar-hover);
color: var(--fg-strong);
font-weight: 600;
}
@@ -401,13 +428,12 @@
text-overflow: ellipsis;
white-space: nowrap;
}
/* Details give way to the names, except the model's effort and context: the model's
name truncates first, since they are only shown here. */
.chipDetail:not(.modelDetail) {
.chipDetail {
display: none;
}
.modelDetail {
flex: none;
flex-shrink: 0;
max-width: 65%;
}
.inlineSetting {
display: none;
+13 -13
Переглянути файл
@@ -340,10 +340,10 @@ describe("model settings", () => {
render(<ConfigPickers config={copilotConfig()} onChange={onChange} />);
const model = screen.getByRole("button", { name: "Model" });
expect(model).toHaveTextContent("Claude Sonnet 5.5");
expect(model).toHaveTextContent("medium");
const settings = screen.getByRole("button", { name: "Model settings: medium" });
expect(screen.getByRole("button", { name: "Mode" })).toHaveTextContent("AgentAllow All");
fireEvent.click(model);
const dialog = screen.getByRole("dialog", { name: "Model" });
fireEvent.click(settings);
const dialog = screen.getByRole("dialog", { name: "Model settings" });
const effort = within(dialog).getByRole("radiogroup", { name: "Effort Level" });
expect(within(effort).getByRole("radio", { name: "medium" })).toHaveAttribute("aria-checked", "true");
fireEvent.click(within(effort).getByRole("radio", { name: "XHigh" }));
@@ -364,10 +364,8 @@ describe("model settings", () => {
: o,
);
render(<ConfigPickers config={config} onChange={onChange} />);
const model = screen.getByRole("button", { name: "Model" });
expect(model).toHaveTextContent("Max");
fireEvent.click(model);
const dialog = screen.getByRole("dialog", { name: "Model" });
fireEvent.click(screen.getByRole("button", { name: "Model settings: Max" }));
const dialog = screen.getByRole("dialog", { name: "Model settings" });
expect(within(dialog).queryByRole("radiogroup", { name: "Effort Level" })).not.toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("button", { name: /Reasoning Effort/ }));
fireEvent.click(screen.getByRole("option", { name: /Extra high/ }));
@@ -389,12 +387,12 @@ describe("model settings", () => {
];
render(<ConfigPickers config={config} onChange={vi.fn()} />);
expect(screen.queryByRole("switch", { name: "Fast" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Model" }));
const dialog = screen.getByRole("dialog", { name: "Model" });
fireEvent.click(screen.getByRole("button", { name: "Model settings: Fast: Off" }));
const dialog = screen.getByRole("dialog", { name: "Model settings" });
expect(within(dialog).getByRole("switch", { name: "Fast" })).toHaveAttribute("aria-checked", "false");
});
it("lists models by name in one page, with context size, cost and pinning", () => {
it("opens settings from the selected row without choosing it and returns to a pinnable model list", () => {
const onChange = vi.fn();
const cfg = copilotConfig().map((o) =>
o.id === "model"
@@ -419,14 +417,15 @@ describe("model settings", () => {
render(<ConfigPickers config={cfg} onChange={onChange} />);
const model = screen.getByRole("button", { name: "Model" });
expect(model).toHaveTextContent("Claude Sonnet 5.5");
expect(model).toHaveTextContent("medium");
expect(model).toHaveTextContent("1M");
expect(model).toHaveAttribute("title", expect.stringContaining("Effort Level: medium · Context Size: 1M"));
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("medium · 1M");
fireEvent.click(model);
const dialog = screen.getByRole("dialog", { name: "Model" });
expect(within(dialog).queryByText("Balanced")).not.toBeInTheDocument();
expect(within(dialog).getByText("Medium cost")).toBeVisible();
expect(within(dialog).queryByRole("radio")).not.toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("button", { name: "Configure Claude Sonnet 5.5…" }));
expect(onChange).not.toHaveBeenCalled();
const effortGroup = within(dialog).getByRole("radiogroup", { name: "Effort Level" });
expect(within(effortGroup).getByRole("radio", { name: "medium" })).toHaveAttribute("aria-checked", "true");
@@ -435,6 +434,7 @@ describe("model settings", () => {
fireEvent.click(within(contextGroup).getByRole("radio", { name: "200K" }));
expect(onChange).toHaveBeenCalledWith("contextTier", "default");
fireEvent.click(within(dialog).getByRole("button", { name: "Back to models" }));
fireEvent.click(within(dialog).getAllByRole("button", { name: "Pin model" })[0]!);
const listbox = within(dialog).getByRole("listbox", { name: "Model" });
expect(within(listbox).getByText("Pinned")).toBeVisible();
+217 -138
Переглянути файл
@@ -1,7 +1,5 @@
/**
* Model, effort, mode and approvals controls for a composer's bottom row. The model button
* opens a searchable model list (pinned models first) and keeps effort and context settings
* together above it.
* Model and settings controls shared by the New Task and session composers.
*/
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
@@ -78,6 +76,8 @@ function switchValues(option: AgentConfigOption): { on: string; off: string } |
const selected = (option: AgentConfigOption, value: string | null) =>
option.values.find((v) => v.value === value) ?? null;
type ChangeOption = (option: string, value: string, forModel?: string) => void;
interface ModelRefresh {
draft?: boolean;
refreshing: boolean;
@@ -86,6 +86,12 @@ interface ModelRefresh {
error: string | null;
onOpen?: () => void;
onRefresh: () => void;
preview?: {
/** Undefined until discovery; an empty array means the agent reported no settings. */
settingsFor: (model: string) => AgentConfigOption[] | undefined;
load: (model: string) => void;
errorFor: (model: string) => string | null | undefined;
};
}
export function ConfigPickers({
@@ -97,7 +103,7 @@ export function ConfigPickers({
config: readonly AgentConfigOption[];
/** Chosen values that override `current`, by option id. */
values?: Record<string, string>;
onChange: (option: string, value: string) => void;
onChange: ChangeOption;
modelRefresh?: ModelRefresh;
}) {
const tx = useTx();
@@ -145,10 +151,9 @@ export function ConfigPickers({
<ModelPicker
model={o}
modelValue={valueOf(o)}
modelConfigs={modelConfigs}
effort={tuckedEffort}
effortValue={tuckedEffort ? valueOf(tuckedEffort) : null}
valueOf={valueOf}
settings={(tuckedEffort ? [tuckedEffort, ...modelConfigs] : modelConfigs)
.filter((opt) => opt.values.length > 0)
.map((opt) => ({ ...opt, current: valueOf(opt) }))}
onChange={onChange}
modelRefresh={modelRefresh}
/>
@@ -257,181 +262,255 @@ function ConfigPicker({
}
/** Effort levels that fit the popup's segmented control; more (Codex has six) get a dropdown. */
const SEGMENTED_EFFORT_MAX = 4;
const SEGMENTED_EFFORT_MAX = 5;
function settingName(option: AgentConfigOption) {
return option.category === "thought_level"
? "Effort Level"
: isContextOption(option.id)
? "Context Size"
: option.name;
}
function settingValue(option: AgentConfigOption) {
return selected(option, option.current) ?? option.values[0];
}
function settingsSummary(options: AgentConfigOption[], tx: ReturnType<typeof useTx>) {
return options
.map((o) => {
const label = settingValue(o)?.name ?? tx("Default");
return o.category === "thought_level" || isContextOption(o.id) ? label : `${tx(o.name)}: ${label}`;
})
.join(" · ");
}
/** The model button: a searchable model list, with effort, context size and model settings above it. */
function ModelPicker({
model,
modelValue,
modelConfigs,
effort,
effortValue,
valueOf,
settings,
onChange,
modelRefresh,
}: {
model: AgentConfigOption;
modelValue: string | null;
modelConfigs: AgentConfigOption[];
effort: AgentConfigOption | null;
effortValue: string | null;
valueOf: (o: AgentConfigOption) => string | null;
onChange: (option: string, value: string) => void;
settings: AgentConfigOption[];
onChange: ChangeOption;
modelRefresh?: ModelRefresh;
}) {
const tx = useTx();
const [open, setOpen] = useState(false);
const [page, setPage] = useState<"models" | { model: string | null } | null>(null);
const pinnedModels = useAgents((s) => s.pinnedModels);
const anchor = useRef<HTMLButtonElement>(null);
const anchor = useRef<HTMLSpanElement>(null);
const selectedModel = selected(model, modelValue);
const unavailable = !!modelRefresh && modelValue !== null && !selectedModel;
const modelName = unavailable
? tx`${modelValue} (unavailable)`
: (selectedModel?.name ?? (modelRefresh ? modelValue : null) ?? tx("Default"));
const contextOption = modelConfigs.find((o) => isContextOption(o.id) && o.values.length > 0);
const contextValue = contextOption ? valueOf(contextOption) : null;
const contextLabel = contextOption
? ((selected(contextOption, contextValue) ?? contextOption.values[0])?.name ?? null)
: null;
const effortLabel = effort ? ((selected(effort, effortValue) ?? effort.values[0])?.name ?? null) : null;
const otherModelConfigs = modelConfigs.filter((o) => o !== contextOption);
const summary = [
effortLabel ? `${tx("Effort Level")}: ${effortLabel}` : null,
contextLabel ? `${tx("Context Size")}: ${contextLabel}` : null,
...otherModelConfigs.map((o) => {
const current = selected(o, valueOf(o));
return current ? `${tx(o.name)}: ${current.name}` : null;
}),
]
.filter(Boolean)
.join(" · ");
const summary = settingsSummary(settings, tx);
const settingsFor = (id: string | null) =>
id === modelValue ? settings : id ? modelRefresh?.preview?.settingsFor(id) : undefined;
const details = page && page !== "models" && (page.model === modelValue || selected(model, page.model)) ? page : null;
const inspectedModel = details ? selected(model, details.model) : null;
const openModels = () => {
modelRefresh?.onOpen?.();
setPage("models");
};
return (
<>
<span ref={anchor} className={styles.modelControl}>
<button
ref={anchor}
type="button"
className={styles.chip}
aria-label={tx(model.name)}
aria-haspopup="dialog"
aria-expanded={open}
title={`${tx(model.name)}: ${modelName}${summary ? ` · ${summary}` : ""}`}
onClick={() => {
if (!open) modelRefresh?.onOpen?.();
setOpen(!open);
}}
aria-expanded={!!page && !details}
title={`${tx(model.name)}: ${modelName}`}
onClick={() => (page && !details ? setPage(null) : openModels())}
>
<span className={styles.chipValue}>{modelName}</span>
{(effortLabel || contextLabel) && (
<span className={clsx(styles.chipDetail, styles.modelDetail)}>
{[effortLabel, contextLabel].filter(Boolean).join(" · ")}
</span>
)}
<Icon name="chevron-down" size={14} className={styles.chipChevron} />
</button>
{summary && !unavailable && (
<button
type="button"
className={clsx(styles.chip, styles.modelDetail)}
aria-label={tx`Model settings: ${summary}`}
title={tx`Configure ${modelName}…`}
aria-haspopup="dialog"
aria-expanded={!!details && details.model === modelValue}
onClick={() => setPage(details && details.model === modelValue ? null : { model: modelValue })}
>
<span className={styles.chipValue}>{summary}</span>
</button>
)}
<Popup
open={open}
open={!!page}
anchor={anchor}
onClose={() => setOpen(false)}
aria-label={tx("Model")}
onClose={() => setPage(null)}
aria-label={tx(details ? "Model settings" : "Model")}
className={styles.modelEffortPopup}
>
{unavailable && (
<p className={styles.catalogError} role="alert">
<T>Choose another model before starting.</T>
</p>
{details ? (
<ModelSettings
key={details.model}
id={details.model}
name={inspectedModel?.name ?? modelName}
settings={settingsFor(details.model)}
modelRefresh={modelRefresh}
onBack={openModels}
onChange={(option, value) => {
if (details.model && details.model !== modelValue) onChange(option, value, details.model);
else onChange(option, value);
}}
/>
) : (
<>
{unavailable && (
<p className={styles.catalogError} role="alert">
<T>Choose another model before starting.</T>
</p>
)}
{model.values.length > 0 || !modelRefresh ? (
<SelectListbox
aria-label={tx(model.name)}
value={modelValue}
options={configPickerOptions(model, pinnedModels, false)}
searchable
listClassName={styles.modelList}
onChoose={(v) => {
onChange(model.id, v);
setPage(null);
}}
renderAction={(opt) => {
const raw = model.values.find((v) => v.value === opt.value);
if (!raw) return null;
const pinned = pinnedModels.includes(raw.value);
const rowSettings = settingsFor(raw.value);
const configurable = rowSettings
? rowSettings.some((o) => o.values.length > 0)
: !!modelRefresh?.preview;
return (
<>
<CostBadge category={raw.costCategory} />
<button
type="button"
className={clsx(styles.modelRowConfigure, pinned && styles.pinnedButton)}
aria-label={pinned ? tx("Unpin model") : tx("Pin model")}
aria-pressed={pinned}
title={pinned ? tx("Unpin model") : tx("Pin model")}
onClick={() => togglePinnedModel(raw.value)}
>
<Icon name="pin" size={12} />
</button>
{configurable && (
<button
type="button"
className={clsx(
styles.modelRowConfigure,
styles.modelRowSettings,
raw.value === modelValue && styles.currentRowSettings,
)}
title={tx`Configure ${opt.label}…`}
aria-label={tx`Configure ${opt.label}…`}
aria-haspopup="dialog"
onClick={() => setPage({ model: raw.value })}
>
{rowSettings && <span>{settingsSummary(rowSettings, tx)}</span>}
<Icon name="chevron-right" size={14} />
</button>
)}
</>
);
}}
/>
) : (
<p className={styles.catalogNote} role="status">
{modelRefresh?.refreshing ? <T>Loading models…</T> : <T>No models reported by this agent.</T>}
</p>
)}
{modelRefresh && <ModelRefreshFooter key={modelRefresh.retryAtMs} {...modelRefresh} />}
</>
)}
{(effort || contextOption || otherModelConfigs.length > 0) && (
<div className={styles.quickSettings}>
{effort && (
<div className={styles.quickRow}>
<span className={styles.quickLabel}>
<T>Effort Level</T>
</Popup>
</span>
);
}
function ModelSettings({
id,
name,
settings,
modelRefresh,
onBack,
onChange,
}: {
id: string | null;
name: string;
settings: AgentConfigOption[] | undefined;
modelRefresh?: ModelRefresh;
onBack: () => void;
onChange: ChangeOption;
}) {
const tx = useTx();
const attempted = useRef(false);
const lookup = modelRefresh?.preview;
const refreshing = modelRefresh?.refreshing;
useEffect(() => {
if (!id || settings || !lookup || refreshing || attempted.current) return;
attempted.current = true;
lookup.load(id);
}, [id, settings, lookup, refreshing]);
const loading = modelRefresh?.loadingSettings || (!settings && refreshing);
const error = !settings && id && lookup?.errorFor(id);
return (
<div className={styles.quickSettings}>
<div className={styles.modelSettingsHeader}>
<IconButton autoFocus icon="arrow-left" title="Back to models" size="small" onClick={onBack} />
<strong>{name}</strong>
</div>
{loading ? (
<p role="status">
<T>Loading model settings…</T>
</p>
) : error ? (
<p role="alert" className={styles.catalogError}>{tx`Could not refresh models: ${error}`}</p>
) : !settings?.some((o) => o.values.length) ? (
<p role="status">
<T>No settings reported for this model.</T>
</p>
) : (
settings
.filter((o) => o.values.length > 0)
.map((o) => {
const label = tx(settingName(o));
const segmented =
isContextOption(o.id) || (o.category === "thought_level" && o.values.length <= SEGMENTED_EFFORT_MAX);
return (
<div key={o.id} className={styles.quickRow}>
<span className={styles.quickLabel} title={o.description ?? undefined}>
{label}
</span>
{effort.values.length <= SEGMENTED_EFFORT_MAX ? (
{segmented ? (
<SegmentedControl
ariaLabel={tx("Effort Level")}
options={effort.values.map((v) => ({
ariaLabel={label}
options={o.values.map((v) => ({
value: v.value,
label: v.name,
description: v.description ?? undefined,
}))}
value={effortValue ?? effort.values[0]!.value}
onChange={(v) => onChange(effort.id, v)}
value={settingValue(o)!.value}
onChange={(v) => onChange(o.id, v)}
/>
) : (
<ConfigPicker option={effort} value={effortValue} onChange={onChange} framed />
<ConfigPicker option={o} value={o.current} onChange={onChange} framed />
)}
</div>
)}
{contextOption && (
<div className={styles.quickRow}>
<span className={styles.quickLabel}>
<T>Context Size</T>
</span>
<SegmentedControl
ariaLabel={tx("Context Size")}
options={contextOption.values.map((v) => ({
value: v.value,
label: v.name,
description: v.description ?? undefined,
}))}
value={contextValue ?? contextOption.values[0]!.value}
onChange={(v) => onChange(contextOption.id, v)}
/>
</div>
)}
{otherModelConfigs.map((o) => (
<div key={o.id} className={styles.quickRow}>
<span className={styles.quickLabel} title={o.description ?? undefined}>
{tx(o.name)}
</span>
<ConfigPicker option={o} value={valueOf(o)} onChange={onChange} framed />
</div>
))}
</div>
)}
{model.values.length > 0 || !modelRefresh ? (
<SelectListbox
aria-label={tx(model.name)}
value={modelValue}
options={configPickerOptions(model, pinnedModels, false)}
searchable
listClassName={styles.modelList}
onChoose={(v) => {
onChange(model.id, v);
setOpen(false);
}}
renderAction={(opt) => {
const raw = model.values.find((v) => v.value === opt.value);
if (!raw) return null;
const pinned = pinnedModels.includes(raw.value);
return (
<>
<CostBadge category={raw.costCategory} />
<button
type="button"
className={clsx(styles.modelRowConfigure, pinned && styles.pinnedButton)}
aria-label={pinned ? tx("Unpin model") : tx("Pin model")}
aria-pressed={pinned}
title={pinned ? tx("Unpin model") : tx("Pin model")}
onClick={() => togglePinnedModel(raw.value)}
>
<Icon name="pin" size={12} />
</button>
</>
);
}}
/>
) : (
<p className={styles.catalogNote} role="status">
{modelRefresh?.refreshing ? <T>Loading models…</T> : <T>No models reported by this agent.</T>}
</p>
)}
{modelRefresh && <ModelRefreshFooter key={modelRefresh.retryAtMs} {...modelRefresh} />}
</Popup>
</>
);
})
)}
</div>
);
}
+10 -11
Переглянути файл
@@ -90,15 +90,16 @@ beforeEach(() => {
});
const modelButton = () => screen.getByRole("button", { name: "Model" });
const settingsButton = () => screen.getByRole("button", { name: /^Model settings:/ });
async function chooseModel(model: string) {
if (!screen.queryByRole("dialog", { name: "Model" })) fireEvent.click(modelButton());
fireEvent.click(screen.getByRole("option", { name: model }));
fireEvent.click(screen.getByTitle(model));
fireEvent.pointerDown(document.body);
}
async function chooseEffort(effort: string) {
if (!screen.queryByRole("dialog", { name: "Model" })) fireEvent.click(modelButton());
fireEvent.click(settingsButton());
const group = screen.getByRole("radiogroup", { name: "Effort Level" });
fireEvent.click(within(group).getByRole("radio", { name: effort }));
fireEvent.keyDown(document, { key: "Escape" });
@@ -107,14 +108,14 @@ async function chooseEffort(effort: string) {
it("switches model-specific levels and restores each draft effort before starting", async () => {
render(<HomeEditor />);
expect(modelButton()).toHaveTextContent("big");
expect(modelButton()).toHaveTextContent("high");
expect(settingsButton()).toHaveTextContent("high");
await chooseModel("small");
expect(modelButton()).toHaveTextContent("minimal");
expect(settingsButton()).toHaveTextContent("minimal");
await chooseEffort("medium");
await chooseModel("big");
expect(modelButton()).toHaveTextContent("high");
expect(settingsButton()).toHaveTextContent("high");
await chooseModel("small");
expect(modelButton()).toHaveTextContent("medium");
expect(settingsButton()).toHaveTextContent("medium");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([
@@ -143,12 +144,10 @@ it("uses GitHub Copilot's own defaults and preserves per-model context tier and
useAgents.setState({ providers: [copilot], draft: savedDraft({ provider: "copilot", config: {} }) });
render(<HomeEditor />);
expect(modelButton()).toHaveTextContent("gemini-4-carbon");
expect(modelButton()).toHaveTextContent("medium");
expect(modelButton()).toHaveTextContent("default");
expect(settingsButton()).toHaveTextContent("medium · default");
await chooseModel("gpt-5.6-sol");
expect(modelButton()).toHaveTextContent("gpt-5.6-sol");
expect(modelButton()).toHaveTextContent("medium");
expect(modelButton()).toHaveTextContent("default");
expect(settingsButton()).toHaveTextContent("medium · default");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toEqual([
@@ -182,7 +181,7 @@ it("ignores old provider-wide effort choices and refreshes unsupported per-model
draft: savedDraft({ provider: "fake", config: { effort: "low" }, thoughtLevels: { big: { effort: "removed" } } }),
});
render(<HomeEditor />);
expect(modelButton()).toHaveTextContent("high");
expect(settingsButton()).toHaveTextContent("high");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
expect(backend.create.mock.calls[0]![0].config).toContainEqual({ id: "effort", value: "high" });
+17 -2
Переглянути файл
@@ -23,6 +23,7 @@ import {
HOME,
NO_COMMANDS,
draftConfig,
draftModelSettings,
refreshProviders,
refreshModels,
setDraftMcpOverrides,
@@ -99,7 +100,8 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
const requestingModels = useAgents((s) => s.modelRequests.has(provider?.id ?? ""));
const requestTarget = useAgents((s) => s.modelRequestTargets.get(provider?.id ?? ""));
const { defaults, fitWindowWidth } = useAgentSettings();
const config = draftConfig(provider, draft, (provider && defaults[provider.id]) || {});
const providerDefaults = (provider && defaults[provider.id]) || {};
const config = draftConfig(provider, draft, providerDefaults);
const model = config.find((o) => o.category === "model");
const selectedModel = model?.current ?? null;
const selectedModelRef = useRef(selectedModel);
@@ -229,7 +231,10 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
<ConfigPickers
key={provider?.id}
config={config}
onChange={setDraftOption}
onChange={(option, value, forModel) => {
if (forModel && model) setDraftOption(model.id, forModel);
setDraftOption(option, value);
}}
modelRefresh={
provider?.installed
? {
@@ -242,6 +247,16 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
: null,
error: !requestingModels && currentModelRequest ? (catalog?.error ?? null) : null,
onRefresh: () => void executeAction("agents.refreshModels", null),
preview: {
settingsFor: (id) =>
draftModelSettings(
(catalog ?? provider).thoughtLevels?.[id],
draft.thoughtLevels?.[id],
providerDefaults,
),
load: (id) => void refreshModels(provider.id, false, id),
errorFor: (id) => (requestTarget === id ? catalog?.error : null),
},
}
: undefined
}
+17 -2
Переглянути файл
@@ -6,6 +6,8 @@
import { createElement } from "react";
import { registerActions } from "@/platform/actions";
import { useProject } from "@/platform/project";
import { clearContext, setContext } from "@/platform/context";
import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowSettings";
import { executeAction } from "@/platform/actions";
import { lazyComponent, lazyWhen } from "@/ui";
import { isVirtualUri } from "@/platform/virtualDocs";
@@ -47,6 +49,18 @@ import { replyActions } from "./replyActions";
export { activateSettingsPages } from "./settingsPages";
function trackAgentButtonSetting(): () => void {
setContext("commitAgentButton", workflowSettings().vcs.commit.agentButton);
const stop = onWorkflowSettingsChange(
(s) => s.vcs.commit.agentButton,
(on) => setContext("commitAgentButton", on),
);
return () => {
stop();
clearContext("commitAgentButton");
};
}
export function activate(): () => void {
const sync = (root: string | null | undefined) => {
disconnect();
@@ -153,12 +167,13 @@ export function activate(): () => void {
accepts: (type) => type === TASK_DRAG,
drop: ({ payload }) => void executeAction("agents.openTaskInEditor", payload),
}),
// The button above the commit message (the Commit tool window and dialog).
// The button above the commit message (the Commit tool window and dialog), unless turned off.
trackAgentButtonSetting(),
registerMenuSlotItem("commitMessage", {
action: "agents.generateCommitMessage",
label: "Generate Commit Message with Agent",
icon: "toolwindow-agents",
when: "projectOpen && vcsAvailable",
when: "projectOpen && vcsAvailable && commitAgentButton",
}),
registerStatusItem({ id: "agents.status", align: "right", priority: 3, title: "Agents", component: AgentsStatus }),
registerMenuGroup({
+46 -13
Переглянути файл
@@ -220,7 +220,7 @@ it("refreshes an existing chat's searchable model choices and switches through i
expect(modelButton).toHaveTextContent("old");
expect(screen.getByRole("option", { name: "session-only" })).toBeVisible();
expect(modelButton).toHaveTextContent("low");
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("low");
expect(screen.getByRole("button", { name: "Mode" })).toHaveTextContent("plan");
expect(screen.getByText("Earlier message")).toBeVisible();
expect(screen.queryByText("catalog-only")).not.toBeInTheDocument();
@@ -363,7 +363,7 @@ it("retains cached model and effort choices after a command failure and retries
draft: savedDraft({ provider: "first", config: { model: "big" }, thoughtLevels: { big: { effort: "low" } } }),
});
render(<HomeEditor />);
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("low");
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("low");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(await screen.findByRole("alert")).toHaveTextContent("connection lost");
fireEvent.click(screen.getByRole("option", { name: "small" }));
@@ -390,7 +390,7 @@ it("preserves a valid remembered model and effort when discovery changes the def
render(<HomeEditor />);
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("low");
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("low");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(screen.getByRole("option", { name: "new" })).toBeVisible();
fireEvent.keyDown(document, { key: "Escape" });
@@ -528,16 +528,18 @@ it("discovers an uncached model's own settings before its first task and restore
),
);
expect(screen.queryByText("Loading model settings…")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("medium");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
const settings = screen.getByRole("button", { name: /^Model settings:/ });
expect(settings).toHaveTextContent("medium");
fireEvent.click(settings);
fireEvent.click(screen.getByRole("radio", { name: "max" }));
expect(screen.getByRole("radio", { name: "long_context" })).toBeVisible();
fireEvent.click(screen.getByRole("radio", { name: "long_context" }));
fireEvent.click(screen.getByRole("option", { name: "big" }));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("high");
fireEvent.click(screen.getByRole("button", { name: "Back to models" }));
fireEvent.click(screen.getByTitle("big"));
expect(settings).toHaveTextContent("high");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("option", { name: "small" }));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("max");
fireEvent.click(screen.getByTitle("small"));
expect(settings).toHaveTextContent("max");
expect(backend.refresh).toHaveBeenCalledTimes(2);
fireEvent.click(screen.getByRole("button", { name: "Start" }));
await waitFor(() => expect(backend.create).toHaveBeenCalled());
@@ -555,13 +557,44 @@ it("does not rediscover a model that explicitly reports no per-model controls",
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
for (const model of ["small", "big", "small"]) {
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("option", { name: model }));
fireEvent.click(screen.getByTitle(model));
}
expect(backend.refresh).toHaveBeenCalledExactlyOnceWith("first", false, "big");
expect(screen.queryByText("Loading model settings…")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Reasoning" })).not.toBeInTheDocument();
});
it("inspects uncached settings without switching models or borrowing the current model's levels", async () => {
delete backend.providers[0]!.thoughtLevels!.small;
await connect();
render(<HomeEditor />);
await waitFor(() => expect(useAgents.getState().modelRequests.size).toBe(0));
const pending = deferred<CatalogReply>();
backend.refresh.mockReturnValueOnce(pending.promise);
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("button", { name: "Configure small…" }));
expect(backend.refresh).toHaveBeenLastCalledWith("first", false, "small");
expect(screen.getByRole("status")).toHaveTextContent("Loading model settings…");
expect(screen.queryByRole("radio")).not.toBeInTheDocument();
await act(async () =>
pending.resolve(
ok(
catalog("first", {
thoughtLevels: {
...catalog().thoughtLevels,
small: [option("effort", "thought_level", ["quick", "thorough"])],
},
}),
),
),
);
expect(screen.getByRole("radio", { name: "quick" })).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Back to models" }));
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big");
expect(backend.setConfig).not.toHaveBeenCalled();
expect(backend.create).not.toHaveBeenCalled();
});
it("waits for an unrelated lookup and discovers only the latest selected model", async () => {
backend.providers[0]!.config = [option("model", "model", ["big", "small", "latest"])];
await connect();
@@ -587,7 +620,7 @@ it("waits for an unrelated lookup and discovers only the latest selected model",
ok(catalog("first", { thoughtLevels: { latest: [option("effort", "thought_level", ["medium", "max"])] } })),
),
);
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("medium");
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("medium");
expect(backend.refresh).toHaveBeenCalledTimes(2);
expect(backend.create).not.toHaveBeenCalled();
});
@@ -628,7 +661,7 @@ it("does not leak a delayed model's levels or failure into a newer selection", a
backend.refresh.mockReturnValueOnce(pending.promise);
for (const model of ["small", "big"]) {
fireEvent.click(screen.getByRole("button", { name: "Model" }));
fireEvent.click(screen.getByRole("option", { name: model }));
fireEvent.click(screen.getByTitle(model));
}
await act(async () =>
pending.resolve(
@@ -645,7 +678,7 @@ it("does not leak a delayed model's levels or failure into a newer selection", a
),
);
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("big");
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("low");
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("low");
fireEvent.click(screen.getByRole("button", { name: "Model" }));
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Refresh models" })).toBeEnabled();
+22 -4
Переглянути файл
@@ -160,6 +160,7 @@ export function SessionComposer({
const provider = useAgents((s) => s.providers.find((p) => p.id === task.provider));
const catalog = useAgents((s) => s.modelCatalogs.get(task.provider));
const requestingModels = useAgents((s) => s.modelRequests.has(task.provider));
const requestTarget = useAgents((s) => s.modelRequestTargets.get(task.provider));
const model = task.config.find((o) => o.category === "model");
const catalogModel = (catalog?.config ?? provider?.config)?.find((o) => o.category === "model");
const canRefreshModels =
@@ -225,16 +226,28 @@ export function SessionComposer({
)
.finally(() => setSending(false));
};
const setOption = (id: string, value: string) => {
const changingModel = id === model?.id;
const loadingModel = changingModel && !model.values.some((v) => v.value === value);
const setOption = (id: string, value: string, forModel?: string) => {
const pickerModel = pickerConfig.find((o) => o.category === "model");
const changingModel = id === pickerModel?.id;
const loadingModel = !!forModel || (changingModel && !model?.values.some((v) => v.value === value));
const pendingModel = model?.current != null && model.current !== task.model;
const change = loadingModel || (changingModel && configChange.current) || pendingModel ? { loadingModel } : null;
if (change) {
configChange.current = change;
setConfiguring(change);
}
void setTaskConfig(task.id, id, value)
const apply = async () => {
if (forModel && pickerModel) {
await setTaskConfig(task.id, pickerModel.id, forModel);
// A later model choice supersedes both halves of this edit.
const latest = useAgents.getState().tasks.get(task.id);
const selected = latest?.config.find((o) => o.category === "model")?.current ?? latest?.model;
if (configChange.current !== change) return;
if (selected !== forModel) throw new Error(tx("The model changed before its setting could be applied."));
}
await setTaskConfig(task.id, id, value);
};
void apply()
.catch((e: unknown) =>
notifications().notify({
level: "error",
@@ -313,6 +326,11 @@ export function SessionComposer({
error: requestingModels ? null : (catalog?.error ?? null),
onOpen: () => void refreshTaskModels(task.id, false),
onRefresh: () => void executeAction("agents.refreshModels", task.id),
preview: {
settingsFor: (id) => (catalog ?? provider)?.thoughtLevels?.[id],
load: (id) => void refreshTaskModels(task.id, false, id),
errorFor: (id) => (requestTarget === id ? catalog?.error : null),
},
}
: undefined
}
+19 -10
Переглянути файл
@@ -279,19 +279,28 @@ export function draftConfig(
const model = config.find((o) => o.category === "model")?.current;
if (model) {
config.push(
...((catalog ?? provider)?.thoughtLevels?.[model] ?? []).map((o) => {
const choice = draft.thoughtLevels?.[model]?.[o.id] ?? defaults[o.id];
return {
...o,
defaultValue: o.defaultValue ?? o.current,
current: choice !== undefined && o.values.some((v) => v.value === choice) ? choice : o.current,
};
}),
...(draftModelSettings((catalog ?? provider)?.thoughtLevels?.[model], draft.thoughtLevels?.[model], defaults) ??
[]),
);
}
return config;
}
export function draftModelSettings(
options: AgentConfigOption[] | undefined,
choices: Record<string, string> | undefined,
defaults: Record<string, string>,
) {
return options?.map((o) => {
const choice = choices?.[o.id] ?? defaults[o.id];
return {
...o,
defaultValue: o.defaultValue ?? o.current,
current: choice !== undefined && o.values.some((v) => v.value === choice) ? choice : o.current,
};
});
}
export function setDraftOption(id: string, value: string) {
const { draft, providers } = useAgents.getState();
const config = draftConfig(
@@ -418,13 +427,13 @@ export async function refreshModels(
}
/** Discover switch candidates without using or updating the session's settings. */
export async function refreshTaskModels(id: string, force = true): Promise<void> {
export async function refreshTaskModels(id: string, force = true, model: string | null = null): Promise<void> {
const { tasks, providers } = useAgents.getState();
const task = tasks.get(id);
if (!task || task.status === "archived" || (!task.model && !task.config.some((o) => o.category === "model"))) return;
const provider = providers.find((p) => p.id === task.provider);
if (!provider?.installed || useProject.getState().project?.trusted === false) return;
await refreshProviderModels(provider, force, null, null);
await refreshProviderModels(provider, force, model, null);
}
async function refreshProviderModels(
+17 -1
Переглянути файл
@@ -130,7 +130,7 @@ describe("Maven tree", () => {
it("shows profiles, then the aggregator with lifecycle, plugins and its modules", () => {
const roots = mavenRoots(maven);
expect(labels(roots)).toEqual(["Profiles", "Multi Demo"]);
expect(labels(children(roots[0]!))).toEqual(["dev", "ci"]);
expect(labels(children(roots[0]!))).toEqual(["ci", "dev"]);
const top = children(roots[1]!);
expect(labels(top)).toEqual(["Lifecycle", "Plugins", "core", "Demo App"]);
expect(labels(children(top[0]!))).toEqual([
@@ -148,6 +148,22 @@ describe("Maven tree", () => {
expect(nodeIcon(roots[1]!)).toBe("maven-project");
});
it("sorts Maven profiles by ID ignoring case while preserving the order used for Maven arguments", () => {
const model = {
...maven,
profiles: [
{ id: "zulu", activeByDefault: false },
{ id: "Beta", activeByDefault: false },
{ id: "alpha_ci", activeByDefault: false },
{ id: "alpha", activeByDefault: true },
{ id: "alpha-edge", activeByDefault: false },
],
};
const group = mavenRoots(model)[0]!;
expect(labels(mavenChildren(group, model, [])!)).toEqual(["alpha", "alpha-edge", "alpha_ci", "Beta", "zulu"]);
expect(profilesArg(model.profiles, { zulu: true, alpha_ci: true, alpha: false })).toBe("zulu,alpha_ci,!alpha");
});
it("expands plugins to goals and dependencies to their transitive ones", () => {
const core = children(mavenRoots(maven)[1]!)[2]!;
const kids = children(core);
+5
Переглянути файл
@@ -187,6 +187,11 @@ export function mavenChildren(
case "profiles":
return model.profiles
.filter((p) => p.projectRoot === node.projectRoot)
.sort((a, b) => {
const aId = a.id.toLowerCase();
const bId = b.id.toLowerCase();
return aId < bId ? -1 : aId > bId ? 1 : 0;
})
.map((profile) => ({ kind: "profile", key: `mvn:profile:${profileKey(profile)}`, profile }));
case "mavenProject": {
const p = node.project;
+8 -6
Переглянути файл
@@ -1020,14 +1020,16 @@ export function SourceDialog({
}
onChange={(e) => setOptions({ timeZone: e.target.value })}
/>
<SecondsOption
label="Run keep-alive query each"
value={options.keepAliveSecs}
fallback={60}
onChange={(keepAliveSecs) => setOptions({ keepAliveSecs })}
/>
</>
)}
{!sqlite && (
<SecondsOption
label="Run keep-alive query each"
value={options.keepAliveSecs}
fallback={60}
onChange={(keepAliveSecs) => setOptions({ keepAliveSecs })}
/>
)}
<SecondsOption
label="Auto-disconnect after"
value={options.autoDisconnectSecs}
+14
Переглянути файл
@@ -1072,6 +1072,18 @@ function promptOf(id: string): string {
* `schema` is a console's active context: the backend puts the connection that runs
* each statement in it, so unqualified names resolve there.
*/
/** Shows `id` disconnected when the backend closed its connection (it reconnects on next use). */
async function syncDropped(id: string) {
const server = await call(commands.dbConnected()).catch(() => null);
if (!server || server.includes(id) || !useDatabase.getState().connected.has(id)) return;
useDatabase.setState((s) => {
const connected = new Set(s.connected);
connected.delete(id);
return { connected };
});
log("info", `${targetLabel(id)}: the connection was lost; the next statement reconnects`);
}
async function run(
id: string,
statements: SqlStatement[],
@@ -1087,6 +1099,8 @@ async function run(
);
if (!current()) return outcomes;
if (!wasConnected) log("info", "Connected");
// A failed statement can have found the session dead; the backend then dropped it.
if (outcomes.some((o) => o.error)) void syncDropped(id);
const prompt = schema || promptOf(id);
for (const o of outcomes) {
log("statement", o.statement.text, `${prompt}>`);
+1 -1
Переглянути файл
@@ -292,7 +292,7 @@ describe("debug tool window", () => {
expect(screen.getByRole("tab", { name: /main/ })).toBeTruthy();
expect(screen.getByRole("tab", { name: "Threads & Variables" })).toBeTruthy();
expect(screen.getByRole("tab", { name: "Console" })).toBeTruthy();
expect(screen.getByText(", main.py:12")).toBeTruthy();
expect(screen.getByRole("option", { selected: true })).toHaveTextContent("main:12, main.py");
expect(screen.getByPlaceholderText("Evaluate expression (↩) or add a watch (⇧⌘↩)")).toBeTruthy();
expect(await screen.findByText("{int}")).toBeTruthy();
expect(screen.getByText("'hi'")).toBeTruthy();
+31 -10
Переглянути файл
@@ -102,11 +102,20 @@
display: flex;
flex-direction: column;
min-height: 0;
padding: 4px 0;
padding-bottom: var(--space-1);
}
.threadHeader {
display: flex;
align-items: center;
flex: none;
height: 30px;
padding: 0 var(--space-1);
border-bottom: 1px solid var(--border);
}
.threadSelect {
margin: 0 8px 4px;
max-width: 100%;
}
.frameList {
@@ -116,7 +125,7 @@
display: flex;
flex-direction: column;
outline: none;
padding: 0 4px;
padding: var(--space-1) var(--space-1) 0;
}
.frame {
@@ -150,24 +159,36 @@
flex: none;
}
.frameName {
.frameText,
.frameLabel {
display: flex;
align-items: baseline;
min-width: 0;
}
.frameText {
flex: 1;
}
.frameLine {
flex: none;
}
.frameName,
.frameFile {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.frameFile {
flex: 1;
min-width: 0;
/* ", File.java:12" hugs the name, cancelling the row gap. */
margin-left: -6px;
flex: 0 1000 auto;
min-width: min(12ch, 32%);
color: var(--fg-subtle);
overflow: hidden;
text-overflow: ellipsis;
font-size: var(--fs-small);
}
.hiddenFrames {
display: block;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
font-style: italic;
}
+33 -18
Переглянути файл
@@ -1,6 +1,6 @@
/** Debug tool window: toolbar, Threads & Variables (frames + variables), Console. */
import { writeClipboardText } from "@/platform/clipboard";
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { basename, useProject } from "@/platform/project";
@@ -22,6 +22,7 @@ import {
type TabItem,
T,
} from "@/ui";
import { revealVertically } from "@/ui/Tabs";
import { setMuted, useBreakpoints } from "../breakpoints/store";
import { frameLabel, groupFrames } from "../frames";
import { blurDebugView, focusDebugView } from "./focusedView";
@@ -347,10 +348,15 @@ function ThreadsAndVariables({ session }: { session: DebugSession }) {
function FramesPane({ session }: { session: DebugSession }) {
const root = useProject((s) => s.project?.root ?? null);
const [showAll, setShowAll] = useState(false);
const list = useRef<HTMLDivElement>(null);
const selectedRow = useRef<HTMLButtonElement>(null);
const items = useMemo(
() => groupFrames(session.frames, root, session.selectedFrame, showAll),
[session.frames, root, session.selectedFrame, showAll],
);
useLayoutEffect(() => {
if (list.current && selectedRow.current) revealVertically(list.current, selectedRow.current);
}, [items]);
const paused = session.status === "paused";
const onKeyDown = (e: KeyboardEvent) => {
if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
@@ -365,19 +371,24 @@ function FramesPane({ session }: { session: DebugSession }) {
return (
<div className={styles.frames}>
{session.threads.length > 0 && (
<Select
value={session.selectedThread != null ? String(session.selectedThread) : null}
options={session.threads.map((t) => ({
value: String(t.id),
label: t.name,
detail: t.id === session.stoppedThread ? "suspended" : undefined,
}))}
onChange={(v) => void selectThread(session.id, +v)}
aria-label="Thread"
className={styles.threadSelect}
/>
<div className={styles.threadHeader}>
<Select
value={session.selectedThread != null ? String(session.selectedThread) : null}
options={session.threads.map((t) => ({
value: String(t.id),
label: t.name,
verbatim: true,
detail: t.id === session.stoppedThread ? "suspended" : undefined,
}))}
onChange={(v) => void selectThread(session.id, +v)}
aria-label="Thread"
variant="ghost"
className={styles.threadSelect}
/>
</div>
)}
<div
ref={list}
className={styles.frameList}
role="listbox"
aria-label={tx("Frames")}
@@ -415,9 +426,11 @@ function FramesPane({ session }: { session: DebugSession }) {
) : (
<button
key={item.frame.id}
ref={item.frame.id === session.selectedFrame ? selectedRow : undefined}
type="button"
role="option"
aria-selected={item.frame.id === session.selectedFrame}
title={item.frame.path ? `${frameLabel(item.frame)}, ${basename(item.frame.path)}` : item.frame.name}
className={clsx(
styles.frame,
item.frame.id === session.selectedFrame && styles.frameSelected,
@@ -459,13 +472,15 @@ function FramesPane({ session }: { session: DebugSession }) {
}}
>
<Icon name="method" size={16} className={styles.frameIcon} />
<span className={styles.frameName}>{item.frame.name}</span>
{item.frame.path && (
<span className={styles.frameFile}>
, {basename(item.frame.path)}
{item.frame.line >= 0 ? `:${item.frame.line + 1}` : ""}
<span className={styles.frameText}>
<span className={styles.frameLabel}>
<span className={styles.frameName}>{item.frame.name}</span>
{item.frame.path && item.frame.line >= 0 && (
<span className={styles.frameLine}>:{item.frame.line + 1}</span>
)}
</span>
)}
{item.frame.path && <span className={styles.frameFile}>, {basename(item.frame.path)}</span>}
</span>
</button>
),
)}
+4 -1
Переглянути файл
@@ -2,6 +2,7 @@ import { StateEffect, StateField, type Text } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type DecorationSet as CmDecorations } from "@codemirror/view";
import type { DecorationSet, Range } from "@/bindings";
import { registerEditorContribution, useEditorRegistry, type EditorDocContext } from "@/editor/api";
import { foldChipWidth } from "@/editor/core/cm/folding";
import { commands, isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { addPathIconProvider, bumpFileIconRevision } from "@/ui";
@@ -147,8 +148,10 @@ class AfterText extends WidgetType {
if (!line || !inner) return;
const own = offsetOf(el, "--openidea-message-offset");
const hint = line.querySelector<HTMLElement>(".cm-openidea-lensInlineInner");
// A folded chip drawn after this anchor paints under the box; step past it first (folding.ts).
let width = foldChipWidth(el);
// The hint's inner box sits `--openidea-hint-offset` past its zero-width anchor.
let width = hint ? Math.round(hint.getBoundingClientRect().width) + offsetOf(hint, "--openidea-hint-offset") : 0;
if (hint) width += Math.round(hint.getBoundingClientRect().width) + offsetOf(hint, "--openidea-hint-offset");
// Every message before this one adds its own width and offset.
for (const other of line.querySelectorAll<HTMLElement>(".cm-plugin-after")) {
if (other === el || other.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING) continue;
+3
Переглянути файл
@@ -417,6 +417,9 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
{ kind: "separator" },
act("vcs.stash", undefined, "Stash Changes…"),
act("vcs.unstash", undefined, "Unstash Changes…"),
{ kind: "separator" },
act("vcs.manageRemotes", undefined, "Manage Remotes…"),
act("vcs.clone", undefined, "Clone…"),
],
"branch",
),
+25 -1
Переглянути файл
@@ -47,7 +47,10 @@ vi.mock("@/platform/javaLaunch", async (original) => ({
...(await original<typeof import("@/platform/javaLaunch")>()),
resolveJavaModule: async () => "app",
}));
vi.mock("./buildUpdate", () => ({ runUpdateBuild: mocks.runBuild }));
vi.mock("./buildUpdate", async (original) => ({
...(await original<typeof import("./buildUpdate")>()),
runUpdateBuild: mocks.runBuild,
}));
vi.mock("./tomcat", () => ({ buildTomcatArtifact: mocks.build, syncTomcatOutputs: mocks.sync }));
vi.mock("./store", () => ({
rerunConfig: (s: Pick<RunSession, "config">) => mocks.state.configs.find((c) => c.id === s.config.id) ?? s.config,
@@ -157,6 +160,27 @@ describe("Spring Boot application updates", () => {
expect.objectContaining({ body: expect.stringContaining("Restart the application") }),
);
});
it("names the compile errors when the update's Java build fails", async () => {
mocks.resolve.mockResolvedValueOnce({
status: "ok",
data: {
build: "withErrors",
classPaths: [],
pathListSeparator: ":",
errors: [{ path: "/p/app/src/A.java", line: 1, column: 1, message: "illegal character: '\\ufeff'" }],
errorCount: 1,
hints: [],
},
} as never);
await updateTomcat(boot, "classes");
expect(mocks.runBuild).not.toHaveBeenCalled();
expect(mocks.notify).toHaveBeenCalledWith(
expect.objectContaining({
level: "error",
body: "Application update build failed\n/p/app/src/A.java:1:1: error: illegal character: '\\ufeff'",
}),
);
});
it("never publishes resources after a failed build", async () => {
mocks.runBuild.mockRejectedValueOnce(new Error("failed"));
await updateTomcat(boot, "resources");
+8 -3
Переглянути файл
@@ -12,7 +12,7 @@ import {
} from "@/workbench/contributions";
import { showContextMenu } from "@/ui";
import { buildTomcatArtifact, syncTomcatOutputs } from "./tomcat";
import { runUpdateBuild } from "./buildUpdate";
import { runUpdateBuild, updateBuildError } from "./buildUpdate";
import { rerunConfig, startRun, stopSession, useRun, waitForExit, type RunSession } from "./store";
import { isUpdatable, updateAllowed, type UpdateMode } from "./updatePolicies";
@@ -51,7 +51,7 @@ async function updateSpringBoot(config: RunConfig, mode: UpdateMode, debugging:
),
);
if (info.build === "failed" || info.build === "withErrors" || info.build === "cancelled")
throw new Error(tx("Application update build failed"));
throw updateBuildError(info);
await runUpdateBuild(await call(commands.runApplicationBuild(config, module)));
const classPaths = parsed.explicitClasspath?.split(info.pathListSeparator) ?? info.classPaths;
await call(commands.runApplicationPublish(config, classPaths, parsed.mainClass));
@@ -106,7 +106,12 @@ export async function updateApplication(session: UpdateSession, mode: string): P
}
if (!session.debug) useRun.setState({ activeSession: session.id });
} catch (e) {
notifications().notify({ group: "run", level: "error", title: "Application update failed", body: String(e) });
notifications().notify({
group: "run",
level: "error",
title: "Application update failed",
body: e instanceof Error ? e.message : String(e),
});
} finally {
updatingConfigs.delete(session.config.id);
useApplicationUpdates.setState((s) => ({ ids: new Set([...s.ids].filter((id) => id !== session.id)) }));
+31
Переглянути файл
@@ -0,0 +1,31 @@
import { describe, expect, it, vi } from "vitest";
vi.mock("./store", () => ({ startRun: vi.fn() }));
import { compileErrorCollector } from "./buildUpdate";
describe("compileErrorCollector", () => {
it("keeps the compiler errors of Maven, javac and Kotlin output without colour codes", () => {
const errors = compileErrorCollector();
errors.add("[INFO] Compiling 3 source files with javac [debug release 17] to target/classes");
errors.add("\u001b[1;31m[ERROR] /p/src/main/java/a/XxxServiceImpl.java:[1,1] 非法字符: '\\ufeff'\u001b[m");
errors.add("[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.13.0:compile");
// Maven's failure summary repeats the error.
errors.add("[ERROR] /p/src/main/java/a/XxxServiceImpl.java:[1,1] 非法字符: '\\ufeff'");
errors.add("/p/src/main/java/a/B.java:12: error: ';' expected\n int x = 1\n");
errors.add("e: file:///p/src/main/kotlin/a/C.kt:3:5 Unresolved reference: foo");
expect(errors.lines()).toEqual([
"[ERROR] /p/src/main/java/a/XxxServiceImpl.java:[1,1] 非法字符: '\\ufeff'",
"/p/src/main/java/a/B.java:12: error: ';' expected",
"e: file:///p/src/main/kotlin/a/C.kt:3:5 Unresolved reference: foo",
]);
});
it("keeps the first ten and counts the rest", () => {
const errors = compileErrorCollector();
for (let i = 1; i <= 13; i++) errors.add(`[ERROR] /p/A.java:[${i},1] cannot find symbol`);
const lines = errors.lines();
expect(lines).toHaveLength(11);
expect(lines[9]).toBe("[ERROR] /p/A.java:[10,1] cannot find symbol");
expect(lines[10]).toBe("… and 3 more");
});
});
+47 -3
Переглянути файл
@@ -1,15 +1,59 @@
import { tx } from "@/platform/i18n";
import type { RunConfig } from "@/platform/ipc";
import type { JavaLaunchInfo, RunConfig } from "@/platform/ipc";
import { formatCompileErrors } from "@/platform/javaLaunch";
import { stripAnsi } from "@/ui/ansi";
import { startRun } from "./store";
const MAX_ERRORS = 10;
/**
* A compiler error line of a Maven or Gradle build: Maven's `[ERROR] /p/A.java:[1,1] …`,
* javac's `/p/A.java:1: error: …` and Kotlin's `e: file:///p/A.kt:1:1 …`.
*/
const COMPILE_ERROR = [
/^\[ERROR\] .+\.(?:java|kt|groovy|scala):\[\d+,\d+\]/,
/^.+\.(?:java|groovy|scala):\d+: error: /,
/^e: .+\.kts?:\d+:\d+ /,
];
/** Collects the distinct compiler errors of a build's output, without colour codes; `lines()` keeps the first `MAX_ERRORS`. */
export function compileErrorCollector() {
const errors: string[] = [];
// Maven repeats each compiler error in its failure summary.
const seen = new Set<string>();
return {
add(text: string) {
for (const raw of text.split("\n")) {
const line = stripAnsi(raw).trimEnd();
if (seen.has(line) || !COMPILE_ERROR.some((re) => re.test(line))) continue;
seen.add(line);
if (seen.size <= MAX_ERRORS) errors.push(line);
}
},
lines: () => (seen.size > MAX_ERRORS ? [...errors, `… and ${seen.size - MAX_ERRORS} more`] : errors),
};
}
function failure(details: readonly string[]): Error {
const title = tx("Application update build failed");
return new Error(details.length ? `${title}\n${details.join("\n")}` : title);
}
export async function runUpdateBuild(build: RunConfig): Promise<void> {
let finish!: (ok: boolean) => void;
const exited = new Promise<boolean>((resolve) => {
finish = resolve;
});
const errors = compileErrorCollector();
const session = await startRun(build, undefined, undefined, {
onLine: errors.add,
onExit: (code, stopped) => finish(code === 0 && !stopped),
});
if (!session || session.status === "failed" || !(await exited))
throw new Error(tx("Application update build failed"));
if (!session || session.status === "failed" || !(await exited)) throw failure(errors.lines());
}
/** The error for an update whose Java build failed, with the compiler's errors so the user sees what to fix. */
export function updateBuildError(info: JavaLaunchInfo): Error {
const errors = formatCompileErrors(info).trimEnd();
return failure(errors ? errors.split("\n") : []);
}
+2 -3
Переглянути файл
@@ -1,8 +1,7 @@
import { tx } from "@/platform/i18n";
import { call, commands, nextRequestId, type RunConfig } from "@/platform/ipc";
import type { RunConfigTypeContribution } from "@/workbench/contributions";
import { updatePolicyDefaults, updatePolicyFields } from "./updatePolicies";
import { runUpdateBuild } from "./buildUpdate";
import { runUpdateBuild, updateBuildError } from "./buildUpdate";
const validatePort = (value: string) =>
/^\d+$/.test(value) && Number(value) > 0 && Number(value) <= 65535 ? null : "Port must be between 1 and 65535";
@@ -167,7 +166,7 @@ export async function syncTomcatOutputs(config: RunConfig, resourcesOnly: boolea
);
if (!info) return false;
if (info.build === "failed" || info.build === "withErrors" || info.build === "cancelled")
throw new Error(tx("Application update build failed"));
throw updateBuildError(info);
return call(commands.runTomcatSync(config, artifact.module, info.classPaths, resourcesOnly));
}
+45 -17
Переглянути файл
@@ -1,16 +1,31 @@
.root {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
min-width: 0;
}
.tabs {
min-width: 0;
border: 0;
background: none;
}
.toolbar {
flex: none;
width: 32px;
display: flex;
flex-direction: column;
align-items: center;
gap: var(--space-0-5);
padding: var(--space-1) 0;
border-right: 1px solid var(--border);
overflow-y: auto;
}
.toolbar > button {
flex: none;
}
.body {
flex: 1;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
@@ -20,23 +35,24 @@
display: flex;
align-items: center;
gap: var(--space-2);
height: 26px;
padding: 0 10px;
min-height: 26px;
padding: var(--space-0-5) var(--space-2);
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.title {
color: var(--fg-secondary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--fs-ui);
}
.count {
flex: none;
color: var(--fg-faint);
min-width: 0;
overflow-wrap: anywhere;
}
.spacer {
flex: 1;
.replaceActions {
flex: none;
display: flex;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
gap: var(--space-1) var(--space-2);
padding: var(--space-1) var(--space-2);
border-top: 1px solid var(--border);
}
.tree {
flex: 1;
@@ -47,6 +63,7 @@
}
.node {
display: flex;
flex: 1;
align-items: center;
gap: var(--space-1-5);
min-width: 0;
@@ -56,6 +73,8 @@
color: var(--fg-muted);
}
.label {
flex: none;
max-width: 56%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -65,12 +84,20 @@
color: var(--fg-faint);
font-size: var(--fs-small);
}
.directory {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.lineNo {
flex: none;
min-width: 28px;
color: var(--fg-gutter);
min-width: 3ch;
color: var(--fg-line-number);
font-family: var(--font-mono);
font-size: var(--fs-small);
font-size: var(--fs-ui);
text-align: right;
}
.code {
@@ -79,6 +106,7 @@
text-overflow: ellipsis;
white-space: pre;
font-family: var(--font-mono);
font-size: var(--fs-code);
}
.nodeWrap {
display: contents;
+148 -134
Переглянути файл
@@ -1,5 +1,5 @@
import { menuGroupItems } from "@/workbench/contributions";
import { useMemo, useRef, useState, type KeyboardEvent } from "react";
import { useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { create } from "zustand";
import { executeAction } from "@/platform/actions";
@@ -218,16 +218,26 @@ export function FindToolWindow() {
</EmptyState>
);
}
return (
<div className={styles.root}>
<FindTabView key={tab.id} tab={tab} />
</div>
);
return <FindTabView key={tab.id} tab={tab} />;
}
function FindTabView({ tab }: { tab: FindTab }) {
const groupByDirectory = useFindViewOptions((o) => o.groupByDirectory);
const showPreview = useFindViewOptions((o) => o.preview);
const body = useRef<HTMLDivElement>(null);
const [stacked, setStacked] = useState(false);
useLayoutEffect(() => {
const frame = body.current;
if (!showPreview || !frame) return;
const measure = () => setStacked(frame.clientWidth < 580);
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(frame);
return () => observer.disconnect();
}, [showPreview]);
const previewLayout = stacked ? "openidea.find.previewSplit.vertical" : "openidea.find.previewSplit";
const minPanelSize = stacked ? "30%" : 160;
const roots = useMemo(() => buildFindTree(tab.state.files, groupByDirectory), [tab.state.files, groupByDirectory]);
const tree = useRef<TreeHandle>(null);
const [leadNode, setLeadNode] = useState<Node | null>(null);
@@ -381,26 +391,118 @@ function FindTabView({ tab }: { tab: FindTab }) {
const selectedPending = pendingUsages(selectedGroups(), marks);
return (
<div className={styles.body} onKeyDown={onKeyDown}>
<div className={styles.summary}>
{(st.status === "searching" || busy) && <Spinner size={16} variant="spokes" />}
<span className={styles.title}>{tab.title}</span>
<span className={styles.count}>
{st.status === "invalid" || st.status === "error"
? (st.error ?? tx("Search failed"))
: progress
? tx`Replacing… ${progress.done}/${progress.total} files`
: t(st.summary?.limitHit ? "search.find.matchesIncomplete" : "search.find.matches", {
matches: st.matchCount,
files: st.files.length,
}) + (marks.excluded.size ? ` · ${tx`${marks.excluded.size} excluded`}` : "")}
</span>
<span className={styles.spacer} />
<Button size="small" variant="ghost" disabled={!selection.size} onClick={exclude} title="Exclude / include (⌫)">
<T>Exclude</T>
</Button>
<div className={styles.root} onKeyDown={onKeyDown}>
<FindActions tab={tab} roots={roots} canExclude={selection.size > 0} onExclude={exclude} />
<div ref={body} className={styles.body}>
<div className={styles.summary}>
{(st.status === "searching" || busy) && <Spinner size={16} variant="spokes" />}
<span className={styles.count}>
{st.status === "invalid" || st.status === "error"
? (st.error ?? tx("Search failed"))
: progress
? tx`Replacing… ${progress.done}/${progress.total} files`
: t(st.summary?.limitHit ? "search.find.matchesIncomplete" : "search.find.matches", {
matches: st.matchCount,
files: st.files.length,
}) + (marks.excluded.size ? ` · ${tx`${marks.excluded.size} excluded`}` : "")}
</span>
</div>
<SplitGroup
orientation={showPreview && stacked ? "vertical" : "horizontal"}
className={styles.split}
id="find-results-split"
storageKey={showPreview ? previewLayout : undefined}
>
<SplitPanel id="results" minSize={showPreview ? minPanelSize : undefined} className={styles.splitPanel}>
<Tree<Node>
className={styles.tree}
aria-label="Find results"
handleRef={tree}
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => (n.kind === "dir" ? n.label : n.kind === "file" ? n.name : n.text)}
getChildren={(n) => (n.kind === "match" ? undefined : n.children)}
isExpandable={(n) => n.kind !== "match"}
isOccurrence={(n) => n.kind === "match" && groupState(nodeGroups(n)[0]!, marks) !== "excluded"}
expanded={expanded}
onExpandedChange={(next) => {
const all = allExpandableKeys(roots);
setCollapsed(tab.id, new Set([...all].filter((k) => !next.has(k))));
}}
selected={selection}
onSelectionChange={(next, lead) => {
setSelection(next);
setLeadNode(lead);
if (tab.editorResults && lead?.kind === "match")
void openLocation(
lead.path,
{ line: lead.line, col: lead.col, endLine: lead.line, endCol: lead.endCol },
{ focus: false },
);
}}
multiSelect
onActivate={(n) => {
if (n.kind === "match")
void openLocation(
n.path,
{ line: n.line, col: n.col, endLine: n.line, endCol: n.endCol },
{ focus: true },
);
else if (n.kind === "file")
void openLocation(n.path, previewOf(n) ? { line: previewOf(n)!.line } : null);
}}
onContextMenu={(_n, sel, e) => {
const groups = [...sel].flatMap((k) => (byKey.get(k) ? nodeGroups(byKey.get(k)!) : []));
const excludedAll = groups.length > 0 && groups.every((g) => groupState(g, marks) === "excluded");
showContextMenu(e, [
...(_n?.kind === "match"
? menuGroupItems("searchResults", { paths: [_n.path], line: _n.line, column: _n.col })
: []),
{
id: "exclude",
label: excludedAll ? "Include" : "Exclude",
shortcut: "⌫",
disabled: !groups.length,
run: exclude,
},
...(replaceMode
? [
{
id: "replace",
label: "Replace Selected",
disabled: busy || !pendingUsages(groups, marks).length,
run: () => void replace(pendingUsages(groups, marks)),
},
{
id: "preview",
label: "Preview Replacement",
disabled: busy || !groups.length,
run: () => void previewReplace(),
},
]
: []),
]);
}}
activateExpandable={false}
renderNode={(n, s) => <FindNode node={n} state={s} tab={tab} marks={marks} />}
empty={
<span className={styles.empty}>
{st.status === "searching" || st.status === "validating" ? "Searching…" : "No matches"}
</span>
}
/>
</SplitPanel>
{showPreview && (
<>
<SplitHandle aria-label={tx("Resize find preview")} />
<SplitPanel id="preview" minSize={minPanelSize} defaultSize="45%" className={styles.splitPanel}>
<CodePreview path={preview?.path ?? null} line={preview?.line ?? 0} highlights={highlights} />
</SplitPanel>
</>
)}
</SplitGroup>
{replaceMode && (
<>
<div className={styles.replaceActions}>
{running && (
<Button size="small" onClick={() => running.cancel()}>
<T>Stop</T>
@@ -428,102 +530,9 @@ function FindTabView({ tab }: { tab: FindTab }) {
>
<T>Replace All</T>
</Button>
</>
</div>
)}
</div>
<SplitGroup
orientation="horizontal"
className={styles.split}
id="find-results-split"
storageKey={showPreview ? "openidea.find.previewSplit" : undefined}
>
<SplitPanel id="results" minSize={120} className={styles.splitPanel}>
<Tree<Node>
className={styles.tree}
aria-label="Find results"
handleRef={tree}
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => (n.kind === "dir" ? n.label : n.kind === "file" ? n.name : n.text)}
getChildren={(n) => (n.kind === "match" ? undefined : n.children)}
isExpandable={(n) => n.kind !== "match"}
isOccurrence={(n) => n.kind === "match" && groupState(nodeGroups(n)[0]!, marks) !== "excluded"}
expanded={expanded}
onExpandedChange={(next) => {
const all = allExpandableKeys(roots);
setCollapsed(tab.id, new Set([...all].filter((k) => !next.has(k))));
}}
selected={selection}
onSelectionChange={(next, lead) => {
setSelection(next);
setLeadNode(lead);
if (tab.editorResults && lead?.kind === "match")
void openLocation(
lead.path,
{ line: lead.line, col: lead.col, endLine: lead.line, endCol: lead.endCol },
{ focus: false },
);
}}
multiSelect
onActivate={(n) => {
if (n.kind === "match")
void openLocation(
n.path,
{ line: n.line, col: n.col, endLine: n.line, endCol: n.endCol },
{ focus: true },
);
else if (n.kind === "file") void openLocation(n.path, previewOf(n) ? { line: previewOf(n)!.line } : null);
}}
onContextMenu={(_n, sel, e) => {
const groups = [...sel].flatMap((k) => (byKey.get(k) ? nodeGroups(byKey.get(k)!) : []));
const excludedAll = groups.length > 0 && groups.every((g) => groupState(g, marks) === "excluded");
showContextMenu(e, [
...(_n?.kind === "match"
? menuGroupItems("searchResults", { paths: [_n.path], line: _n.line, column: _n.col })
: []),
{
id: "exclude",
label: excludedAll ? "Include" : "Exclude",
shortcut: "⌫",
disabled: !groups.length,
run: exclude,
},
...(replaceMode
? [
{
id: "replace",
label: "Replace Selected",
disabled: busy || !pendingUsages(groups, marks).length,
run: () => void replace(pendingUsages(groups, marks)),
},
{
id: "preview",
label: "Preview Replacement",
disabled: busy || !groups.length,
run: () => void previewReplace(),
},
]
: []),
]);
}}
activateExpandable={false}
renderNode={(n, s) => <FindNode node={n} state={s} tab={tab} marks={marks} />}
empty={
<span className={styles.empty}>
{st.status === "searching" || st.status === "validating" ? "Searching…" : "No matches"}
</span>
}
/>
</SplitPanel>
{showPreview && (
<>
<SplitHandle />
<SplitPanel id="preview" minSize={120} defaultSize="45%" className={styles.splitPanel}>
<CodePreview path={preview?.path ?? null} line={preview?.line ?? 0} highlights={highlights} />
</SplitPanel>
</>
)}
</SplitGroup>
</div>
);
}
@@ -555,7 +564,11 @@ function FindNodeContent({ node, state, tab }: { node: Node; state: TreeRowState
<Icon name={fileIconName(node.name)} size={16} className={styles.icon} />
<span className={styles.label}>{node.name}</span>
<span className={styles.meta}>{node.count}</span>
{!state.depth && node.dir && <span className={styles.meta}>{node.dir}</span>}
{!state.depth && node.dir && (
<span className={styles.directory} title={node.dir}>
{node.dir}
</span>
)}
</span>
);
case "match":
@@ -577,15 +590,20 @@ function FindNodeContent({ node, state, tab }: { node: Node; state: TreeRowState
}
}
/** Header controls of the Find tool window. */
export function FindToolWindowActions() {
const tabs = useFindWindow((s) => s.tabs);
const activeId = useFindWindow((s) => s.active);
const tab = tabs.find((t) => t.id === activeId) ?? tabs[tabs.length - 1];
if (!tab) return null;
function FindActions({
tab,
roots,
canExclude,
onExclude,
}: {
tab: FindTab;
roots: readonly Node[];
canExclude: boolean;
onExclude: () => void;
}) {
const searching = tab.state.status === "searching";
return (
<>
<div className={styles.toolbar} role="toolbar" aria-orientation="vertical" aria-label={tx("Find actions")}>
<IconButton icon="arrow-up" action="navigate.prevOccurrence" size="small" />
<IconButton icon="arrow-down" action="navigate.nextOccurrence" size="small" />
{searching ? (
@@ -604,14 +622,10 @@ export function FindToolWindowActions() {
icon="collapse-all"
title="Collapse All"
size="small"
onClick={() =>
setCollapsed(
tab.id,
allExpandableKeys(buildFindTree(tab.state.files, useFindViewOptions.getState().groupByDirectory)),
)
}
onClick={() => setCollapsed(tab.id, allExpandableKeys(roots))}
/>
<IconButton icon="minus" title="Exclude / include (⌫)" size="small" disabled={!canExclude} onClick={onExclude} />
<IconButton icon="close" title="Close Tab" size="small" onClick={() => closeFindTab(tab.id)} />
</>
</div>
);
}
-1
Переглянути файл
@@ -221,7 +221,6 @@ export function activate(): void | (() => void) {
order: 5,
component: lazyComponent(() => import("./find/FindToolWindow").then((m) => m.FindToolWindow)),
headerContent: lazyComponent(() => import("./find/FindToolWindow").then((m) => m.FindTabs)),
headerActions: lazyComponent(() => import("./find/FindToolWindow").then((m) => m.FindToolWindowActions)),
headerMenu: useFindHeaderMenu,
}),
+61
Переглянути файл
@@ -0,0 +1,61 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const backend = vi.hoisted(() => ({
snapshot: vi.fn(),
op: vi.fn(),
remove: vi.fn(),
}));
vi.mock("@tauri-apps/api/core", () => ({ Channel: class {} }));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: {
dockerSnapshot: backend.snapshot,
dockerContainerOp: backend.op,
dockerRemove: backend.remove,
},
}));
import type { DockerContainer } from "@/platform/ipc";
import type { DockerTarget } from "./model";
import { canRestart, canStart, canStop, restart, start, targetBusy } from "./ops";
import { busyOp, containerOp, useServices } from "./store";
const ok = <T>(data: T) => ({ status: "ok" as const, data });
const box = { id: "box", name: "Box", endpoint: { kind: "default" } };
const container = { id: "c1", name: "web", state: "exited", status: "Exited (0)" } as DockerContainer;
const target: DockerTarget = { conn: "box", node: { kind: "container", key: "container:c1", container } };
beforeEach(() => {
for (const f of Object.values(backend)) f.mockReset();
backend.snapshot.mockResolvedValue(ok({ availability: { kind: "ready", context: null }, errors: [] }));
useServices.setState({ settings: { connections: [box], registries: [] } as never, conns: {}, task: null });
});
describe("container operations in progress", () => {
it("disable the container's actions until the snapshot after them has loaded", async () => {
let finish!: () => void;
backend.op.mockReturnValue(new Promise((resolve) => (finish = () => resolve(ok(null)))));
const running = start(target);
await vi.waitFor(() => expect(backend.op).toHaveBeenCalledTimes(1));
expect(busyOp("box", ["c1"])).toBe("start");
expect(targetBusy(target)).toBe("start");
expect([canStart(target), canStop(target), canRestart(target)]).toEqual([false, false, false]);
// A second click while the first runs does nothing.
await restart(target);
expect(backend.op).toHaveBeenCalledTimes(1);
finish();
await running;
expect(backend.snapshot).toHaveBeenCalled();
expect(busyOp("box", ["c1"])).toBeNull();
expect(canStart(target)).toBe(true);
});
it("release the container when the operation fails", async () => {
backend.op.mockRejectedValue(new Error("daemon gone"));
expect(await containerOp("box", ["c1"], "stop")).toBe(false);
expect(busyOp("box", ["c1"])).toBeNull();
});
});
+63 -21
Переглянути файл
@@ -37,9 +37,21 @@ import {
treeKey,
type DockerTarget,
} from "./model";
import { canRemove, canRestart, canStart, canStop, execShell, remove, restart, showDetail, start, stop } from "./ops";
import {
canRemove,
canRestart,
canStart,
canStop,
execShell,
remove,
restart,
showDetail,
start,
stop,
targetBusy,
} from "./ops";
import { openContainerLogInEditor } from "./logEditor";
import { containerOp, endpointOf, errorMessage } from "./store";
import { containerOp, endpointOf, errorMessage, useServices } from "./store";
import { useServicesTree } from "./tree";
import styles from "./Services.module.css";
@@ -658,6 +670,26 @@ function ContainerLinkChip({ conn, container }: { conn: string; container: Docke
// ---------------------------------------------------------------------------
// Container Dashboard & Processes View
/** A dashboard action button that shows a spinner while its operation runs. */
function OpButton({
busy,
disabled,
onClick,
children,
}: {
busy: boolean;
disabled: boolean;
onClick: () => void;
children: string;
}) {
return (
<Button size="small" disabled={disabled} aria-busy={busy || undefined} onClick={onClick}>
{busy && <Spinner size={12} />}
<T>{children}</T>
</Button>
);
}
export function ContainerDashboard({
conn,
container,
@@ -674,6 +706,7 @@ export function ContainerDashboard({
conn,
node: { kind: "container", key: `container:${container.id}`, container },
};
const busy = useServices((s) => targetBusy(target, s));
const inspect = useMemo(() => parseContainerInspect(inspectText, container.ports), [inspectText, container.ports]);
const ports = useMemo(() => inspect?.ports ?? parsePortMappings(container.ports), [inspect, container.ports]);
const matchedImage = useMemo(() => findImageForContainer(snapshot, container), [snapshot, container]);
@@ -708,25 +741,33 @@ export function ContainerDashboard({
return (
<div className={styles.dashboard} tabIndex={0} onKeyDown={copySelectionOnKeyDown}>
<div className={styles.dashboardActions}>
<Button size="small" disabled={!canStart(target)} onClick={() => void start(target)}>
<OpButton busy={busy === "start"} disabled={!canStart(target)} onClick={() => void start(target)}>
Start
</Button>
<Button size="small" disabled={!canStop(target)} onClick={() => void stop(target)}>
</OpButton>
<OpButton busy={busy === "stop"} disabled={!canStop(target)} onClick={() => void stop(target)}>
Stop
</Button>
<Button size="small" disabled={!canRestart(target)} onClick={() => void restart(target)}>
</OpButton>
<OpButton busy={busy === "restart"} disabled={!canRestart(target)} onClick={() => void restart(target)}>
Restart
</Button>
</OpButton>
{container.state === "paused" ? (
<Button size="small" onClick={() => void containerOp(conn, [container.id], "unpause")}>
<OpButton
busy={busy === "unpause"}
disabled={!!busy}
onClick={() => void containerOp(conn, [container.id], "unpause")}
>
Unpause
</Button>
</OpButton>
) : (
<Button size="small" disabled={!running} onClick={() => void containerOp(conn, [container.id], "pause")}>
<OpButton
busy={busy === "pause"}
disabled={!running || !!busy}
onClick={() => void containerOp(conn, [container.id], "pause")}
>
Pause
</Button>
</OpButton>
)}
<Button size="small" disabled={!running} onClick={() => execShell(target)}>
<Button size="small" disabled={!running || !!busy} onClick={() => execShell(target)}>
Create Terminal
</Button>
<Button size="small" onClick={() => showDetail("log")}>
@@ -735,9 +776,9 @@ export function ContainerDashboard({
<Button size="small" onClick={() => openContainerLogInEditor(conn, container)}>
Open Log in Editor
</Button>
<Button size="small" disabled={!canRemove(target)} onClick={() => void remove(target)}>
<OpButton busy={busy === "remove"} disabled={!canRemove(target)} onClick={() => void remove(target)}>
Delete…
</Button>
</OpButton>
</div>
<SectionBanner>
@@ -1543,21 +1584,22 @@ export function ComposeProjectDashboard({
conn,
node: { kind: "compose", key: `compose:${project}`, project, containers },
};
const busy = useServices((s) => targetBusy(target, s));
const first = containers[0];
const runningCount = containers.filter(isRunning).length;
return (
<div className={styles.dashboard} tabIndex={0} onKeyDown={copySelectionOnKeyDown}>
<div className={styles.dashboardActions}>
<Button size="small" disabled={!canStart(target)} onClick={() => void start(target)}>
<OpButton busy={busy === "start"} disabled={!canStart(target)} onClick={() => void start(target)}>
Start
</Button>
<Button size="small" disabled={!canStop(target)} onClick={() => void stop(target)}>
</OpButton>
<OpButton busy={busy === "stop"} disabled={!canStop(target)} onClick={() => void stop(target)}>
Stop
</Button>
<Button size="small" disabled={!canRestart(target)} onClick={() => void restart(target)}>
</OpButton>
<OpButton busy={busy === "restart"} disabled={!canRestart(target)} onClick={() => void restart(target)}>
Restart
</Button>
</OpButton>
<Button size="small" disabled={!canRemove(target)} onClick={() => void remove(target)}>
Compose Down
</Button>
+19 -4
Переглянути файл
@@ -9,6 +9,7 @@ import { promptText } from "./dialogs";
import { openContainerLogInEditor } from "./logEditor";
import { isRunning, nodeContainers, nodeLabel, shortId, type DockerTarget, type ServiceNode } from "./model";
import {
busyOp,
composeOp,
connectionState,
containerOp,
@@ -21,17 +22,31 @@ import {
type DetailTab,
} from "./store";
/**
* The operation in progress on `t`: a start / stop / … of its containers, or for a
* Compose project a running Docker task. Its actions stay disabled until it ends.
*/
export function targetBusy(t: DockerTarget | null, s = useServices.getState()): string | null {
if (!t) return null;
if (t.node.kind === "compose" && s.task) return "task";
return busyOp(
t.conn,
nodeContainers(t.node).map((c) => c.id),
s,
);
}
export function canStart(t: DockerTarget | null): boolean {
return !!t && nodeContainers(t.node).some((c) => !isRunning(c));
return !!t && !targetBusy(t) && nodeContainers(t.node).some((c) => !isRunning(c));
}
export function canStop(t: DockerTarget | null): boolean {
return !!t && nodeContainers(t.node).some(isRunning);
return !!t && !targetBusy(t) && nodeContainers(t.node).some(isRunning);
}
export function canRestart(t: DockerTarget | null): boolean {
return !!t && (t.node.kind === "container" || t.node.kind === "compose");
return !!t && !targetBusy(t) && (t.node.kind === "container" || t.node.kind === "compose");
}
export function canRemove(t: DockerTarget | null): boolean {
return !!t && ["container", "compose", "image", "volume", "network"].includes(t.node.kind);
return !!t && !targetBusy(t) && ["container", "compose", "image", "volume", "network"].includes(t.node.kind);
}
export async function start(t: DockerTarget | null) {
+39 -2
Переглянути файл
@@ -60,6 +60,8 @@ export interface ConnectionState {
error: string | null;
/** Disconnected for this session: no snapshots, events or polling until Connect. */
disconnected?: boolean;
/** Containers with a start / stop / … / remove in progress, by id: the operation. */
busy?: Record<string, ContainerOp | "remove">;
}
interface DockerState {
@@ -381,6 +383,38 @@ async function guarded(connId: string, title: string, run: () => Promise<unknown
}
}
/** The operation in progress on any of `ids`, if one is. */
export function busyOp(connId: string, ids: readonly string[], s = useServices.getState()) {
const busy = connectionState(connId, s).busy;
for (const id of ids) if (busy?.[id]) return busy[id];
return null;
}
/**
* Runs `op` on containers no other operation holds, marking them busy until the
* snapshot after it has loaded, so their actions stay disabled meanwhile.
*/
async function holding(connId: string, ids: string[], op: ContainerOp | "remove", run: () => Promise<boolean>) {
if (busyOp(connId, ids)) return false;
const mark = (on: boolean) =>
useServices.setState((s) => {
const busy = { ...connectionState(connId, s).busy };
for (const id of ids) {
if (on) busy[id] = op;
else delete busy[id];
}
return { conns: { ...s.conns, [connId]: { ...connectionState(connId, s), busy } } };
});
mark(true);
try {
const ok = await run();
await refresh(connId).catch(() => undefined);
return ok;
} finally {
mark(false);
}
}
export function containerOp(connId: string, ids: string[], op: ContainerOp): Promise<boolean> {
const failure = {
start: tx("Could not start container"),
@@ -390,7 +424,9 @@ export function containerOp(connId: string, ids: string[], op: ContainerOp): Pro
unpause: tx("Could not unpause container"),
kill: tx("Could not kill container"),
}[op];
return guarded(connId, failure, () => call(commands.dockerContainerOp(endpointOf(connId), ids, op)));
return holding(connId, ids, op, () =>
guarded(connId, failure, () => call(commands.dockerContainerOp(endpointOf(connId), ids, op))),
);
}
export function removeObjects(connId: string, object: DockerObject, ids: string[], force: boolean): Promise<boolean> {
@@ -400,7 +436,8 @@ export function removeObjects(connId: string, object: DockerObject, ids: string[
volume: tx("Could not remove volume"),
network: tx("Could not remove network"),
}[object];
return guarded(connId, failure, () => call(commands.dockerRemove(endpointOf(connId), object, ids, force)));
const run = () => guarded(connId, failure, () => call(commands.dockerRemove(endpointOf(connId), object, ids, force)));
return object === "container" ? holding(connId, ids, "remove", run) : run();
}
/** Runs a streaming operation, showing its latest output line in the view's banner. */
+21 -7
Переглянути файл
@@ -247,6 +247,7 @@ const APPEARANCE = editorPage({
keywords: ["caret", "line numbers", "whitespace", "indent guides", "distraction free", "zen"],
sections: [
{
title: "Caret",
items: [
{
t: "check",
@@ -269,6 +270,11 @@ const APPEARANCE = editorPage({
],
},
},
],
},
{
title: "Code Structure",
items: [
{
t: "check",
key: `${P}.appearance.hardWrapGuides`,
@@ -289,6 +295,17 @@ const APPEARANCE = editorPage({
},
},
{ t: "check", key: `${P}.appearance.methodSeparators`, label: "Show method separators" },
{
t: "check",
key: `${P}.appearance.indentGuides`,
label: "Show indent guides",
children: [{ t: "check", key: `${P}.appearance.rainbowIndentGuides`, label: "Rainbow indent guides" }],
},
],
},
{
title: "Presentation",
items: [
{
t: "check",
key: `${P}.showWhitespace`,
@@ -299,13 +316,6 @@ const APPEARANCE = editorPage({
{ t: "check", key: `${P}.appearance.whitespaceTrailing`, label: "Trailing" },
],
},
{
t: "check",
key: `${P}.appearance.indentGuides`,
label: "Show indent guides",
children: [{ t: "check", key: `${P}.appearance.rainbowIndentGuides`, label: "Rainbow indent guides" }],
},
{ t: "check", key: `${P}.appearance.intentionBulb`, label: "Show intention bulb" },
{
t: "check",
key: `${P}.appearance.renderDocComments`,
@@ -321,6 +331,10 @@ const APPEARANCE = editorPage({
},
],
},
{
title: "Code Assistance",
items: [{ t: "check", key: `${P}.appearance.intentionBulb`, label: "Show intention bulb" }],
},
],
});
+5
Переглянути файл
@@ -643,6 +643,11 @@ export const VCS_PAGES: PageSpec[] = [
{
title: "Commit Message Generation",
options: [
{
kind: "toggle",
key: "vcs.commit.agentButton",
label: "Show the Generate Commit Message with Agent button",
},
{
kind: "custom",
label: "Agent",
+20 -6
Переглянути файл
@@ -26,7 +26,14 @@ import {
} from "@/ui";
import { useRowHeight } from "@/ui/density";
import type { PopupAnchor } from "@/ui/Popup";
import { buildBranchRows, preferredBranchRow, withExpanded, type BranchRow, type PopupAction } from "./branches";
import {
buildBranchRows,
preferredBranchRow,
scopedExpansion,
withExpanded,
type BranchRow,
type PopupAction,
} from "./branches";
import { branchPresentation, extensionPopupActions, useBranchWidgetExtensions } from "./branchWidgetExtensions";
import { branchMenu, commonBranchMenu, inRepo, tagMenu } from "./branchMenu";
import { loadFavoriteBranches, recentBranches, toggleFavoriteBranch, useFavoriteBranches } from "./branchOps";
@@ -262,12 +269,19 @@ function loadExpansion(root: string | null) {
useExpansion.setState(next);
}
function useExpanded(kind: "single" | "multi") {
const expanded = useExpansion((s) => s[kind]);
/**
* The expansion of one popup kind. `repo` scopes it to one repository's branches (a
* repository's submenu in a multi-repository project), so expanding a group there leaves
* the other repositories' submenus as they were.
*/
function useExpanded(kind: "single" | "multi", repo?: string) {
const all = useExpansion((s) => s[kind]);
const prefix = repo === undefined ? "" : `${repo}\u0000`;
const expanded = useMemo(() => scopedExpansion(all, prefix), [all, prefix]);
const setOpen = (key: string, open: boolean) => {
const s = useExpansion.getState();
if (s[kind].get(key) === open) return;
const next = { ...s, [kind]: withExpanded(s[kind], key, open) };
if (s[kind].get(prefix + key) === open) return;
const next = { ...s, [kind]: withExpanded(s[kind], prefix + key, open) };
useExpansion.setState(next);
if (!next.root) return;
try {
@@ -459,7 +473,7 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack }
const conflicts = useVcs((s) => s.status.filter((f) => f.unstaged === "conflicted").length);
const actions = useMemo(() => [...operationActions(op, conflicts), ...baseActions], [op, conflicts, baseActions]);
const options = usePopupOptions();
const [expanded, setOpen] = useExpanded("single");
const [expanded, setOpen] = useExpanded("single", root);
const rows = useMemo(
() => buildBranchRows(branches, recent, query, actions, favorites, tags, { ...options, expanded }),
[branches, recent, query, actions, favorites, tags, options, expanded],
+19
Переглянути файл
@@ -9,6 +9,7 @@ import {
isFavoriteBranch,
preferredBranchRow,
pushRecent,
scopedExpansion,
type BranchRow,
type BranchTreeNode,
} from "../branches";
@@ -323,3 +324,21 @@ describe("remote web URLs", () => {
expect(commitWebUrl("[email protected]:o/r.git", "abc")).toBe("https://bitbucket.org/o/r/commits/abc");
});
});
describe("scopedExpansion", () => {
it("keeps each repository's submenu expansion apart from the others and the project's", () => {
const all = new Map([
["group:remote", false],
["/r/alpha\u0000group:remote", true],
["/r/alpha\u0000folder:remote:origin/feature", true],
["/r/beta\u0000group:local", false],
]);
expect([...scopedExpansion(all, "/r/alpha\u0000")]).toEqual([
["group:remote", true],
["folder:remote:origin/feature", true],
]);
expect([...scopedExpansion(all, "/r/beta\u0000")]).toEqual([["group:local", false]]);
expect([...scopedExpansion(all, "/r/gamma\u0000")]).toEqual([]);
expect([...scopedExpansion(all, "")]).toEqual([["group:remote", false]]);
});
});
+33 -1
Переглянути файл
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { EditorSelection, EditorState } from "@codemirror/state";
import type { LineHunk } from "@/bindings";
import { applyRollback, hunkAtLine, hunkKeys, hunksOverlapping, nextHunk, prevHunk, rollbackEdit } from "../hunks";
@@ -132,6 +132,38 @@ describe("change lane clicks", () => {
setHunkPopupHooks(null);
parent.remove();
});
it("opens a deletion from the hit area above its line", async () => {
const { EditorView } = await import("@codemirror/view");
const { changeLane } = await import("@/editor/core/cm/lanes");
const { changeMarkers, setHunkPopupHooks } = await import("../gutter");
const opened: string[] = [];
setHunkPopupHooks({ open: (_v, hunk) => opened.push(hunk.kind), docChanged: () => {} });
const parent = document.createElement("div");
document.body.appendChild(parent);
const view = new EditorView({
parent,
state: EditorState.create({
doc: "a\nc\n",
extensions: [changeLane, changeMarkers({ path: "/p/f.txt" } as Parameters<typeof changeMarkers>[0])],
}),
});
view.dispatch({ effects: setHunksEffect.of([h("deleted", 1, 0, 1, 1, "b\n")]) });
const lane = view.dom.querySelector<HTMLElement>(".cm-openidea-lane")!;
vi.spyOn(lane, "getBoundingClientRect").mockReturnValue({ left: 100, right: 104, top: 0, bottom: 100 } as DOMRect);
const marker = view.dom.querySelector<HTMLElement>(".cm-openidea-laneDeleted")!;
vi.spyOn(marker, "getBoundingClientRect").mockReturnValue({ left: 96, top: 14, width: 12, height: 12 } as DOMRect);
const previous = view.lineBlockAt(view.state.doc.line(1).from);
const deleted = view.lineBlockAt(view.state.doc.line(2).from);
vi.spyOn(view, "lineBlockAtHeight").mockImplementation((height) => (height < 20 ? previous : deleted));
marker.dispatchEvent(
new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0, clientX: 96, clientY: 17 }),
);
expect(opened).toEqual(["deleted"]);
view.destroy();
setHunkPopupHooks(null);
parent.remove();
});
});
describe("change markers in folds", () => {
+37
Переглянути файл
@@ -437,6 +437,43 @@ describe("current line decoration", () => {
expect(label()!.style.left).toBe("");
});
it("steps past a folded chip drawn after its anchor, including one that appears later", async () => {
// jsdom has no layout: the chip's width is faked like the hint boxes above.
class FakeChip extends WidgetType {
toDOM() {
const el = document.createElement("span");
el.className = "cm-foldPlaceholder";
el.getBoundingClientRect = () => ({ width: 18 }) as DOMRect;
return el;
}
}
const lens = new Compartment();
view = new EditorView({
parent: document.body,
state: EditorState.create({ doc: "one\ntwo\nthree", extensions: [inlineBlame(ctx), lens.of([])] }),
});
await tick();
await vi.advanceTimersByTimeAsync(10);
expect(label()!.style.left).toBe("");
// The chip lands after the blame's anchor only in a later update (the fold happens after
// the blame mounted): the blame must still step past it. Side 3 mirrors the production DOM
// order, where CodeMirror draws the fold's replace widget after the side-1/2 anchors.
view.dispatch({
effects: lens.reconfigure(
EditorView.decorations.of(Decoration.set([Decoration.widget({ widget: new FakeChip(), side: 3 }).range(3)])),
),
});
await vi.advanceTimersByTimeAsync(10);
// chip 18px: 3ch gap + chip
expect(label()!.style.left).toBe("calc(3ch + 18px)");
// and it gives the space back when the fold expands again
view.dispatch({ effects: lens.reconfigure([]) });
await vi.advanceTimersByTimeAsync(10);
expect(label()!.style.left).toBe("");
});
it("is an out-of-flow, zero-width anchor so soft wrap cannot fold it onto a new row", () => {
const anchor = inlineBlameTheme[".cm-vcs-inline-blame"];
const inner = inlineBlameTheme[".cm-vcs-inline-blame-inner"];
+10
Переглянути файл
@@ -46,6 +46,16 @@ export interface BranchTreeOptions {
showTags?: boolean;
}
/** The entries of `all` under `prefix` (without it); unprefixed entries when `prefix` is empty. */
export function scopedExpansion(all: ReadonlyMap<string, boolean>, prefix: string): ReadonlyMap<string, boolean> {
const out = new Map<string, boolean>();
for (const [key, open] of all) {
const scoped = key.indexOf("\u0000");
if (prefix ? key.startsWith(prefix) : scoped < 0) out.set(key.slice(prefix.length), open);
}
return out;
}
/** Copy of `expanded` with `key` set to `open`. */
export function withExpanded(expanded: ReadonlyMap<string, boolean>, key: string, open: boolean): Map<string, boolean> {
return new Map(expanded).set(key, open);
+4 -29
Переглянути файл
@@ -2,7 +2,7 @@
import { useEffect, useId, useState } from "react";
import type { FileStatus, Stash } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { Checkbox, Dialog, Icon, IconButton, Input, T, fileIconName } from "@/ui";
import { Checkbox, Dialog, IconButton, Input, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { addedThenDeleted, groupOf, remainingOverrides, renamedFromPath } from "./changes";
import { runCommitChecks } from "./commitChecks";
@@ -12,10 +12,11 @@ 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 { baseName, effectiveKind, stripSlash } from "./model";
import { logConsole, runOp, saveAll } from "./ops";
import { ensureCommitIdentity } from "./commitIdentity";
import { showCompareRevisions } from "./operations";
import { FileChecklist } from "./shelf";
import { currentRepo, loadStashes, refreshNow, useVcs } from "./store";
import styles from "./common.module.css";
import { tx } from "@/platform/i18n";
@@ -216,7 +217,6 @@ export function showRollbackDialog(files: FileStatus[]) {
}
function RollbackDialog({ files, onClose }: { files: FileStatus[]; onClose: () => void }) {
const root = useVcs((s) => s.root) ?? "";
const [selected, setSelected] = useState(() => new Set(files.map((f) => f.path)));
const [deleteAdded, setDeleteAdded] = useState(false);
const hasAdded = files.some((f) => f.staged === "added");
@@ -256,32 +256,7 @@ function RollbackDialog({ files, onClose }: { files: FileStatus[]; onClose: () =
? tx`${selected.size} of ${files.length} file will be reverted to their last committed state. Uncommitted changes are lost.`
: tx`${selected.size} of ${files.length} files will be reverted to their last committed state. Uncommitted changes are lost.`}
</div>
<div className={styles.fileList} role="group" aria-label={tx("Files to roll back")}>
{files.map((f) => {
const kind = effectiveKind(f) ?? "modified";
return (
<div key={f.path} className={styles.fileRow}>
<Checkbox
aria-label={tx`Include ${baseName(f.path)}`}
checked={selected.has(f.path)}
onChange={(v) =>
setSelected((s) => {
const n = new Set(s);
if (v) n.add(f.path);
else n.delete(f.path);
return n;
})
}
/>
<Icon name={fileIconName(baseName(f.path), f.path)} size={14} />
<span className={styles.fileName} style={{ color: KIND_COLOR[kind] }}>
{baseName(f.path)}
</span>
<span className={styles.fileDir}>{dirName(relTo(root, stripSlash(f.path)))}</span>
</div>
);
})}
</div>
<FileChecklist files={files} selected={selected} onChange={setSelected} label="Files to roll back" />
<div style={{ height: 12 }} />
</Dialog>
);
+10 -5
Переглянути файл
@@ -235,14 +235,19 @@ const laneTheme = EditorView.baseTheme({
*/
export function laneMouseDown(view: EditorView, event: MouseEvent, path: string): boolean {
if (event.button !== 0 || event.shiftKey || event.metaKey || event.ctrlKey || event.altKey) return false;
const deletedMarker = event.target instanceof Element ? event.target.closest(".cm-openidea-laneDeleted") : null;
const lane = view.dom.querySelector(".cm-openidea-lane");
if (!lane) return false;
const rect = lane.getBoundingClientRect();
if (event.clientX < rect.left - 1 || event.clientX > rect.right + 3) return false;
if (event.clientY < rect.top || event.clientY > rect.bottom) return false;
const block = view.lineBlockAtHeight(event.clientY - view.documentTop);
if (!deletedMarker) {
const rect = lane.getBoundingClientRect();
if (event.clientX < rect.left - 1 || event.clientX > rect.right + 3) return false;
if (event.clientY < rect.top || event.clientY > rect.bottom) return false;
}
const markerRect = deletedMarker?.getBoundingClientRect();
const y = markerRect ? markerRect.top + markerRect.height / 2 + 1 : event.clientY;
const block = view.lineBlockAtHeight(y - view.documentTop);
const hunk = hunkAtPos(view.state, block.from);
if (!hunk) return false;
if (!hunk || (deletedMarker && hunk.kind !== "deleted")) return false;
event.preventDefault();
event.stopPropagation();
showHunkPopup(view, hunk, path);
+9 -8
Переглянути файл
@@ -10,6 +10,7 @@ import {
} from "@codemirror/view";
import type { BlameLine } from "@/bindings";
import { HEAVY_LIMIT, onEditorEvent, type EditorDocContext } from "@/editor/api";
import { foldChipWidth } from "@/editor/core/cm/folding";
import { executeAction } from "@/platform/actions";
import { tx, useI18n } from "@/platform/i18n";
import { call, commands, isTauri } from "@/platform/ipc";
@@ -126,19 +127,19 @@ class BlameWidget extends WidgetType {
}
/**
* Line-end annotations stack left to right: the code-vision hint, every plugin's line-end
* message, then this label. All of them are zero-width anchors with an absolutely positioned
* inner box (see codeLens.ts, decorations.module.css), so none takes part in the line's flow
* and a soft wrap can never fold one onto a new visual row. Each message steps past its
* predecessors itself, so this one steps past the whole chain, as IDEA lays its line-end
* inlays out. They can also appear (or go away) after this widget mounted, hence the observer
* below.
* Line-end annotations stack left to right: a folded chip drawn after this anchor, the
* code-vision hint, every plugin's line-end message, then this label. All of them are
* zero-width anchors with an absolutely positioned inner box (see codeLens.ts,
* decorations.module.css), so none takes part in the line's flow and a soft wrap can never
* fold one onto a new visual row. Each message steps past its predecessors itself, so this one
* steps past the whole chain, as IDEA lays its line-end inlays out. They can also appear (or
* go away) after this widget mounted, hence the observer below.
*/
private stepPastLineEnd(el: HTMLElement) {
const line = el.closest(".cm-line");
const inner = el.firstElementChild as HTMLElement | null;
if (!line || !inner) return;
let width = 0;
let width = foldChipWidth(el);
const hint = line.querySelector<HTMLElement>(".cm-openidea-lensInlineInner");
// The hint's inner box sits its anchor's `--openidea-hint-offset` past that anchor.
if (hint) width += Math.round(hint.getBoundingClientRect().width) + offsetOf(hint, "--openidea-hint-offset");
+14 -1
Переглянути файл
@@ -12,6 +12,7 @@
"Resize file type panes": "Resize file type panes",
"Problems actions": "Problems actions",
"TODO actions": "TODO actions",
"Resize paste preview": "Resize paste preview",
"Same as the existing configuration '{existing}'": "Same as the existing configuration '{existing}'",
"Windows file and folder names cannot end with a period or space": "Windows file and folder names cannot end with a period or space",
"Use URL template": "Use URL template",
@@ -137,6 +138,11 @@
"Pinned": "Pinned",
"Models": "Models",
"Effort Level": "Effort Level",
"Model settings": "Model settings",
"Model settings: {summary}": "Model settings: {summary}",
"Back to models": "Back to models",
"No settings reported for this model.": "No settings reported for this model.",
"The model changed before its setting could be applied.": "The model changed before its setting could be applied.",
"Context Size": "Context Size",
"Free": "Free",
"Low cost": "Low cost",
@@ -2259,6 +2265,7 @@
"Finished": "Finished",
"Only while the tab cannot be seen. A command stopped with Ctrl-C, shell startup and short commands stay quiet; a non-zero exit always reports its code.": "Only while the tab cannot be seen. A command stopped with Ctrl-C, shell startup and short commands stay quiet; a non-zero exit always reports its code.",
"Generate Commit Message with Agent": "Generate Commit Message with Agent",
"Show the Generate Commit Message with Agent button": "Show the Generate Commit Message with Agent button",
"Has the coding agent you work with review the changes about to be committed and write the commit message.": "Has the coding agent you work with review the changes about to be committed and write the commit message.",
"No changes to describe": "No changes to describe",
"Include changes in the commit first.": "Include changes in the commit first.",
@@ -2716,5 +2723,11 @@
"Remove All Watches": "Remove All Watches",
"GitHub account": "GitHub account",
"Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.",
"github-username": "github-username"
"github-username": "github-username",
"Find actions": "Find actions",
"Resize find preview": "Resize find preview",
"Caret": "Caret",
"Code Structure": "Code Structure",
"Presentation": "Presentation",
"Code Assistance": "Code Assistance"
}
+13
Переглянути файл
@@ -126,6 +126,11 @@
"Unpin model": "取消置顶模型",
"Models": "模型",
"Effort Level": "思考强度",
"Model settings": "模型设置",
"Model settings: {summary}": "模型设置:{summary}",
"Back to models": "返回模型列表",
"No settings reported for this model.": "此模型未提供可配置的设置。",
"The model changed before its setting could be applied.": "应用设置前,所选模型已发生变化。",
"Context Size": "上下文大小",
"Free": "免费",
"Low cost": "低开销",
@@ -944,6 +949,7 @@
"Cannot undo": "无法撤消",
"Cannot undo refactoring": "无法撤消重构",
"Cannot preview replacements": "无法预览替换",
"Caret": "光标",
"Caret blinking (ms):": "光标闪烁(毫秒):",
"Caret column number (1-based)": "光标所在列号(从 1 开始)",
"Caret line number (1-based)": "光标所在行号(从 1 开始)",
@@ -1033,8 +1039,10 @@
"Close the window instead of showing the Welcome screen": "关闭窗口,而不是显示欢迎屏幕",
"Closing Policy": "关闭策略",
"Code": "代码",
"Code Assistance": "代码辅助",
"Code Completion": "代码补全",
"Code Editing": "代码编辑",
"Code Structure": "代码结构",
"Code Folding": "代码折叠",
"Code Style": "代码样式",
"Code breadcrumbs": "代码痕迹导航",
@@ -1480,6 +1488,7 @@
"Find Previous Occurrence": "查找上一个匹配项",
"Find Usages": "查找用法",
"Find Usages of File": "查找文件的用法",
"Find actions": "查找操作",
"Find actions by shortcut": "按快捷键查找操作",
"Find in Directory…": "在目录中查找…",
"Find in Files": "在文件中查找",
@@ -2160,6 +2169,7 @@
"Preserve Case": "保留大小写",
"Press a shortcut": "按下快捷键",
"Press a shortcut to find actions": "按下快捷键以查找操作",
"Presentation": "显示",
"Preview": "预览",
"Preview Diff": "预览差异",
"Preview Replacement": "预览替换",
@@ -2511,6 +2521,7 @@
"Reset IDE Zoom": "重置 IDE 缩放",
"Reset Shortcuts": "重置快捷键",
"Reset Zoom": "重置缩放",
"Resize find preview": "调整查找预览大小",
"Reset to Language Defaults": "重置为语言默认值",
"Comment Code": "注释代码",
"Line comment at first column": "在第一列添加行注释",
@@ -2963,6 +2974,7 @@
"Tests failed: {detail}": "测试失败:{detail}",
"TODO comment": "TODO 注释",
"TODO actions": "TODO 操作",
"Resize paste preview": "调整粘贴预览大小",
"TODO filters": "TODO 筛选器",
"TODO items": "TODO 项",
"TODO items unavailable": "TODO 项不可用",
@@ -8654,6 +8666,7 @@
"Exited with code {code}": "退出代码 {code}",
"Only while the tab cannot be seen. A command stopped with Ctrl-C, shell startup and short commands stay quiet; a non-zero exit always reports its code.": "仅当标签页不可见时通知。用 Ctrl-C 停止的命令、shell 启动和短命令保持安静;非零退出始终报告退出代码。",
"Generate Commit Message with Agent": "使用智能体生成提交消息",
"Show the Generate Commit Message with Agent button": "显示“使用智能体生成提交消息”按钮",
"Has the coding agent you work with review the changes about to be committed and write the commit message.": "让您正在使用的编程智能体审查即将提交的更改并撰写提交消息。",
"No changes to describe": "没有可描述的更改",
"Include changes in the commit first.": "请先在提交中包含更改。",
+4
Переглянути файл
@@ -69,6 +69,8 @@ export interface CommitSettingsValid {
agentModel: string;
/** That model's thinking level for commit messages; empty keeps the agent's. */
agentEffort: string;
/** Show the Generate Commit Message with Agent button above the commit message. */
agentButton: boolean;
}
export interface VcsSettingsValid {
@@ -316,6 +318,7 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
agent: "",
agentModel: "",
agentEffort: "",
agentButton: true,
},
confirmation: {
onCreate: "ask",
@@ -488,6 +491,7 @@ export function validateVcs(raw: unknown): VcsSettingsValid {
agent: text(c.agent, d.commit.agent),
agentModel: text(c.agentModel, d.commit.agentModel),
agentEffort: text(c.agentEffort, d.commit.agentEffort),
agentButton: bool(c.agentButton, d.commit.agentButton),
},
confirmation: {
onCreate: oneOf(conf.onCreate, confirm, d.confirmation.onCreate),
+2
Переглянути файл
@@ -158,6 +158,8 @@
.toastBody {
color: var(--fg-secondary);
overflow-wrap: anywhere;
/* Bodies list one item per line (compile errors, failed paths). */
white-space: pre-line;
/* A huge message (stack trace, build output) scrolls inside the balloon instead
of growing past the window and pushing the close button off-screen. */
max-height: 40vh;
+3
Переглянути файл
@@ -292,6 +292,9 @@ export function SelectListbox<V extends string = string>({
className={styles.rowAction}
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") e.stopPropagation();
}}
>
{action}
</span>