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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 205241c0b3 fix(notebook): Vim u and Ctrl-R undo and redo in notebook cells
Notebook cells have no CodeMirror history: source and structural edits
share the notebook's backend history, which Cmd+Z already uses. Vim's u /
Ctrl-R called CodeMirror's history and did nothing. An editor can now
provide externalHistory, and the Vim engine sends undo / redo there.
2026-11-16 00:11:25 +08:00
50 змінених файлів з 79 додано та 1207 видалено

No files matched your search

+10 -8
Переглянути файл
@@ -10,14 +10,12 @@ use crate::provider::ProviderSpec;
use crate::{Shared, client_info};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;
const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(3) } else { Duration::from_secs(120) };
/// Opens `session/new`, reads `configOptions`, and records the `thought_level` choices of the
/// session's model: they describe that model only, and other models may offer different ones.
/// Opens `session/new`, reads `configOptions`, and records per-model `thought_level` choices.
pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec) -> Result<Discovered, String> {
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
match run_once(shared, spec, prefer_stored).await {
@@ -64,17 +62,21 @@ async fn run_once(shared: &Arc<Shared>, spec: &ProviderSpec, strip_ambient: bool
.map_err(|e| e.to_string())?;
let mut options = config::options_of(&new);
config::add_client_options(&launch.id, &mut options);
let model = options.iter().find(|o| o.category.as_deref() == Some("model")).and_then(|o| o.current.clone());
let levels = match (model, levels_for_model_from_slice(&options)) {
(Some(model), Some(effort)) => BTreeMap::from([(model, effort)]),
_ => BTreeMap::new(),
let model_option = options.iter().find(|o| o.category.as_deref() == Some("model"));
let effort = levels_for_model_from_slice(&options);
let levels: Vec<(String, Vec<AgentConfigOption>)> = match (model_option, effort) {
(Some(model), Some(effort)) if !model.values.is_empty() => {
model.values.iter().map(|v| (v.value.clone(), effort.clone())).collect()
}
(Some(model), Some(effort)) => model.current.clone().map(|m| vec![(m, effort)]).unwrap_or_default(),
_ => Vec::new(),
};
let commands = updates
.commands
.lock()
.clone()
.or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, &launch.id)));
Ok::<_, String>(Discovered { config: options, commands, levels })
Ok::<_, String>(Discovered { config: options, commands, levels: levels.into_iter().collect() })
};
let result = tokio::time::timeout(DISCOVER_TIMEOUT, work).await;
peer.kill();
-2
Переглянути файл
@@ -58,8 +58,6 @@ fn client_capabilities() -> Value {
"terminal": false,
// Subagents as sessions of their own (ACP subagents RFD; v2 baseline).
"subagents": {},
// Forms the agent asks the user to fill in (`elicitation/create`); not URL mode.
"elicitation": { "form": {} },
// Cursor exposes model parameters (e.g. Composer `fast`) as separate config options
// only when the client advertises this flag (undocumented Cursor ACP extension).
"_meta": { "parameterizedModelPicker": true },
+1 -5
Переглянути файл
@@ -97,13 +97,10 @@ fn the_negotiating_request_carries_both_versions() {
p["clientCapabilities"]["_meta"]["parameterizedModelPicker"], true,
"Cursor and similar agents need parameterized model options (e.g. fast on/off)"
);
// Forms only: URL mode would open pages the agent names.
assert_eq!(p["clientCapabilities"]["elicitation"], json!({ "form": {} }));
// What we sent in the capture is what claude-agent-acp negotiated v2 and v1 from.
let sent = frames(TURN, "out")[0]["params"]["clientCapabilities"].clone();
let mut expected = sent;
expected["_meta"] = p["clientCapabilities"]["_meta"].clone();
expected["elicitation"] = p["clientCapabilities"]["elicitation"].clone();
assert_eq!(expected, p["clientCapabilities"]);
}
@@ -171,8 +168,7 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
let fast = cursor.config.iter().find(|o| o.id == "fast").expect("fast option");
assert_eq!(fast.category.as_deref(), Some("model_config"));
assert_eq!(fast.current.as_deref(), Some("false"));
// The effort option belongs to the session's model; m2 may offer other levels.
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
assert!(cursor.thought_levels.contains_key("m1") && cursor.thought_levels.contains_key("m2"));
assert!(cursor.thought_levels["m1"].iter().any(|o| o.category.as_deref() == Some("thought_level")));
}
+1 -53
Переглянути файл
@@ -56,16 +56,6 @@ pub(crate) struct CatalogData {
pub refreshed_at_ms: Option<f64>,
}
impl CatalogData {
fn model_option(&self) -> Option<&AgentConfigOption> {
self.config.iter().find(|o| o.category.as_deref() == Some("model"))
}
fn lists(&self, model: &str) -> bool {
self.model_option().is_some_and(|o| o.values.iter().any(|v| v.value == model))
}
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SavedCatalog {
@@ -339,17 +329,11 @@ impl AgentCatalogs {
Ok(found) => {
let mut cache = shared.known.lock();
let known = cache.entry(key.2.clone()).or_default();
let mut catalog = CatalogData {
let catalog = CatalogData {
config: found.config,
thought_levels: found.levels,
refreshed_at_ms: Some(self.epoch_ms()),
};
// Efforts sessions reported for models discovery doesn't read stay while listed.
for (model, levels) in entry.catalog.take().map(|old| old.thought_levels).unwrap_or_default() {
if catalog.lists(&model) && !catalog.thought_levels.contains_key(&model) {
catalog.thought_levels.insert(model, levels);
}
}
known.config = catalog.config.clone();
known.thought_levels = catalog.thought_levels.clone();
if let Some(commands) = found.commands {
@@ -382,42 +366,6 @@ impl AgentCatalogs {
}
}
/// Records the efforts a session reported for a listed `model` other than the one discovery
/// read: ACP discovery opens one session, so it knows only that model's efforts.
pub(crate) fn learn_levels(&self, shared: &Shared, provider: &str, model: &str, levels: Vec<AgentConfigOption>) {
let lacks = |catalog: &CatalogData| {
catalog.lists(model)
&& catalog.model_option().and_then(|o| o.current.as_deref()) != Some(model)
&& catalog.thought_levels.get(model) != Some(&levels)
};
let key = Self::key(shared, provider);
let mut state = self.state.lock();
let mut learned = false;
if let Some(catalog) = state.entries.get_mut(&key).and_then(|e| e.catalog.as_mut()).filter(|c| lacks(c)) {
catalog.thought_levels.insert(model.to_owned(), levels.clone());
learned = true;
}
let mut cache = shared.known.lock();
if let Some(saved) = cache
.get_mut(provider)
.and_then(|known| known.catalogs.get_mut(&shared.root_key()))
.filter(|saved| lacks(&saved.catalog))
{
saved.catalog.thought_levels.insert(model.to_owned(), levels);
learned = true;
}
if !learned {
return;
}
shared.persist_known(&cache);
drop(cache);
let snapshot = state.entries.get(&key).map(|entry| self.snapshot(shared, provider, entry));
drop(state);
if let Some(snapshot) = snapshot {
self.broadcast(shared, &snapshot);
}
}
fn subscribers(&self, shared: &Shared) -> Vec<Arc<Shared>> {
self.state
.lock()
+1 -38
Переглянути файл
@@ -199,8 +199,7 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
pending.reply.send(Ok(response(&["retained", "new"], &["medium"]))).unwrap();
let fresh = completed(&mut events).await;
assert_eq!(model_values(&fresh), ["retained", "new"]);
// The session's efforts describe its own model, not "new".
assert_eq!(fresh.thought_levels.keys().map(String::as_str).collect::<Vec<_>>(), ["retained"]);
assert_eq!(fresh.thought_levels.keys().map(String::as_str).collect::<Vec<_>>(), ["new", "retained"]);
assert_eq!(fresh.thought_levels["retained"][0].values[0].value, "medium");
assert!(fresh.refreshed_at_ms.is_some() && fresh.retry_at_ms.is_some());
manager.shared.remember(PROVIDER, Some(&old), None, Some("old"));
@@ -221,42 +220,6 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
assert!(!tmp.path().join("store").exists(), "refresh never creates tasks");
}
#[tokio::test]
async fn a_session_adds_the_efforts_of_a_model_discovery_did_not_read() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "one");
let mut harness = Harness::new();
let catalogs = Arc::new(AgentCatalogs::default());
let manager = make_manager(tmp.path(), catalogs.clone(), &harness);
let mut events = events(&manager);
manager.refresh_models(PROVIDER, false).unwrap();
harness.next().await.reply.send(Ok(response(&["first", "second"], &["low", "high"]))).unwrap();
completed(&mut events).await;
// A session on "second" reports its own efforts; one on a model the catalog lacks, or on
// "first" with other efforts, changes nothing.
let second = config::options_of(&response(&["second"], &["off", "auto"]));
manager.shared.remember(PROVIDER, Some(&second), None, Some("second"));
manager.shared.remember(PROVIDER, Some(&config::options_of(&response(&["gone"], &["x"]))), None, Some("gone"));
manager.shared.remember(PROVIDER, Some(&config::options_of(&response(&["first"], &["max"]))), None, Some("first"));
let efforts = |catalog: &AgentModelCatalog, model: &str| -> Vec<String> {
catalog.thought_levels[model][0].values.iter().map(|v| v.value.clone()).collect()
};
let catalog = manager.refresh_models(PROVIDER, false).unwrap();
assert_eq!(catalog.thought_levels.keys().map(String::as_str).collect::<Vec<_>>(), ["first", "second"]);
assert_eq!(efforts(&catalog, "first"), ["low", "high"]);
assert_eq!(efforts(&catalog, "second"), ["off", "auto"]);
let restored = make_manager(tmp.path(), Arc::default(), &harness).refresh_models(PROVIDER, false).unwrap();
assert_eq!(efforts(&restored, "second"), ["off", "auto"], "persisted with the project's catalog");
// Discovery again reads "first" only; "second" keeps what its session reported.
advance(&catalogs, 60);
while events.try_recv().is_ok() {}
manager.refresh_models(PROVIDER, true).unwrap();
harness.next().await.reply.send(Ok(response(&["first", "second"], &["medium"]))).unwrap();
let fresh = completed(&mut events).await;
assert_eq!(efforts(&fresh, "first"), ["medium"]);
assert_eq!(efforts(&fresh, "second"), ["off", "auto"]);
}
#[tokio::test]
async fn legacy_cache_loads_without_claiming_authoritative_freshness() {
let tmp = tempfile::tempdir().unwrap();
-250
Переглянути файл
@@ -1,250 +0,0 @@
//! ACP elicitation in form mode: the agent's restricted JSON Schema as form fields, and the
//! user's answer as the `elicitation/create` response.
use crate::model::{AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption};
use serde_json::{Map, Value, json};
/// The reply that declines the form; a JSON object of field name to values accepts it, and
/// anything else cancels it.
const DECLINE: &str = "decline";
/// The form `elicitation/create` asks for; `Err` when it asks for something else.
pub(crate) fn form_of(params: &Value) -> Result<AgentForm, String> {
if params.get("mode").and_then(Value::as_str) != Some("form") {
return Err("only form elicitation is supported".to_owned());
}
let schema = params.get("requestedSchema").ok_or("requestedSchema is missing")?;
let required: Vec<&str> = schema
.get("required")
.and_then(Value::as_array)
.map(|names| names.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
let properties = schema.get("properties").and_then(Value::as_object).ok_or("requestedSchema has no properties")?;
let fields = properties
.iter()
.map(|(name, property)| field(name, property, required.contains(&name.as_str())))
.collect::<Result<_, _>>()?;
Ok(AgentForm { fields })
}
fn field(name: &str, property: &Value, required: bool) -> Result<AgentFormField, String> {
let text = |key: &str| property.get(key).and_then(Value::as_str).unwrap_or_default().trim().to_owned();
let number = |key: &str| property.get(key).and_then(Value::as_f64);
let unsupported = || format!("field {name} has an unsupported schema");
let (kind, options, min, max) = match property.get("type").and_then(Value::as_str) {
Some("string") => match choices(property) {
Some(options) => (AgentFormFieldKind::Choice, options, None, None),
None => (AgentFormFieldKind::Text, Vec::new(), number("minLength"), number("maxLength")),
},
Some("number") => (AgentFormFieldKind::Number, Vec::new(), number("minimum"), number("maximum")),
Some("integer") => (AgentFormFieldKind::Integer, Vec::new(), number("minimum"), number("maximum")),
Some("boolean") => (AgentFormFieldKind::Boolean, Vec::new(), None, None),
Some("array") => {
let options = property.get("items").and_then(choices).ok_or_else(unsupported)?;
(AgentFormFieldKind::Choices, options, number("minItems"), number("maxItems"))
}
_ => return Err(unsupported()),
};
let default = match property.get("default") {
Some(Value::Array(values)) => values.iter().filter_map(scalar).collect(),
Some(value) => scalar(value).into_iter().collect(),
None => Vec::new(),
};
let title = text("title");
Ok(AgentFormField {
name: name.to_owned(),
title: if title.is_empty() { name.to_owned() } else { title },
description: text("description"),
required,
kind,
options,
default,
min,
max,
})
}
/// The values of a choice: `enum` (titled by the legacy `enumNames`), or `oneOf` / `anyOf`
/// of `{ const, title }`.
fn choices(schema: &Value) -> Option<Vec<AgentFormOption>> {
let option = |value: &str, label: Option<&str>, description: Option<&str>| AgentFormOption {
value: value.to_owned(),
label: label.filter(|l| !l.trim().is_empty()).unwrap_or(value).to_owned(),
description: description.unwrap_or_default().trim().to_owned(),
};
if let Some(values) = schema.get("enum").and_then(Value::as_array) {
let names = schema.get("enumNames").and_then(Value::as_array);
return Some(
values
.iter()
.enumerate()
.filter_map(|(i, value)| {
Some(option(value.as_str()?, names.and_then(|n| n.get(i)).and_then(Value::as_str), None))
})
.collect(),
);
}
let listed = schema.get("oneOf").or_else(|| schema.get("anyOf"))?.as_array()?;
Some(
listed
.iter()
.filter_map(|o| {
let text = |key: &str| o.get(key).and_then(Value::as_str);
Some(option(text("const")?, text("title"), text("description")))
})
.collect(),
)
}
fn scalar(value: &Value) -> Option<String> {
match value {
Value::String(text) => Some(text.clone()),
Value::Number(number) => Some(number.to_string()),
Value::Bool(flag) => Some(flag.to_string()),
_ => None,
}
}
/// A form is submitted from its own card; this option only names a declined form.
pub(crate) fn options() -> Vec<AgentPermissionOption> {
vec![AgentPermissionOption { id: DECLINE.to_owned(), name: "Decline".to_owned(), kind: "reject_once".to_owned() }]
}
/// The `elicitation/create` response to the user's `reply`, and what the conversation
/// records as chosen.
pub(crate) fn answer(form: &AgentForm, reply: Option<&str>) -> (Value, String) {
let values = match reply {
Some(DECLINE) => return (json!({ "action": "decline" }), "Decline".to_owned()),
Some(reply) => serde_json::from_str::<Map<String, Value>>(reply).ok(),
None => None,
};
let Some(values) = values else { return (json!({ "action": "cancel" }), "Cancelled".to_owned()) };
let mut content = Map::new();
let mut shown = Vec::new();
for field in &form.fields {
let given: Vec<&str> = match values.get(&field.name) {
Some(Value::Array(items)) => items.iter().filter_map(Value::as_str).collect(),
Some(Value::String(item)) => vec![item.as_str()],
_ => Vec::new(),
};
let given: Vec<&str> = given.into_iter().map(str::trim).filter(|v| !v.is_empty()).collect();
let Some(&first) = given.first() else { continue };
let value = match field.kind {
AgentFormFieldKind::Text | AgentFormFieldKind::Choice => json!(first),
AgentFormFieldKind::Number => match first.parse::<f64>() {
Ok(number) => json!(number),
Err(_) => continue,
},
AgentFormFieldKind::Integer => match first.parse::<i64>() {
Ok(number) => json!(number),
Err(_) => continue,
},
AgentFormFieldKind::Boolean => json!(first == "true"),
AgentFormFieldKind::Choices => json!(given),
};
let label = |value: &str| {
field.options.iter().find(|o| o.value == value).map_or_else(|| value.to_owned(), |o| o.label.clone())
};
let text = match field.kind {
AgentFormFieldKind::Boolean => (if first == "true" { "yes" } else { "no" }).to_owned(),
AgentFormFieldKind::Choices => given.iter().map(|v| label(v)).collect::<Vec<_>>().join(", "),
_ => label(first),
};
shown.push(format!("{}: {text}", field.title));
content.insert(field.name.clone(), value);
}
let chosen = if shown.is_empty() { "Submitted".to_owned() } else { shown.join("; ") };
(json!({ "action": "accept", "content": content }), chosen)
}
#[cfg(test)]
mod tests {
use super::*;
/// The form OMP's `ask` tool sends: a choice with a recommended default, then an
/// optional typed answer beside it.
fn ask() -> Value {
json!({
"sessionId": "s", "mode": "form", "message": "Which database?",
"requestedSchema": { "type": "object", "properties": {
"q0": { "type": "string", "title": "Which database?", "description": "Storage",
"oneOf": [{ "const": "pg", "title": "Postgres", "description": "Relational" },
{ "const": "sqlite", "title": "SQLite" }],
"default": "pg" },
"q0__other": { "type": "string", "title": "Other (type your own)" }
} }
})
}
#[test]
fn reads_choices_and_text_fields() {
let form = form_of(&ask()).unwrap();
let [choice, other] = form.fields.as_slice() else { panic!("{form:?}") };
assert_eq!((choice.name.as_str(), choice.kind, choice.required), ("q0", AgentFormFieldKind::Choice, false));
assert_eq!(choice.options[0].label, "Postgres");
assert_eq!(choice.options[0].description, "Relational");
assert_eq!(choice.default, ["pg"]);
assert_eq!((other.kind, other.title.as_str()), (AgentFormFieldKind::Text, "Other (type your own)"));
}
#[test]
fn reads_every_restricted_schema_kind() {
let form = form_of(&json!({ "mode": "form", "requestedSchema": {
"type": "object", "required": ["count"],
"properties": {
"count": { "type": "integer", "minimum": 1, "maximum": 5 },
"ratio": { "type": "number" },
"ok": { "type": "boolean", "default": true },
"size": { "type": "string", "enum": ["s", "l"], "enumNames": ["Small", "Large"] },
"tags": { "type": "array", "items": { "anyOf": [{ "const": "a" }, { "const": "b" }] },
"default": ["b"], "maxItems": 2 }
}
} }))
.unwrap();
let field = |name: &str| form.fields.iter().find(|f| f.name == name).unwrap();
use AgentFormFieldKind::*;
let kinds: Vec<_> = ["count", "ratio", "ok", "size", "tags"].map(|name| field(name).kind).into();
assert_eq!(kinds, [Integer, Number, Boolean, Choice, Choices]);
assert!(field("count").required && !field("ratio").required);
assert_eq!((field("count").min, field("count").max), (Some(1.0), Some(5.0)));
assert_eq!(field("ok").default, ["true"]);
assert_eq!(field("size").options[1].label, "Large");
assert_eq!((field("tags").default.as_slice(), field("tags").max), (["b".to_owned()].as_slice(), Some(2.0)));
}
#[test]
fn url_mode_and_unsupported_fields_are_refused() {
assert!(form_of(&json!({ "mode": "url", "url": "https://example.com" })).is_err());
let nested = json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
"address": { "type": "object" }
} } });
assert!(form_of(&nested).is_err());
}
#[test]
fn an_answer_is_typed_by_its_field() {
let form = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
"count": { "type": "integer" },
"ok": { "type": "boolean" },
"size": { "type": "string", "oneOf": [{ "const": "s", "title": "Small" }] },
"tags": { "type": "array", "items": { "enum": ["a", "b"] } },
"note": { "type": "string" }
} } }))
.unwrap();
let reply = json!({ "count": ["3"], "ok": ["false"], "size": ["s"], "tags": ["a", "b"], "note": [" "] });
let (response, chosen) = answer(&form, Some(&reply.to_string()));
assert_eq!(
response,
json!({ "action": "accept", "content": { "count": 3, "ok": false, "size": "s", "tags": ["a", "b"] } })
);
assert_eq!(chosen, "count: 3; ok: no; size: Small; tags: a, b");
}
#[test]
fn declining_and_dismissing_send_no_content() {
let form = form_of(&ask()).unwrap();
assert_eq!(answer(&form, Some(DECLINE)), (json!({ "action": "decline" }), "Decline".to_owned()));
assert_eq!(answer(&form, None).0, json!({ "action": "cancel" }));
assert_eq!(answer(&form, Some("cancel")).0, json!({ "action": "cancel" }));
}
}
+17 -66
Переглянути файл
@@ -11,7 +11,6 @@ mod acp;
mod catalogs;
mod config;
mod conversation;
mod elicitation;
mod external;
pub mod mcp;
mod model;
@@ -224,7 +223,6 @@ impl Shared {
commands: Option<&[AgentCommand]>,
model: Option<&str>,
) {
let acp = self.spec(provider).is_some_and(|spec| spec.driver == provider::Driver::Acp);
let mut cache = self.known.lock();
let known = cache.entry(provider.to_owned()).or_default();
let mut changed = false;
@@ -246,12 +244,6 @@ impl Shared {
changed = true;
}
}
// Discovery reads one model's efforts; a session on another model reports that model's.
let learned = model.filter(|_| acp && known.authoritative).zip(config).map(|(model, config)| {
let levels: Vec<_> =
config.iter().filter(|o| o.category.as_deref() == Some("thought_level")).cloned().collect();
(model, levels)
});
if let Some(commands) = commands.filter(|c| !c.is_empty())
&& known.commands.get(&self.root_key()).map(Vec::as_slice) != Some(commands)
{
@@ -262,9 +254,6 @@ impl Shared {
self.persist_known(&cache);
}
drop(cache);
if let Some((model, levels)) = learned.filter(|(_, levels)| !levels.is_empty()) {
self.paths.catalogs.learn_levels(self, provider, model, levels);
}
if changed {
self.emit(AgentEvent::Providers);
}
@@ -2389,7 +2378,12 @@ impl Task {
// first question says what it wants, as the Claude Code adapter titles its own.
let title =
if by_index { questions.first().map(|question| question.question.clone()).unwrap_or(title) } else { title };
let title = self.labelled(params, title);
// A subagent's request is answered in the task's conversation, named after the subagent.
let session = params.get("sessionId").and_then(Value::as_str);
let title = match session.and_then(|s| self.state.lock().conversation.label(s)) {
Some(label) => format!("{label}: {title}"),
None => title,
};
let options: Vec<AgentPermissionOption> = params
.get("options")
.and_then(Value::as_array)
@@ -2421,7 +2415,6 @@ impl Task {
command: None,
options,
questions: Vec::new(),
form: None,
chosen: Some("Denied: side conversations are read-only".to_owned()),
});
return match reject {
@@ -2448,7 +2441,6 @@ impl Task {
command: shown.clone(),
options,
questions: Vec::new(),
form: None,
chosen: Some(format!("Blocked by policy ({pattern})")),
});
return match reject {
@@ -2469,7 +2461,6 @@ impl Task {
command: shown.clone(),
options,
questions: Vec::new(),
form: None,
chosen: Some(format!("{} (whitelisted)", allow.name)),
});
return json!({ "outcome": { "outcome": "selected", "optionId": allow.id } });
@@ -2485,7 +2476,6 @@ impl Task {
command: shown,
options: options.clone(),
questions,
form: None,
chosen: None,
});
self.permissions.lock().insert(id, tx);
@@ -2512,7 +2502,17 @@ impl Task {
.and_then(|reply| options.iter().find(|option| &option.id == reply))
.map_or_else(|| "Cancelled".to_owned(), |option| option.name.clone()),
};
self.settle(entry, name);
{
let mut s = self.state.lock();
if let Some(AgentEntry::Permission { chosen, .. }) = s.conversation.main.entries.get_mut(entry) {
*chosen = Some(name);
}
}
self.mark_dirty([(None, entry)]);
let still_asking = !self.permissions.lock().is_empty();
if !still_asking && self.state.lock().task.status == AgentStatus::NeedsInput {
self.set_status(AgentStatus::Running, None);
}
// An agent that answers by index reads the answers beside the outcome, keyed by
// question index, with its Submit option chosen; anything less cancels the request.
if by_index {
@@ -2544,54 +2544,6 @@ impl Task {
}
}
/// A request from a subagent is answered in the task's conversation, named after the subagent.
fn labelled(&self, params: &Value, title: String) -> String {
let session = params.get("sessionId").and_then(Value::as_str);
match session.and_then(|s| self.state.lock().conversation.label(s)) {
Some(label) => format!("{label}: {title}"),
None => title,
}
}
/// An agent's form (`elicitation/create`): asked in the conversation like a permission
/// request, and answered with its values, declined or cancelled. Blocks like `ask_permission`.
fn elicit(self: &Arc<Self>, params: &Value) -> Result<Value, String> {
let form = elicitation::form_of(params)?;
let id = self.next_permission.fetch_add(1, Ordering::Relaxed);
let message = params.get("message").and_then(Value::as_str).unwrap_or_default().trim().to_owned();
let (tx, rx) = std::sync::mpsc::channel();
let entry = self.push_entry(AgentEntry::Permission {
id,
title: self.labelled(params, message),
command: None,
options: elicitation::options(),
questions: Vec::new(),
form: Some(form.clone()),
chosen: None,
});
self.permissions.lock().insert(id, tx);
self.set_status(AgentStatus::NeedsInput, None);
let reply = rx.recv().ok().flatten();
let (response, chosen) = elicitation::answer(&form, reply.as_deref());
self.settle(entry, chosen);
Ok(response)
}
/// Records the answer to the request at `entry`; the turn runs on once nothing else waits.
fn settle(self: &Arc<Self>, entry: usize, chosen: String) {
{
let mut s = self.state.lock();
if let Some(AgentEntry::Permission { chosen: answer, .. }) = s.conversation.main.entries.get_mut(entry) {
*answer = Some(chosen);
}
}
self.mark_dirty([(None, entry)]);
let still_asking = !self.permissions.lock().is_empty();
if !still_asking && self.state.lock().task.status == AgentStatus::NeedsInput {
self.set_status(AgentStatus::Running, None);
}
}
fn approve_pending(&self) {
let s = self.state.lock();
if self.cancel_pending.load(Ordering::Acquire) || !config::bypass_approvals(&s.task.config) {
@@ -2656,7 +2608,6 @@ impl Handler for Client {
let task = self.task.upgrade().ok_or((codes::INTERNAL_ERROR, "task closed".to_owned()))?;
match method {
"session/request_permission" => Ok(task.ask_permission(&params)),
"elicitation/create" => task.elicit(&params).map_err(|e| (codes::INVALID_PARAMS, e)),
_ => Err((codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
}
}
-57
Переглянути файл
@@ -316,59 +316,6 @@ pub struct AgentQuestionOption {
pub preview: Option<String>,
}
/// A form the agent asks the user to fill in (ACP `elicitation/create`, form mode).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentForm {
pub fields: Vec<AgentFormField>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentFormField {
/// The property name the answer is keyed by.
pub name: String,
pub title: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub required: bool,
pub kind: AgentFormFieldKind,
/// The choices of a `choice` or `choices` field.
#[serde(default)]
pub options: Vec<AgentFormOption>,
/// The initial answer: option values, a text, a number, or `true` / `false`.
#[serde(default)]
pub default: Vec<String>,
/// Bounds: the number of a `number` / `integer`, the length of a `text`, the count of `choices`.
#[serde(default)]
pub min: Option<f64>,
#[serde(default)]
pub max: Option<f64>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentFormFieldKind {
Text,
Number,
Integer,
Boolean,
/// One of `options`.
Choice,
/// Any of `options`.
Choices,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentFormOption {
pub value: String,
pub label: String,
#[serde(default)]
pub description: String,
}
/// One item of a task's conversation.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
@@ -449,10 +396,6 @@ pub enum AgentEntry {
/// of question to answer instead of an option.
#[serde(default)]
questions: Vec<AgentQuestion>,
/// Set when the agent asks for a form (ACP elicitation); answered with a JSON object of
/// field name to its values, `decline`, or nothing to cancel.
#[serde(default)]
form: Option<AgentForm>,
/// Name of the chosen option, or `None` while pending. Cancelled requests read "Cancelled".
chosen: Option<String>,
},
-69
Переглянути файл
@@ -295,23 +295,6 @@ impl Handler for FakeAgent {
self.say(&session, &format!("escalation chose {chosen}"));
return Ok(json!({"stopReason": "end_turn"}));
}
if text == "form" {
let peer = self.latest();
let answer: Value = tokio::runtime::Handle::current()
.block_on(peer.request(
"elicitation/create",
json!({"sessionId": session, "mode": "form", "message": "How should I refactor?",
"requestedSchema": {"type": "object", "required": ["strategy"], "properties": {
"strategy": {"type": "string", "title": "Strategy",
"oneOf": [{"const": "safe", "title": "Conservative"},
{"const": "bold", "title": "Aggressive"}]},
"tests": {"type": "boolean", "title": "Run tests"}}}}),
None,
))
.unwrap();
self.say(&session, &format!("form {answer}"));
return Ok(json!({ "stopReason": "end_turn" }));
}
if text == "ask" {
let peer = self.latest();
let answer: Value = tokio::runtime::Handle::current()
@@ -2052,58 +2035,6 @@ async fn bypass_approvals_keeps_both_question_dialects_pending_but_allows_permis
}
}
#[tokio::test(flavor = "multi_thread")]
async fn an_agent_form_is_answered_declined_or_cancelled_even_when_approvals_are_bypassed() {
let accept = json!({"strategy": ["bold"], "tests": ["true"]}).to_string();
for (reply, said, chosen) in [
(
Some(accept.as_str()),
r#"form {"action":"accept","content":{"strategy":"bold","tests":true}}"#,
"Strategy: Aggressive; Run tests: yes",
),
(Some("decline"), r#"form {"action":"decline"}"#, "Decline"),
(None, r#"form {"action":"cancel"}"#, "Cancelled"),
] {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("form"),
provider: "cursor".into(),
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let (id, form) = mgr
.entries(&task.id, None)
.unwrap()
.into_iter()
.find_map(|entry| match entry {
AgentEntry::Permission { id, title, form: Some(form), chosen: None, .. }
if title == "How should I refactor?" =>
{
Some((id, form))
}
_ => None,
})
.unwrap();
assert_eq!(form.fields.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["strategy", "tests"]);
mgr.respond(&task.id, id, reply.map(str::to_owned)).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id, None).unwrap();
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == said)), "{entries:?}");
assert!(
entries.iter().any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c == chosen)),
"{entries:?}"
);
mgr.shutdown();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_approval_choice_applies_before_first_prompt() {
let tmp = tempfile::tempdir().unwrap();
-1
Переглянути файл
@@ -441,7 +441,6 @@ mod tests {
command: None,
options: vec![],
questions: vec![],
form: None,
chosen: None,
});
assert_eq!(t.end_turn(None), vec![2, 3]);
-2
Переглянути файл
@@ -19,7 +19,6 @@ pub enum Tool {
Maven,
Gradle,
Ruby,
Zig,
}
impl Tool {
@@ -33,7 +32,6 @@ impl Tool {
Tool::Maven => &["maven"],
Tool::Gradle => &["gradle"],
Tool::Ruby => &["ruby"],
Tool::Zig => &["zig"],
}
}
}
-82
Переглянути файл
@@ -25,7 +25,6 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
SdkKind::Jdk => jdk(),
SdkKind::Maven => maven(),
SdkKind::Ruby => crate::ruby::detect(root),
SdkKind::Zig => zig(),
};
if let Some(root) = root {
pinned_first(&mut out, kind, root);
@@ -41,7 +40,6 @@ fn tool_of(kind: SdkKind) -> Option<Tool> {
SdkKind::Jdk => Some(Tool::Java),
SdkKind::Maven => Some(Tool::Maven),
SdkKind::Ruby => Some(Tool::Ruby),
SdkKind::Zig => Some(Tool::Zig),
SdkKind::Php | SdkKind::PackageManager | SdkKind::Rust | SdkKind::TypeScript => None,
}
}
@@ -741,86 +739,6 @@ fn go() -> Vec<Sdk> {
})
}
// ------------------------------------------------------------------ zig
/// The directory holding the `zig` executable of the install rooted at `base`,
/// the way the common distributions lay it out: `zig` at the root (official
/// tarballs, mise / asdf installs), `<base>/bin/zig` (Homebrew) or one
/// directory down (zvm's nested version folders).
fn zig_dir(base: &Path) -> Option<PathBuf> {
if base.join(exe("zig")).is_file() {
return Some(base.to_path_buf());
}
let bin = base.join(bin_dir());
if bin.join(exe("zig")).is_file() {
return Some(bin);
}
subdirs(base).into_iter().find(|d| d.join(exe("zig")).is_file())
}
/// Zig toolchains: PATH, Homebrew, zvm and mise / asdf installs. `path` is the
/// directory holding `zig`, which is what `languages.zig.zig` stores.
fn zig() -> Vec<Sdk> {
let mut roots: Vec<(PathBuf, &'static str)> = Vec::new();
if let Some(bin) = which("zig").filter(|p| !version_managers::is_shim(p))
&& let Some(dir) = bin.parent()
{
roots.push((dir.to_path_buf(), "path"));
}
for p in ["/opt/homebrew/opt/zig", "/usr/local/opt/zig"] {
roots.push((PathBuf::from(p), "system"));
}
if let Some(home) = home_dir() {
for d in subdirs(&home.join(".zvm")) {
roots.push((d, "zvm"));
}
}
for (d, manager) in version_managers::installs(Tool::Zig) {
roots.push((d, manager));
}
let mut dirs: Vec<(PathBuf, &'static str)> =
roots.into_iter().filter_map(|(base, source)| zig_dir(&base).map(|dir| (dir, source))).collect();
let mut seen = HashSet::new();
dirs.retain(|(dir, _)| seen.insert(dir.canonicalize().unwrap_or_else(|_| dir.clone())));
par_map(&dirs, |(dir, source)| {
let version = query(&dir.join(exe("zig")), &["version"], VERSION_TIMEOUT).map(|v| v.trim().to_owned());
Some(Sdk {
path: dir.clone().into(),
name: format!("Zig {}", version.as_deref().unwrap_or_default()).trim().to_owned(),
version,
source: (*source).to_owned(),
home: Some(dir.clone().into()),
extra: None,
})
})
}
#[cfg(test)]
mod zig_tests {
use super::*;
#[test]
fn finds_the_zig_directory_of_each_layout() {
let tmp = tempfile::tempdir().unwrap();
let install = |rel: &str| {
let dir = tmp.path().join(rel);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(exe("zig")), "").unwrap();
dir
};
// Official tarballs and mise / asdf installs: `zig` at the root.
let root = install("0.14.1");
assert_eq!(zig_dir(&root), Some(root));
// Homebrew: <opt>/bin/zig.
let brew = install("brew/bin");
assert_eq!(zig_dir(brew.parent().unwrap()), Some(brew));
// zvm: one directory down.
let zvm = install("zvm/x");
assert_eq!(zig_dir(&tmp.path().join("zvm")), Some(zvm));
assert_eq!(zig_dir(&tmp.path().join("missing")), None);
}
}
// ------------------------------------------------------------------ typescript
/// `node_modules/typescript/lib` of the project (root or a direct workspace member).
-2
Переглянути файл
@@ -52,8 +52,6 @@ pub enum SdkKind {
/// Maven homes.
Maven,
Ruby,
/// Zig toolchain directories.
Zig,
}
/// One installed interpreter / toolchain.
-10
Переглянути файл
@@ -61,9 +61,6 @@ fn mise_and_asdf_installs_are_detected_and_pinned_versions_used() {
script(&maven.join("bin/mvn"), "Apache Maven 3.9.6");
write(&maven.join("lib/maven-core-3.9.6.jar"), "");
script(&installs.join("gradle/8.7/bin/gradle"), "Gradle 8.7");
// Zig: asdf keeps the executable at the install root, zvm under ~/.zvm.
script(&asdf.join("installs/zig/0.14.1/zig"), "0.14.1");
script(&tmp.join("home/.zvm/0.13.0/zig"), "0.13.0");
let project = tmp.join("project");
write(
@@ -94,13 +91,6 @@ fn mise_and_asdf_installs_are_detected_and_pinned_versions_used() {
let mvn = find(&mavens, &maven);
assert_eq!((mvn.source.as_str(), mvn.version.as_deref()), ("mise", Some("3.9.6")));
let zigs = detect(SdkKind::Zig, Some(&project));
let zig = find(&zigs, &asdf.join("installs/zig"));
assert_eq!((zig.source.as_str(), zig.version.as_deref()), ("asdf", Some("0.14.1")));
assert_eq!(zig.path, asdf.join("installs/zig/0.14.1"), "the setting stores the directory");
let zvm = find(&zigs, &tmp.join("home/.zvm"));
assert_eq!((zvm.source.as_str(), zvm.version.as_deref()), ("zvm", Some("0.13.0")));
// Nothing configured in Settings: the pinned versions apply.
let s = Settings::default();
let jdk = ide_sdk::apply::project_jdk(&project, &s).expect("pinned JDK");
+1 -1
Переглянути файл
@@ -43,7 +43,7 @@ User-visible text is written in English at the call site and goes through the te
## WebKit compatibility
On macOS and Linux the app runs in WebKit, and the supported floor is Safari 15.4, the engine of macOS 12 (the app's minimum). `pnpm build` runs `scripts/check-webkit.ts` on the bundle, and `src/platform/webkitCompatibility.test.ts` checks application regexes. Avoid:
On macOS and Linux the app runs in WebKit, and the supported floor is Safari 16, the engine of macOS 13 (on macOS 11 and 12 a Safari update doesn't update the engine other apps use). `pnpm build` runs `scripts/check-webkit.ts` on the bundle, and `src/platform/webkitCompatibility.test.ts` checks application regexes. Avoid:
- regex lookbehind (`(?<=…)`, `(?<!…)`), which needs Safari 16.4, and the regex `v` flag;
- import attributes;
+1 -1
Переглянути файл
@@ -117,7 +117,7 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
| **Go to Next Splitter** | `⌥⇥` | `Alt+Tab` |
| **Go to Previous Splitter** | `⌥⇧⇥` | `Alt+Shift+Tab` |
**Window › Editor Tabs** also offers **Split Down**, **Unsplit**, **Unsplit All**, **Move to Opposite Group**, **Open in Opposite Group** and **Change Splitter Orientation**. You can also drag a tab to an edge of the editor area to split it. In the Project view, **Open in Right Split** (`⇧↵` / `Shift+Enter`, also in the context menu) opens the selected file in the split to the right.
**Window › Editor Tabs** also offers **Split Down**, **Unsplit**, **Unsplit All**, **Move to Opposite Group**, **Open in Opposite Group** and **Change Splitter Orientation**. You can also drag a tab to an edge of the editor area to split it.
## View options
+1 -1
Переглянути файл
@@ -9,7 +9,7 @@ In the file names below, `<version>` is the release version, for example `0.1.40
## macOS
macOS 12 Monterey or later.
macOS 13 Ventura or later.
| Mac | File |
| ------------- | -------------------------------- |
+1 -1
Переглянути файл
@@ -43,7 +43,7 @@ description: "前端 UI 代码的规则:设计 token、CSS Modules、图标、
## WebKit 兼容性
在 macOS 和 Linux 上应用运行于 WebKit,最低支持 Safari 15.4,即 macOS 12 的引擎(应用的最低系统版本)。`pnpm build` 会对产物运行 `scripts/check-webkit.ts`,`src/platform/webkitCompatibility.test.ts` 会检查应用中的正则。请避免:
在 macOS 和 Linux 上应用运行于 WebKit,最低支持 Safari 16,即 macOS 13 的引擎(macOS 11、12 上更新 Safari 不会更新其他应用使用的引擎)。`pnpm build` 会对产物运行 `scripts/check-webkit.ts`,`src/platform/webkitCompatibility.test.ts` 会检查应用中的正则。请避免:
- 正则后行断言(`(?<=…)`、`(?<!…)`,需要 Safari 16.4)和正则 `v` 标志;
- import attributes;
+1 -1
Переглянути файл
@@ -117,7 +117,7 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
| **转到下一个拆分器** | `⌥⇥` | `Alt+Tab` |
| **转到上一个拆分器** | `⌥⇧⇥` | `Alt+Shift+Tab` |
**窗口 › 编辑器标签页** 中还有 **向下拆分**、**取消拆分**、**全部取消拆分**、**移动到另一组**、**在相对组中打开** 和 **更改拆分方向**。也可以把标签页拖到编辑区的某一侧边缘来拆分。在 Project 视图中,**在右侧拆分中打开**(`⇧↵` / `Shift+Enter`,右键菜单中也有)会把选中的文件打开到右侧拆分中。
**窗口 › 编辑器标签页** 中还有 **向下拆分**、**取消拆分**、**全部取消拆分**、**移动到另一组**、**在相对组中打开** 和 **更改拆分方向**。也可以把标签页拖到编辑区的某一侧边缘来拆分。
## 显示选项
+1 -1
Переглянути файл
@@ -9,7 +9,7 @@ description: "在 macOS、Windows 或 Linux 上下载并安装 OpenIDEA,以及
## macOS
需要 macOS 12 Monterey 或更高版本。
需要 macOS 13 Ventura 或更高版本。
| Mac | 文件 |
| ---------- | -------------------------------- |
+12 -6
Переглянути файл
@@ -13,7 +13,7 @@
details: "启动错误详情",
timeout: "启动未在 60 秒内完成。",
outdatedMac:
"这台 Mac 的系统网页引擎过旧:OpenIDEA 的界面运行在 macOS 自带的 WebKit 引擎上,需要 macOS 12 Monterey 或更高版本(引擎为 Safari 15.4 或更新)。更旧的系统缺少应用所需的引擎,需要升级 macOS。",
"这台 Mac 的系统网页引擎过旧:OpenIDEA 的界面运行在 macOS 自带的 WebKit 引擎上,需要 macOS 13 Ventura 或更高版本。在 macOS 11、12 上更新 Safari 不会更新其他应用使用的引擎,需要升级 macOS。",
outdated:
"系统的 WebKitGTK 版本过旧:OpenIDEA 需要较新的 WebKitGTK(webkit2gtk-4.1)。请通过系统的包管理器更新后重新打开 OpenIDEA。",
}
@@ -27,14 +27,20 @@
details: "Startup error details",
timeout: "Startup did not finish within 60 seconds.",
outdatedMac:
"The system web engine on this Mac is too old: OpenIDEA's interface runs on macOS's built-in WebKit and needs macOS 12 Monterey or later (Safari 15.4 or newer). Older macOS releases lack the engine the app needs, so macOS itself needs upgrading.",
"The system web engine on this Mac is too old: OpenIDEA's interface runs on macOS's built-in WebKit and needs macOS 13 Ventura or later. On macOS 11 and 12 a Safari update doesn't update the engine other apps use, so macOS itself needs upgrading.",
outdated:
"The system's WebKitGTK is too old: OpenIDEA needs a recent WebKitGTK (webkit2gtk-4.1). Update it with your package manager, then open OpenIDEA again.",
};
// The bundle targets Safari 15.4 (vite.config.ts), so an older system web engine can't
// even parse it. structuredClone came with Safari 15.4, and WebKit's user agent doesn't
// name its version.
const outdated = () => typeof structuredClone !== "function";
// The bundle targets Safari 16 (vite.config.ts); an older system web engine can't even
// parse it. Container queries came with Safari 16, and WebKit's user agent doesn't name
// its version. Unknown (no CSS.supports) counts as current.
const outdated = () => {
try {
return typeof window.CSS?.supports === "function" && !window.CSS.supports("container-type", "inline-size");
} catch {
return false;
}
};
let failed = false;
let ready = false;
const describe = (reason) => {
+1 -5
Переглянути файл
@@ -10,16 +10,12 @@ it.each([
"Object.groupBy(items, key)",
"Array.fromAsync(items)",
"text.toWellFormed()",
"input.showPicker()",
'Intl.supportedValuesOf("collator")',
"items.toSorted(compare)",
"path.toReversed()",
'new RegExp("[a-z]", "v")',
'RegExp("(?<=a)b")',
"/[a-z]/v",
"/(?<!a)b/",
'import data from "./data.json" with { type: "json" }',
])("rejects %s in the Safari 15.4 startup graph", (source) => {
])("rejects %s in the Safari 16 startup graph", (source) => {
expect(checkSource(source, true).length).toBeGreaterThan(0);
});
+4 -13
Переглянути файл
@@ -3,7 +3,7 @@ import { dirname, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import ts from "typescript";
// Safari 15.4 is the bundle's floor, macOS 12's engine (the app's minimum). Keep this floor in sync with vite.config.ts.
// Safari 16 is macOS 13's system engine (the app's minimum). Keep this floor in sync with vite.config.ts.
// Syntax lowering does not replace newer runtime APIs in dependencies.
const newerStatics = new Set([
"Promise.withResolvers",
@@ -15,16 +15,7 @@ const newerStatics = new Set([
"Uint8Array.fromBase64",
"Uint8Array.fromHex",
]);
const newerMethods = new Set([
"isWellFormed",
"toWellFormed",
// Safari 16 / 16.4 APIs above the floor.
"showPicker",
"supportedValuesOf",
"toSorted",
"toReversed",
"toSpliced",
]);
const newerMethods = new Set(["isWellFormed", "toWellFormed"]);
export function checkSource(source: string, startup: boolean): string[] {
const tree = ts.createSourceFile("bundle.js", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
@@ -93,6 +84,6 @@ export function checkBuild(dir: string): string[] {
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
const errors = checkBuild(resolve("dist"));
if (errors.length) throw new Error(`Safari 15.4 compatibility check failed:\n${errors.join("\n")}`);
console.log("Safari 15.4 startup API and bundle syntax checks passed");
if (errors.length) throw new Error(`Safari 16 compatibility check failed:\n${errors.join("\n")}`);
console.log("Safari 16 startup API and bundle syntax checks passed");
}
+1 -1
Переглянути файл
@@ -41,7 +41,7 @@
"longDescription": "OpenIDEA is an open-source IDE inspired by IntelliJ IDEA. Not affiliated with JetBrains.",
"macOS": {
"entitlements": "./Entitlements.plist",
"minimumSystemVersion": "12.0"
"minimumSystemVersion": "13.0"
}
},
"mainBinaryName": "openidea",
+1 -41
Переглянути файл
@@ -2056,11 +2056,6 @@ command?: string | null; options: AgentPermissionOption[];
* of question to answer instead of an option.
*/
questions?: AgentQuestion[];
/**
* Set when the agent asks for a form (ACP elicitation); answered with a JSON object of
* field name to its values, `decline`, or nothing to cancel.
*/
form?: AgentForm | null;
/** Name of the chosen option, or `None` while pending. Cancelled requests read "Cancelled". */
chosen: string | null } | { type: "error"; message: string };
@@ -2084,39 +2079,6 @@ export type AgentEvent =
/** The installed or configured agent providers changed. */
{ type: "providers" };
/** A form the agent asks the user to fill in (ACP `elicitation/create`, form mode). */
export type AgentForm = {
fields: AgentFormField[],
};
export type AgentFormField = {
/** The property name the answer is keyed by. */
name: string,
title: string,
description?: string,
required?: boolean,
kind: AgentFormFieldKind,
/** The choices of a `choice` or `choices` field. */
options?: AgentFormOption[],
/** The initial answer: option values, a text, a number, or `true` / `false`. */
default?: string[],
/** Bounds: the number of a `number` / `integer`, the length of a `text`, the count of `choices`. */
min?: number | null,
max?: number | null,
};
export type AgentFormFieldKind = "text" | "number" | "integer" | "boolean" |
/** One of `options`. */
"choice" |
/** Any of `options`. */
"choices";
export type AgentFormOption = {
value: string,
label: string,
description?: string,
};
export type AgentImage = {
mimeType: string,
/** Base64, without a `data:` prefix. */
@@ -9665,9 +9627,7 @@ export type SdkKind = "python" | "node" |
/** JDK homes. */
"jdk" |
/** Maven homes. */
"maven" | "ruby" |
/** Zig toolchain directories. */
"zig";
"maven" | "ruby";
/**
* IDEA's search context: matches anywhere, only in, or outside comments and
-183
Переглянути файл
@@ -1,183 +0,0 @@
import { useId, useState } from "react";
import type { AgentForm, AgentFormField, AgentTask } from "@/bindings";
import { Button, Checkbox, Input, Radio, T } from "@/ui";
import type { PermissionEntry } from "./permission";
import { respond } from "./store";
import styles from "./Session.module.css";
/** Each field's answer as the backend reads it: option values, a text, a number, or `true` / `false`. */
type Values = Record<string, string[]>;
const within = (field: AgentFormField, n: number) =>
(field.min == null || n >= field.min) && (field.max == null || n <= field.max);
function isValid(field: AgentFormField, value: string[]) {
const given = value.map((item) => item.trim()).filter(Boolean);
if (!given.length) return !field.required;
switch (field.kind) {
case "number":
case "integer": {
const n = Number(given[0]);
return Number.isFinite(n) && (field.kind === "number" || Number.isInteger(n)) && within(field, n);
}
case "text":
return within(field, given[0]!.length);
case "choices":
return within(field, given.length);
default:
return true;
}
}
/** An agent's open form (ACP elicitation), answered above the composer like a question. */
export function FormCard({ task, entry, form }: { task: AgentTask; entry: PermissionEntry; form: AgentForm }) {
const [values, setValues] = useState<Values>(() =>
Object.fromEntries(
form.fields.map((field) => [
field.name,
field.kind === "boolean" ? [String(field.default?.[0] === "true")] : (field.default ?? []),
]),
),
);
const [busy, setBusy] = useState(false);
const complete = form.fields.every((field) => isValid(field, values[field.name] ?? []));
// `decline` declines the form, nothing cancels it, and the values accept it.
const send = (reply: string | null) => {
setBusy(true);
void respond(task.id, entry.id, reply).finally(() => setBusy(false));
};
return (
<form
className={styles.questionCard}
aria-label={entry.title}
onSubmit={(event) => {
event.preventDefault();
if (complete) send(JSON.stringify(values));
}}
onKeyDown={(event) => {
if (event.key === "Escape") send(null);
}}
>
{/* A one-question form often titles its field with the message; it is shown once, as the field's. */}
{entry.title && !form.fields.some((field) => field.title === entry.title) && (
<p className={styles.formMessage}>{entry.title}</p>
)}
<fieldset className={styles.formFields} disabled={busy}>
{form.fields.map((field) => (
<FormField
key={field.name}
field={field}
value={values[field.name] ?? []}
onChange={(value) => setValues({ ...values, [field.name]: value })}
/>
))}
</fieldset>
<div className={styles.questionActions}>
<Button variant="ghost" disabled={busy} onClick={() => send(null)}>
Cancel
</Button>
<Button disabled={busy} onClick={() => send("decline")}>
Decline
</Button>
<Button type="submit" variant="primary" disabled={busy || !complete}>
Submit
</Button>
</div>
</form>
);
}
function FormField({
field,
value,
onChange,
}: {
field: AgentFormField;
value: string[];
onChange: (value: string[]) => void;
}) {
const id = useId();
const title = (
<>
{field.title}
{field.required && (
<span className={styles.questionTag}>
<T>Required</T>
</span>
)}
</>
);
const description = field.description && <span className={styles.questionDescription}>{field.description}</span>;
const optionLabel = (label: string, about?: string) => (
<span className={styles.questionOptionText}>
<span className={styles.questionLabel}>{label}</span>
{about && <span className={styles.questionDescription}>{about}</span>}
</span>
);
if (field.kind === "boolean") {
return (
<div className={styles.question}>
<div className={styles.questionChoices}>
<Checkbox
className={styles.questionOption}
checked={value[0] === "true"}
label={optionLabel(field.title, field.description)}
onChange={(checked) => onChange([String(checked)])}
/>
</div>
</div>
);
}
if (field.kind === "choice" || field.kind === "choices") {
return (
<fieldset className={styles.question}>
<legend className={styles.questionText}>{title}</legend>
{description}
<div className={styles.questionChoices}>
{(field.options ?? []).map((option) =>
field.kind === "choices" ? (
<Checkbox
key={option.value}
className={styles.questionOption}
checked={value.includes(option.value)}
label={optionLabel(option.label, option.description)}
onChange={(checked) =>
onChange(checked ? [...value, option.value] : value.filter((v) => v !== option.value))
}
/>
) : (
<Radio
key={option.value}
className={styles.questionOption}
name={id}
checked={value[0] === option.value}
label={optionLabel(option.label, option.description)}
onChange={() => onChange([option.value])}
/>
),
)}
</div>
</fieldset>
);
}
const numeric = field.kind !== "text";
return (
<div className={styles.question}>
<label className={styles.questionText} htmlFor={id}>
{title}
</label>
<Input
id={id}
type={numeric ? "number" : "text"}
inputMode={field.kind === "integer" ? "numeric" : numeric ? "decimal" : undefined}
step={field.kind === "integer" ? 1 : numeric ? "any" : undefined}
min={numeric ? (field.min ?? undefined) : undefined}
max={numeric ? (field.max ?? undefined) : undefined}
maxLength={numeric ? undefined : (field.max ?? undefined)}
invalid={value.some((item) => item.trim()) && !isValid(field, value)}
value={value[0] ?? ""}
onChange={(event) => onChange([event.target.value])}
/>
</div>
);
}
-16
Переглянути файл
@@ -1762,22 +1762,6 @@
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
/* An agent's form (ACP elicitation): its message, then every field at once, in the question card. */
.formMessage {
margin: 0;
color: var(--fg-strong);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.formFields {
display: flex;
flex-direction: column;
gap: var(--space-3);
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
/* Reasoning while it streams (auto): bounded, its tail in view. */
.thoughtLive .thoughtBody {
+9 -8
Переглянути файл
@@ -97,9 +97,7 @@ import {
type Activity,
} from "./workingStatus";
import { AgentReply, MessageActions, ReplyActions } from "./AgentReply";
import { FormCard } from "./FormCard";
import {
asksInCard,
commandPrefix,
permissionDetails,
permissionOption,
@@ -2307,7 +2305,9 @@ function PermissionLine({ task, entry }: { task: AgentTask; entry: PermissionEnt
) : (
<span className={styles.permissionDetail}>{shortTitle(task, detail)}</span>
)}
{!asksInCard(entry) && <PermissionAnswers task={task} entry={entry} className={styles.permissionAnswers} />}
{!entry.questions?.length && (
<PermissionAnswers task={task} entry={entry} className={styles.permissionAnswers} />
)}
</>
)}
</div>
@@ -2332,13 +2332,12 @@ const isRecommended = (label: string) => label.endsWith(RECOMMENDED_SUFFIX);
const plainLabel = (label: string) => (isRecommended(label) ? label.slice(0, -RECOMMENDED_SUFFIX.length) : label);
/** An open `AskUserQuestion` request or agent form, as a card above the composer; one question at a time. */
/** An open `AskUserQuestion` request, as a card above the composer; one question at a time. */
function QuestionCard({ task, entries }: { task: AgentTask; entries: AgentEntry[] | null }) {
const entry = entries?.find(
(candidate): candidate is PermissionEntry =>
candidate.type === "permission" && !candidate.chosen && asksInCard(candidate),
candidate.type === "permission" && !candidate.chosen && !!candidate.questions?.length,
);
if (entry?.form) return <FormCard key={entry.id} task={task} entry={entry} form={entry.form} />;
return entry?.questions ? (
<QuestionForm key={entry.id} task={task} entry={entry} questions={entry.questions} />
) : null;
@@ -2630,7 +2629,9 @@ function QuestionForm({
*/
function Tray({ task, entries, children }: { task: AgentTask; entries: AgentEntry[] | null; children: ReactNode }) {
const tx = useTx();
const pending = entries?.find((e): e is PermissionEntry => e.type === "permission" && !e.chosen && !asksInCard(e));
const pending = entries?.find(
(e): e is PermissionEntry => e.type === "permission" && !e.chosen && !e.questions?.length,
);
const plan = entries?.findLast((e): e is Extract<AgentEntry, { type: "plan" }> => e.type === "plan");
const [planOpen, setPlanOpen] = useState(false);
const done = plan?.items.filter((i) => i.status === "completed").length ?? 0;
@@ -2704,7 +2705,7 @@ function WorkingRow({
);
}
if (task.status !== "running" && task.status !== "starting") return null;
if (entries?.some((e) => e.type === "permission" && !e.chosen && !asksInCard(e))) return null;
if (entries?.some((e) => e.type === "permission" && !e.chosen && !e.questions?.length)) return null;
const userAt = entries?.findLastIndex((e) => e.type === "user") ?? -1;
const lastUser = userAt >= 0 ? (entries![userAt] as UserEntry) : undefined;
return (
-3
Переглянути файл
@@ -3,9 +3,6 @@ import { tx } from "@/platform/i18n";
export type PermissionEntry = Extract<AgentEntry, { type: "permission" }>;
/** Questions and forms are answered in a card above the composer, not with the request's options. */
export const asksInCard = (entry: PermissionEntry) => !!entry.questions?.length || !!entry.form;
export function permissionDetails(entry: PermissionEntry, provider = "Codex") {
// The backend names the command from the request's structured input; the title is the
// agent's own words and never makes a request a command.
-62
Переглянути файл
@@ -1460,68 +1460,6 @@ describe("a pending AskUserQuestion", () => {
});
});
describe("a pending agent form", () => {
const form = {
type: "permission" as const,
id: 12,
title: "How should I refactor?",
chosen: null,
options: [{ id: "decline", name: "Decline", kind: "reject_once" }],
form: {
fields: [
{
name: "strategy",
title: "Strategy",
required: true,
kind: "choice" as const,
options: [
{ value: "safe", label: "Conservative", description: "Small steps" },
{ value: "bold", label: "Aggressive" },
],
},
{ name: "count", title: "Files", kind: "integer" as const, min: 1, max: 5 },
{ name: "tests", title: "Run tests", kind: "boolean" as const },
],
},
};
const open = async () => {
backend.entries.set("A", [form]);
backend.answers = [];
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
return screen.findByRole("form", { name: "How should I refactor?" });
};
it("sends the values once every required field is valid", async () => {
const card = await open();
const submit = within(card).getByRole("button", { name: "Submit" });
expect(submit).toHaveProperty("disabled", true);
fireEvent.click(within(card).getByRole("radio", { name: /^Aggressive/ }));
expect(submit).toHaveProperty("disabled", false);
const files = within(card).getByRole("spinbutton", { name: /^Files/ });
fireEvent.change(files, { target: { value: "9" } });
expect(submit).toHaveProperty("disabled", true);
fireEvent.change(files, { target: { value: "3" } });
fireEvent.click(within(card).getByRole("checkbox", { name: /^Run tests/ }));
fireEvent.click(submit);
await waitFor(() =>
expect(backend.answers).toEqual([
["A", 12, JSON.stringify({ strategy: ["bold"], count: ["3"], tests: ["true"] })],
]),
);
});
it("declines with Decline and cancels with Escape", async () => {
const card = await open();
fireEvent.click(within(card).getByRole("button", { name: "Decline" }));
await waitFor(() => expect(backend.answers).toEqual([["A", 12, "decline"]]));
backend.answers = [];
fireEvent.keyDown(within(card).getByRole("radio", { name: /^Conservative/ }), { key: "Escape" });
await waitFor(() => expect(backend.answers).toEqual([["A", 12, null]]));
});
});
describe("a pending permission request above the composer", () => {
const command = 'python3 -c \'from pathlib import Path\np = Path("note.txt")\np.write_text("one\\ntwo")\'';
const options = [
+1 -2
Переглянути файл
@@ -149,8 +149,7 @@ export function DatabaseView() {
if (!st.treeReveal) return;
const path = st.treeReveal.path;
const frame = requestAnimationFrame(() => {
// Spread + reverse instead of toReversed(), which needs Safari 16.4 (the floor is 15.4).
[...path].reverse().some((key) => tree.current?.reveal(key));
path.toReversed().some((key) => tree.current?.reveal(key));
tree.current?.focus();
});
return () => cancelAnimationFrame(frame);
-21
Переглянути файл
@@ -171,27 +171,6 @@ describe("ProjectView", () => {
await waitFor(() => expect(rows()).toEqual(["acme/w/acme", "build", "src", "App.kt", "Util.kt", "README.md"]));
});
it("opens the selected file in the right split with ⇧Enter; a folder still expands", async () => {
dispatchViaKeymap();
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("README.md"));
tree.focus();
fireEvent.keyDown(tree, { key: "Enter", code: "Enter", shiftKey: true });
await waitFor(() =>
expect(openFile).toHaveBeenLastCalledWith(
"/w/acme/README.md",
expect.objectContaining({ side: true, focus: true }),
),
);
openFile.mockClear();
fireEvent.mouseDown(row("src"));
tree.focus();
fireEvent.keyDown(tree, { key: "Enter", code: "Enter", shiftKey: true });
await waitFor(() => expect(rows()).toContain("App.kt"));
expect(openFile).not.toHaveBeenCalled();
});
it("pastes the files Explorer copied into the selected folder, as copies", async () => {
dispatchViaKeymap();
// What Explorer leaves on the clipboard: a path outside the project.
-12
Переглянути файл
@@ -24,11 +24,9 @@ import {
openMoveDialog,
openRenameDialog,
openSelection,
openSelectionInRightSplit,
paste,
reloadFromDisk,
revealInFinder,
selectedFiles,
selectedNodes,
type PathKind,
} from "./operations";
@@ -293,16 +291,6 @@ export function registerProjectActions(): () => void {
when: FOCUS,
run: openSelection,
},
{
id: "project.openInRightSplit",
title: "Open in Right Split",
category: "Project View",
icon: "split",
when: FOCUS,
// Folders keep Enter's expand / collapse.
enabled: () => selectedFiles().length > 0,
run: () => openSelectionInRightSplit(),
},
{
id: "project.rename",
title: "Rename File…",
+1 -2
Переглянути файл
@@ -142,7 +142,6 @@ describe("project view context menu", () => {
"-",
"Run 'a'",
"-",
"Open in Right Split",
"Open In",
"-",
"Local History",
@@ -229,7 +228,7 @@ describe("project view context menu", () => {
const l = labels(contextMenuItems([node(`${ROOT}/src`, true)]));
expect(l).toContain("Mark Directory as");
expect(sub(contextMenuItems([node(`${ROOT}/src`, true)]), "Refactor")).toContain("Move Directory…");
for (const fileOnly of ["Find Usages", "Reformat Code", "Optimize Imports", "Run 'a'", "Open in Right Split"])
for (const fileOnly of ["Find Usages", "Reformat Code", "Optimize Imports", "Run 'a'"])
expect(l).not.toContain(fileOnly);
});
+1 -14
Переглянути файл
@@ -25,7 +25,6 @@ import {
openFile,
openMoveDialog,
openRenameDialog,
openSelectionInRightSplit,
paste,
reloadFromDisk,
revealInFinder,
@@ -314,9 +313,8 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
// Contributed groups (Run / Debug '…', More Run/Debug ›), each followed by a separator.
push(...menuGroupItems("projectView", menuGroupContext(nodes)));
// Open in Right Split / Open In ›
// Open In ›
push(
files.length > 0 && openInRightSplitItem(files),
submenu("openIn", "Open In", [
canRevealInFileManager() && {
id: "finder",
@@ -459,16 +457,6 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
return items;
}
function openInRightSplitItem(files: ProjectNode[]): MenuItem {
return {
id: "openInRightSplit",
label: "Open in Right Split",
icon: "split",
shortcut: keyLabel("project.openInRightSplit"),
run: () => void openSelectionInRightSplit(files),
};
}
/** Library sources (External Libraries) are read-only: copy, find and reveal only. */
function libraryMenuItems(nodes: ProjectNode[]): MenuItem[] {
if (!nodes.length) return [];
@@ -492,7 +480,6 @@ function libraryMenuItems(nodes: ProjectNode[]): MenuItem[] {
{ kind: "separator" },
!!folder && delegated("find.inPath", { directory: folder }, "Find in Files…", { icon: "search" }),
!!folder && { kind: "separator" },
nodes.every((n) => !n.dir) && openInRightSplitItem(nodes),
submenu("openIn", "Open In", [
canRevealInFileManager() && {
id: "finder",
+2 -20
Переглянути файл
@@ -127,22 +127,14 @@ function expandFolder(path: string) {
// ---------------------------------------------------------------------------
// Open
export async function openFile(
path: string,
opts: { preview?: boolean; focus?: boolean; external?: boolean; side?: boolean } = {},
) {
export async function openFile(path: string, opts: { preview?: boolean; focus?: boolean; external?: boolean } = {}) {
const editor = maybeEditorService();
if (!editor) {
notifications().notify({ level: "warning", title: "No editor available", body: path, key: "project.noEditor" });
return;
}
try {
await editor.openFile(path, {
preview: opts.preview,
focus: opts.focus ?? true,
external: opts.external,
...(opts.side && { side: true }),
});
await editor.openFile(path, { preview: opts.preview, focus: opts.focus ?? true, external: opts.external });
} catch (e) {
fail(`Cannot open ${nameOf(path)}`, e);
}
@@ -152,16 +144,6 @@ export function openSelection() {
for (const n of selectedNodes()) if (!n.dir) void openFile(n.path);
}
/** Files among the selected nodes, for actions that open them. */
export function selectedFiles(): ProjectNode[] {
return selectedNodes().filter((n) => !n.dir && !n.placeholder && !n.member);
}
/** Open in Right Split (⇧Enter): the selected files in the pane right of the current editor. */
export async function openSelectionInRightSplit(nodes = selectedFiles()) {
for (const [i, n] of nodes.entries()) await openFile(n.path, { side: true, focus: i === nodes.length - 1 });
}
// ---------------------------------------------------------------------------
// New / rename
-9
Переглянути файл
@@ -104,14 +104,6 @@ describe("languages settings", () => {
expect(validateSettings(settings).languages.ruby.interpreter).toBe("/opt/ruby/bin/ruby");
});
it("keeps the Zig toolchain through settings normalization and defaults to Auto", () => {
expect(validateSettings({}).languages.zig.zig).toBe("");
expect(validateLanguages({ zig: { zig: 42 } }).zig.zig).toBe("");
const settings = validateSettings({ languages: { zig: { zig: " /opt/zig " } } });
expect(settings.languages.zig.zig).toBe("/opt/zig");
expect(validateSettings(settings).languages.zig.zig).toBe("/opt/zig");
});
it("defaults the PHP language level to Auto and keeps only known levels", () => {
expect(validateSettings({}).languages.php).toEqual({
runTarget: "",
@@ -350,7 +342,6 @@ describe("language pages", () => {
"Ruby",
"Rust",
"TypeScript",
"Zig",
]);
});
-72
Переглянути файл
@@ -1,72 +0,0 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useProject } from "@/platform/project";
import type { Sdk } from "@/platform/ipc";
const ok = <T,>(data: T) => Promise.resolve({ status: "ok" as const, data });
const zig = (path: string, version: string, source: string): Sdk => ({
path,
name: `Zig ${version}`,
version,
source,
home: path,
extra: null,
});
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
isTauri: () => true,
commands: {
...actual.commands,
sdkDetect: (kind: string) =>
ok(
kind === "zig"
? [zig("/opt/homebrew/opt/zig/bin", "0.14.1", "system"), zig("/Users/dev/.zvm/0.13.0", "0.13.0", "zvm")]
: [],
),
},
};
});
import { PageContext } from "../components/context";
import { ZigPage } from "../languages/LanguagePages";
import { DEFAULT_SETTINGS } from "../model/schema";
import { openSettings } from "../model/staging";
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
function page(setting: string) {
const settings = structuredClone(DEFAULT_SETTINGS);
settings.languages.zig.zig = setting;
useProject.setState({ settings, project: null });
openSettings("languages.zig");
render(
<PageContext.Provider value={{ pageId: "languages.zig", scope: "global" }}>
<ZigPage />
</PageContext.Provider>,
);
}
describe("Zig settings page", () => {
it("defaults to Auto and lists the detected toolchains", async () => {
page("");
const combo = screen.getByRole("button", { name: "Zig toolchain" });
await waitFor(() => expect(combo).toHaveTextContent("Auto"));
fireEvent.click(combo);
const options = await screen.findAllByRole("option");
expect(options[0]).toHaveTextContent("Auto");
expect(options[0]).toHaveTextContent("zig on PATH");
expect(options[1]).toHaveTextContent("Zig 0.14.1");
expect(options[2]).toHaveTextContent("Zig 0.13.0");
});
it("shows the selected toolchain's version", async () => {
page("/opt/homebrew/opt/zig/bin");
const combo = screen.getByRole("button", { name: "Zig toolchain" });
await waitFor(() => expect(combo).toHaveTextContent("Zig 0.14.1"));
});
});
-23
Переглянути файл
@@ -726,26 +726,3 @@ export function TypeScriptPage() {
</div>
);
}
// ---------------------------------------------------------------------------
// Zig
export function ZigPage() {
return (
<div className={styles.page}>
<Section>
<SdkRow
k="languages.zig.zig"
label="Zig toolchain"
kind="zig"
emptyLabel="Auto"
emptyDetail="zig on PATH"
directory
browseTitle="Select Zig Directory"
aria-label="Zig toolchain"
hint="Zig whose standard library and build.zig.zon packages appear under External Libraries. ZLS must match this Zig version. PATH, Homebrew, zvm and mise / asdf installs are detected."
/>
</Section>
</div>
);
}
+2 -21
Переглянути файл
@@ -1,18 +1,9 @@
/**
* PyCharm's top-level "Python" group (Interpreter) and
* Languages & Frameworks › Go / Java / Markdown / Node.js / PHP / Rust / TypeScript / Zig. Pages live in
* Languages & Frameworks › Go / Java / Markdown / Node.js / PHP / Rust / TypeScript. Pages live in
* `../languages/`; settings are `languages.*` / `projectStructure.*`.
*/
import {
GoPage,
JavaPage,
NodePage,
PhpPage,
RubyPage,
RustPage,
TypeScriptPage,
ZigPage,
} from "../languages/LanguagePages";
import { GoPage, JavaPage, NodePage, PhpPage, RubyPage, RustPage, TypeScriptPage } from "../languages/LanguagePages";
import { MarkdownPage } from "../languages/MarkdownPage";
import { OxfmtPage, PrettierPage, RuffPage } from "../languages/FormatterPage";
import { PythonInterpreterPage } from "../languages/PythonInterpreterPage";
@@ -277,14 +268,4 @@ export const LANGUAGE_PAGES: PageSpec[] = [
keywords: ["typescript version", "tsdk", "tsserver", "node_modules", "vtsls"],
component: TypeScriptPage,
},
{
id: "languages.zig",
projectScope: true,
defaultScope: "project",
title: "Zig",
group: LANGUAGES_GROUP,
order: 406,
keywords: ["zig toolchain", "zls", "zig build", "build.zig", "build.zig.zon"],
component: ZigPage,
},
];
+5 -4
Переглянути файл
@@ -213,19 +213,20 @@ it("preserves Safari error messages when its stack only lists locations", () =>
});
it("names an outdated system web engine as the cause", () => {
// Simulates Safari < 15.4, which can't parse the bundle's syntax.
vi.stubGlobal("structuredClone", undefined);
const supports = vi.fn(() => false);
vi.stubGlobal("CSS", { supports });
vi.spyOn(navigator, "userAgent", "get").mockReturnValue(
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko)",
);
window.dispatchEvent(new ErrorEvent("error", { error: new SyntaxError("Unexpected token '.'") }));
const hint = document.querySelector("#boot-error p")?.textContent;
expect(hint).toContain("needs macOS 12 Monterey or later");
expect(supports).toHaveBeenCalledWith("container-type", "inline-size");
expect(hint).toContain("needs macOS 13 Ventura or later");
vi.unstubAllGlobals();
});
it("keeps the plain report hint on a current engine", () => {
vi.stubGlobal("structuredClone", () => ({}));
vi.stubGlobal("CSS", { supports: () => true });
window.dispatchEvent(new ErrorEvent("error", { error: new Error("startup failed") }));
expect(document.querySelector("#boot-error p")?.textContent).toBe(
"Copy the details below and include them in a GitHub issue.",
-1
Переглянути файл
@@ -211,7 +211,6 @@ export const intellijMacos: Record<string, string[]> = {
"project.paste": ["Meta+V"],
"project.copyAbsolutePath": ["Meta+Shift+C"],
"project.open": ["F4", "Meta+Down"],
"project.openInRightSplit": ["Shift+Enter"],
"project.findUsages": ["Alt+F7"],
"project.reformatCode": ["Meta+Alt+L"],
"project.optimizeImports": ["Ctrl+Alt+O"],
-1
Переглянути файл
@@ -212,7 +212,6 @@ export const intellijWindows: Record<string, string[]> = {
"project.paste": ["Ctrl+V", "Shift+Insert"],
"project.copyAbsolutePath": ["Ctrl+Shift+C"],
"project.open": ["F4"],
"project.openInRightSplit": ["Shift+Enter"],
"project.findUsages": ["Alt+F7"],
"project.reformatCode": ["Ctrl+Alt+L"],
"project.optimizeImports": ["Ctrl+Alt+O"],
-2
Переглянути файл
@@ -236,8 +236,6 @@ export const vscodeMacos: Record<string, string[]> = {
"project.paste": ["Meta+V"],
"project.copyAbsolutePath": ["Meta+Alt+C"],
"project.open": ["Meta+Down"],
// Explorer: Open to the Side.
"project.openInRightSplit": ["Meta+Enter"],
"project.reloadFromDisk": [],
"project.expandAll": [],
"project.collapseAll": [],
-1
Переглянути файл
@@ -45,7 +45,6 @@ export const vscodeWindows: Record<string, string[]> = {
"db.drop": ["Delete"],
"project.copyAbsolutePath": ["Alt+Shift+C"],
"project.open": [],
"project.openInRightSplit": ["Ctrl+Enter"],
// Editing extras, image viewer (keyWhen: image focused) and Markdown editor layouts
"code.cyclicExpandWord": [],
"code.cyclicExpandWordBackward": [],
-4
Переглянути файл
@@ -168,7 +168,6 @@ export interface LanguagesValid {
showInterpreterPaths: boolean;
};
ruby: { interpreter: string };
zig: { zig: string };
node: {
runTarget: string;
interpreter: string;
@@ -285,7 +284,6 @@ export const DEFAULT_LANGUAGES: LanguagesValid = {
showInterpreterPaths: true,
},
ruby: { interpreter: "" },
zig: { zig: "" },
node: { runTarget: "", interpreter: "", packageManager: "", runtime: "" },
php: { runTarget: "", interpreter: "", languageLevel: "", includePaths: [], stubs: [], phpstanConfig: "" },
rust: { toolchain: "", stdlib: "", checkOnSave: true, checkCommand: "check", rustfmtArgs: "" },
@@ -395,7 +393,6 @@ export function validateLanguages(raw: unknown): LanguagesValid {
const l = obj(raw);
const py = obj(l.python);
const ruby = obj(l.ruby);
const zig = obj(l.zig);
const node = obj(l.node);
const php = obj(l.php);
const rust = obj(l.rust);
@@ -422,7 +419,6 @@ export function validateLanguages(raw: unknown): LanguagesValid {
showInterpreterPaths: bool(py.showInterpreterPaths, d.python.showInterpreterPaths),
},
ruby: { interpreter: text(ruby.interpreter, d.ruby.interpreter) },
zig: { zig: text(zig.zig, d.zig.zig) },
node: {
runTarget: text(node.runTarget, ""),
interpreter: text(node.interpreter, d.node.interpreter),
+1 -2
Переглянути файл
@@ -1884,6 +1884,5 @@
"e.g. Reticulating splines…": "e.g. Reticulating splines…",
"New playful word": "New playful word",
"Restore Built-in Words": "Restore Built-in Words",
"None — type the Engine API URL below": "None — type the Engine API URL below",
"Open in Right Split": "Open in Right Split"
"None — type the Engine API URL below": "None — type the Engine API URL below"
}
+1 -5
Переглянути файл
@@ -5723,9 +5723,6 @@
"e.g. --format documentation --fail-fast": "例如 --format documentation --fail-fast",
"Ruby interpreter": "Ruby 解释器",
"Runs the ruby, rake and rspec configurations and lists the standard library and gems under External Libraries. Installs from rbenv, rvm, chruby, mise and asdf are detected.": "用于运行 ruby、rake 和 rspec 配置,并在“外部库”下列出标准库和 gem。会检测 rbenv、rvm、chruby、mise 和 asdf 安装的版本。",
"Select Zig Directory": "选择 Zig 目录",
"Zig toolchain": "Zig 工具链",
"Zig whose standard library and build.zig.zon packages appear under External Libraries. ZLS must match this Zig version. PATH, Homebrew, zvm and mise / asdf installs are detected.": "用于在“外部库”下列出 Zig 标准库和 build.zig.zon 依赖的 Zig。ZLS 版本必须与该 Zig 版本匹配。可检测 PATH、Homebrew、zvm 以及 mise / asdf 的安装。",
"Monospaced": "等宽",
"Proportional": "非等宽",
"Loading system fonts…": "正在加载系统字体…",
@@ -8288,6 +8285,5 @@
"e.g. Reticulating splines…": "例如:正在网格化样条曲线…",
"New playful word": "新的趣味文字",
"Restore Built-in Words": "恢复内置文字",
"None — type the Engine API URL below": "无(在下方输入 Engine API URL)",
"Open in Right Split": "在右侧拆分中打开"
"None — type the Engine API URL below": "无(在下方输入 Engine API URL)"
}
-1
Переглянути файл
@@ -100,7 +100,6 @@ const UNTRANSLATED = new Set<string>([
"GitHub",
"PHPStan",
"Xdebug",
"Zig",
// Resource kinds of a browser's network panel
"Fetch/XHR",
"JS",
+1 -1
Переглянути файл
@@ -39,7 +39,7 @@ export default defineConfig(() => ({
// separate projects with their own dependencies, never part of this bundle.
optimizeDeps: { entries: ["index.html"] },
build: {
target: "safari15.4",
target: "safari16",
sourcemap: true,
},
test: {