дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-30 22:32:35 +02:00
Порівняти коміти
4
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
3c3d02d7be | ||
|
|
2f66eb0503 | ||
|
|
63db10a688 | ||
|
|
1dd3d64781 |
No files matched your search
@@ -15,6 +15,7 @@
|
||||
"src/editor/core/cm/jsp/parser*.ts",
|
||||
"src/editor/core/cm/astro/parser*.ts",
|
||||
"src/editor/core/cm/django/parser*.ts",
|
||||
"src/editor/core/cm/freemarker/parser*.ts",
|
||||
"plugins/themes.md",
|
||||
"pnpm-lock.yaml",
|
||||
"**/*.toml",
|
||||
|
||||
@@ -18,7 +18,7 @@ pub mod service;
|
||||
mod symbols;
|
||||
mod tool;
|
||||
|
||||
pub(crate) use tool::trusted_attachments;
|
||||
pub(crate) use tool::{PROJECT_PATH, trusted_attachments};
|
||||
mod util;
|
||||
|
||||
use crate::Host;
|
||||
@@ -28,6 +28,7 @@ pub use reports::{
|
||||
FileProblems, FocusedEditor, Reports, mcp_report_problems, mcp_set_focused_editor, mcp_set_open_editors,
|
||||
};
|
||||
pub use run::agent::{AGENT_PARAM, AgentRun, AgentRuns, NAME_PREFIX, SHELL_PARAM};
|
||||
use serde_json::json;
|
||||
pub use service::{McpServerStatus, McpService};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
@@ -55,7 +56,8 @@ fn tools() -> Vec<tool::Tool> {
|
||||
tools
|
||||
}
|
||||
|
||||
// Checked both when listing and calling, so a later trust change takes effect immediately.
|
||||
// What a project lists. A call checks the trust it has then (`call_with_client`), so a later
|
||||
// trust change takes effect immediately.
|
||||
fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
|
||||
trusted || tool.read_only
|
||||
}
|
||||
@@ -63,11 +65,36 @@ fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
|
||||
fn tools_for(host: &Host, root: &Path, trusted: bool) -> Vec<ide_mcp::Tool> {
|
||||
let mut all: Vec<_> = tools().into_iter().map(|t| t.metadata).collect();
|
||||
if let Some(plugins) = host.plugin_host() {
|
||||
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| tool));
|
||||
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| with_project_path(tool)));
|
||||
}
|
||||
all.into_iter().filter(|t| allowed(t, trusted)).collect()
|
||||
}
|
||||
|
||||
/// A plugin's tool as clients see it: it takes `projectPath` like every other tool, which the
|
||||
/// plugin gets only if its own schema takes it (`PluginHost::call_mcp_tool`).
|
||||
fn with_project_path(mut tool: ide_mcp::Tool) -> ide_mcp::Tool {
|
||||
if let Some(schema) = tool.input_schema.as_object_mut()
|
||||
&& let Some(properties) = schema.entry("properties").or_insert_with(|| json!({})).as_object_mut()
|
||||
{
|
||||
properties.entry(tool::PROJECT_PATH).or_insert_with(tool::project_path);
|
||||
}
|
||||
tool
|
||||
}
|
||||
|
||||
/// The tool a call runs: a plugin's or a built-in one.
|
||||
enum Found {
|
||||
Plugin { plugins: Arc<crate::plugins::PluginHost>, plugin: String, tool: String, metadata: ide_mcp::Tool },
|
||||
Builtin(tool::Tool),
|
||||
}
|
||||
impl Found {
|
||||
fn writes(&self) -> bool {
|
||||
match self {
|
||||
Self::Plugin { metadata, .. } => !metadata.read_only,
|
||||
Self::Builtin(tool) => !tool.metadata.read_only,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists the built-in IDE and plugin-contributed MCP tools visible to `window`.
|
||||
pub(crate) fn list_tools_for_window(host: &Host, window: &str) -> Vec<ide_mcp::Tool> {
|
||||
match host.project(window).ok().filter(|p| !p.light) {
|
||||
@@ -110,6 +137,16 @@ impl Registry {
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool `name` for `root`: a plugin's first. Loads nothing.
|
||||
fn find(&self, root: &Path, name: &str) -> Option<Found> {
|
||||
if let Some(plugins) = self.0.plugin_host()
|
||||
&& let Some((plugin, tool, metadata)) = plugins.mcp_tools(root).into_iter().find(|(_, _, t)| t.name == name)
|
||||
{
|
||||
return Some(Found::Plugin { plugins, plugin, tool, metadata });
|
||||
}
|
||||
tools().into_iter().find(|t| t.metadata.name == name).map(Found::Builtin)
|
||||
}
|
||||
|
||||
/// Whether the tools listed for `root` include those that write and run. Opens nothing:
|
||||
/// a background project that is not loaded is judged as its open will judge it.
|
||||
fn lists_as_trusted(&self, root: &Path) -> Result<bool, String> {
|
||||
@@ -150,6 +187,9 @@ impl ToolRegistry for Registry {
|
||||
let trusted = self.lists_as_trusted(root)?;
|
||||
Ok(tools_for(&self.0, root, trusted))
|
||||
}
|
||||
fn tools_without_project(&self) -> Vec<ide_mcp::Tool> {
|
||||
tools_for(&self.0, Path::new(""), true)
|
||||
}
|
||||
fn call(
|
||||
&self,
|
||||
root: &Path,
|
||||
@@ -167,19 +207,27 @@ impl ToolRegistry for Registry {
|
||||
cancel: CancellationToken,
|
||||
client: &str,
|
||||
) -> Result<String, ToolCallError> {
|
||||
let unknown = || ToolCallError::UnknownTool(format!("unknown tool: {name}"));
|
||||
// Before the project loads, so the refusal neither loads a background project nor
|
||||
// unloads an idle one at the limit to make room.
|
||||
if self.find(root, name).ok_or_else(unknown)?.writes() && self.lists_as_trusted(root) == Ok(false) {
|
||||
return Err(ToolCallError::Failed(crate::project::RESTRICTED_MODE.into()));
|
||||
}
|
||||
// The guard lives until the call ends, whichever way it leaves: neither the idle
|
||||
// sweep nor the limit unloads a background project a call runs in.
|
||||
let (window, project, _activity) = self.target(root).map_err(ToolCallError::Failed)?;
|
||||
if let Some(plugins) = self.0.plugin_host()
|
||||
&& let Some((plugin, tool, metadata)) =
|
||||
plugins.mcp_tools(root).into_iter().find(|(_, _, t)| t.name == name && allowed(t, project.is_trusted()))
|
||||
{
|
||||
return self.call_plugin(window, project, plugins, plugin, tool, metadata, arguments, cancel, client);
|
||||
// Found again: a plugin can change while a background project opens, and the call
|
||||
// runs the tool as it is now.
|
||||
let found = self.find(root, name).ok_or_else(unknown)?;
|
||||
if found.writes() {
|
||||
project.require_trust().map_err(|e| ToolCallError::Failed(e.message))?;
|
||||
}
|
||||
let tool = tools()
|
||||
.into_iter()
|
||||
.find(|t| t.metadata.name == name && allowed(&t.metadata, project.is_trusted()))
|
||||
.ok_or_else(|| ToolCallError::UnknownTool(format!("unknown tool: {name}")))?;
|
||||
let tool = match found {
|
||||
Found::Plugin { plugins, plugin, tool, metadata } => {
|
||||
return self.call_plugin(window, project, plugins, plugin, tool, metadata, arguments, cancel, client);
|
||||
}
|
||||
Found::Builtin(tool) => tool,
|
||||
};
|
||||
let args = serde_json::from_str(arguments).map_err(|e| ToolCallError::Failed(e.to_string()))?;
|
||||
let call = tool::Call {
|
||||
host: self.0.clone(),
|
||||
|
||||
@@ -5,6 +5,14 @@ use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The argument that names the project a call is for; the server routes the call by it.
|
||||
pub(crate) const PROJECT_PATH: &str = "projectPath";
|
||||
|
||||
/// The schema of [`PROJECT_PATH`], which every tool takes.
|
||||
pub(crate) fn project_path() -> Value {
|
||||
json!({ "type": "string", "description": "Any directory inside a project that is open in a window or served in the background. Defaults to the connection's project (`?project=`) or the only one open in a window." })
|
||||
}
|
||||
|
||||
pub struct Call {
|
||||
pub client: String,
|
||||
pub tool: String,
|
||||
@@ -242,9 +250,7 @@ impl Tool {
|
||||
read_only: true,
|
||||
destructive: false,
|
||||
output_schema: None,
|
||||
input_schema: json!({ "type": "object", "properties": {
|
||||
"projectPath": { "type": "string", "description": "Any directory inside a project that is open in a window or served in the background. Defaults to the connection's project (`?project=`) or the only one open in a window." }
|
||||
}, "required": [] }),
|
||||
input_schema: json!({ "type": "object", "properties": { PROJECT_PATH: project_path() }, "required": [] }),
|
||||
},
|
||||
handler: Arc::new(move |call| Box::pin(handler(call))),
|
||||
}
|
||||
|
||||
@@ -118,21 +118,50 @@ impl PluginHost {
|
||||
.find(|(p, n, _)| p == plugin && n == tool)
|
||||
.ok_or_else(|| IdeError::not_found("plugin MCP tool is no longer available"))?;
|
||||
let args: serde_json::Value = serde_json::from_str(arguments).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
let validator =
|
||||
jsonschema::validator_for(&declared.input_schema).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
if !validator.is_valid(&args) {
|
||||
return Err(IdeError::invalid("MCP arguments do not match inputSchema"));
|
||||
}
|
||||
let (tool, arguments) = (tool.to_owned(), arguments.to_owned());
|
||||
let arguments = arguments_for(&declared.input_schema, args)?;
|
||||
let tool = tool.to_owned();
|
||||
self.code_call_cancellable(plugin, invocation, "calling the MCP tool", Some(cancel), move |rt, inv| {
|
||||
rt.mcp_call(&tool, &arguments, inv)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `args` as the tool's `schema` takes them. Every listed tool takes `projectPath`, which the
|
||||
/// server routes a call by; a schema that refuses it gets the call without it.
|
||||
fn arguments_for(schema: &serde_json::Value, mut args: serde_json::Value) -> IdeResult<String> {
|
||||
let validator = jsonschema::validator_for(schema).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
if !validator.is_valid(&args)
|
||||
&& let Some(args) = args.as_object_mut()
|
||||
{
|
||||
args.remove(crate::mcp::PROJECT_PATH);
|
||||
}
|
||||
if !validator.is_valid(&args) {
|
||||
return Err(IdeError::invalid("MCP arguments do not match inputSchema"));
|
||||
}
|
||||
Ok(args.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_schema_gets_the_project_path_only_when_it_takes_it() {
|
||||
let call = serde_json::json!({ "text": "hi", "projectPath": "/work/inventory" });
|
||||
let strict = serde_json::json!({
|
||||
"type": "object", "properties": { "text": { "type": "string" } }, "additionalProperties": false
|
||||
});
|
||||
assert_eq!(arguments_for(&strict, call.clone()).unwrap(), r#"{"text":"hi"}"#);
|
||||
// Declared through a local `$ref` and required: the plugin keeps it.
|
||||
let declared = serde_json::json!({
|
||||
"$ref": "#/$defs/call",
|
||||
"$defs": { "call": { "type": "object", "required": ["projectPath"], "additionalProperties": false,
|
||||
"properties": { "text": { "type": "string" }, "projectPath": { "type": "string" } } } }
|
||||
});
|
||||
let kept: serde_json::Value = serde_json::from_str(&arguments_for(&declared, call).unwrap()).unwrap();
|
||||
assert_eq!(kept["projectPath"], "/work/inventory");
|
||||
assert!(arguments_for(&strict, serde_json::json!({ "text": 12, "projectPath": "/p" })).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn validates_names_schema_files_versions_and_schema_keywords_at_install() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1063,17 +1063,16 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a tool that writes or runs refuses a project the user hasn't trusted.
|
||||
pub(crate) const RESTRICTED_MODE: &str = "Project is in Restricted Mode. Trust the project to enable execution.";
|
||||
|
||||
impl Project {
|
||||
pub fn is_trusted(&self) -> bool {
|
||||
self.trusted.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn require_trust(&self) -> IdeResult<()> {
|
||||
if self.is_trusted() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(IdeError::unavailable("Project is in Restricted Mode. Trust the project to enable execution."))
|
||||
}
|
||||
if self.is_trusted() { Ok(()) } else { Err(IdeError::unavailable(RESTRICTED_MODE)) }
|
||||
}
|
||||
|
||||
/// LightEdit: follow external changes to the files of `dir` (its own entries only).
|
||||
|
||||
@@ -252,6 +252,10 @@ async fn restricted_projects_have_only_read_tools_and_remote_projects_explain_th
|
||||
assert!(!h.host.project("main").unwrap().is_trusted());
|
||||
let registry = Registry::new(h.host.clone());
|
||||
assert!(registry.tools(&h.root).unwrap().iter().all(|t| t.read_only && !t.destructive));
|
||||
// A tool that writes, called all the same, says why it can't run.
|
||||
let refused = h.error("create_new_file", json!({"pathInProject":"x.txt","text":"no"})).await;
|
||||
assert_eq!(refused, "Project is in Restricted Mode. Trust the project to enable execution.");
|
||||
assert!(!h.root.join("x.txt").exists());
|
||||
assert!(!h.host.global_settings.effective().mcp_server.enabled);
|
||||
h.host.mcp_reports.set_remote("remote", PathBuf::from("/remote/project"));
|
||||
assert_eq!(
|
||||
@@ -1546,22 +1550,91 @@ async fn a_folder_without_a_window_is_opened_by_its_first_tool_call() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn with_background_projects_off_a_folder_outside_the_open_projects_is_refused() {
|
||||
async fn with_background_projects_off_a_folder_outside_the_open_projects_lists_tools_and_refuses_calls() {
|
||||
let h = Harness::new();
|
||||
let inventory = h.root.parent().unwrap().join("inventory");
|
||||
std::fs::create_dir_all(&inventory).unwrap();
|
||||
let (_server, discovery) = h.server();
|
||||
let list = rpc(1, "tools/list", json!({}));
|
||||
let read = rpc(2, "tools/call", json!({"name":"read_file","arguments":{"file_path":"a.txt"}}));
|
||||
for reply in bridged(&discovery, &inventory, &[list, read]).await {
|
||||
assert_eq!(reply["error"]["code"], -32001, "{reply}");
|
||||
let message = reply["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("isn't served in the background"), "{message}");
|
||||
}
|
||||
let replies = bridged(&discovery, &inventory, &[list, read]).await;
|
||||
let tools = replies[0]["result"]["tools"].as_array().unwrap();
|
||||
assert!(tools.iter().any(|t| t["name"] == "create_new_file" && t["annotations"]["readOnlyHint"] == false));
|
||||
assert_eq!(replies[1]["error"]["code"], -32001, "{}", replies[1]);
|
||||
let message = replies[1]["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("isn't served in the background"), "{message}");
|
||||
assert!(h.background().is_empty());
|
||||
assert_eq!(h.host.projects().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_connection_in_a_folder_no_project_serves_lists_the_tools_and_each_call_names_its_project() {
|
||||
let h = Harness::new();
|
||||
// A folder that only holds repositories: one trusted, one not.
|
||||
let work = h.root.parent().unwrap().join("work");
|
||||
let (inventory, ledger) = (work.join("inventory"), work.join("ledger"));
|
||||
for project in [&inventory, &ledger] {
|
||||
std::fs::create_dir_all(project.join("src")).unwrap();
|
||||
}
|
||||
std::fs::write(inventory.join("src/stock.txt"), "forty crates\n").unwrap();
|
||||
h.set("enabled", json!(true));
|
||||
h.set("backgroundProjects", json!("listed"));
|
||||
h.set("backgroundProjectPaths", json!([inventory, ledger]));
|
||||
h.host.set_project_trust(&inventory, true, false).await.unwrap();
|
||||
let (_server, discovery) = h.server();
|
||||
|
||||
let requests =
|
||||
[rpc(1, "initialize", json!({})), rpc(2, "tools/list", json!({})), rpc(3, "openidea/servesFolder", json!({}))];
|
||||
let replies = bridged(&discovery, &work, &requests).await;
|
||||
let instructions = replies[0]["result"]["instructions"].as_str().unwrap();
|
||||
assert!(instructions.contains("no project of its own: pass `projectPath`"), "{instructions}");
|
||||
let tools = replies[1]["result"]["tools"].as_array().unwrap();
|
||||
assert!(tools.iter().any(|t| t["name"] == "create_new_file" && t["annotations"]["readOnlyHint"] == false));
|
||||
assert_eq!(replies[2]["result"], json!({ "root": null }), "{}", replies[2]);
|
||||
assert!(h.background().is_empty(), "initialize, tools/list and servesFolder open nothing");
|
||||
|
||||
// A tool that writes is refused for the untrusted project before it loads; a call that
|
||||
// names no project is refused too.
|
||||
let create = rpc(
|
||||
4,
|
||||
"tools/call",
|
||||
json!({"name":"create_new_file","arguments":{
|
||||
"projectPath":ledger,"pathInProject":"notes.txt","text":"no"}}),
|
||||
);
|
||||
let unnamed = rpc(5, "tools/call", json!({"name":"read_file","arguments":{"file_path":"src/stock.txt"}}));
|
||||
let replies = bridged(&discovery, &work, &[create, unnamed]).await;
|
||||
assert_eq!(replies[0]["result"]["isError"], true, "{}", replies[0]);
|
||||
let refused = replies[0]["result"]["content"][0]["text"].as_str().unwrap();
|
||||
assert!(refused.contains("Restricted Mode"), "{refused}");
|
||||
assert!(!ledger.join("notes.txt").exists());
|
||||
assert_eq!(replies[1]["error"]["code"], -32001, "{}", replies[1]);
|
||||
assert!(h.background().is_empty(), "refusals open nothing");
|
||||
|
||||
// Inside a served project, servesFolder names it, and loads nothing either.
|
||||
let serves = [rpc(7, "openidea/servesFolder", json!({}))];
|
||||
let replies = bridged(&discovery, &inventory.join("src"), &serves).await;
|
||||
assert_eq!(replies[0]["result"], json!({ "root": inventory }), "{}", replies[0]);
|
||||
assert!(h.background().is_empty());
|
||||
|
||||
let read = rpc(
|
||||
6,
|
||||
"tools/call",
|
||||
json!({"name":"read_file","arguments":{
|
||||
"projectPath":inventory,"file_path":"src/stock.txt"}}),
|
||||
);
|
||||
let replies = bridged(&discovery, &work, &[read]).await;
|
||||
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: forty crates\nL2: ", "{replies:?}");
|
||||
assert_eq!(h.background(), std::slice::from_ref(&inventory));
|
||||
|
||||
// A remote window's root is that host's to serve.
|
||||
let remote = work.join("remote");
|
||||
std::fs::create_dir_all(&remote).unwrap();
|
||||
h.host.mcp_reports.set_remote("remote", remote.clone());
|
||||
let replies = bridged(&discovery, &remote, &serves).await;
|
||||
assert_eq!(replies[0]["result"], json!({ "root": null }), "{}", replies[0]);
|
||||
h.host.close_project_detached("remote");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_tools_of_a_background_project_are_the_same_before_and_after_it_opens() {
|
||||
let h = Harness::new();
|
||||
|
||||
@@ -189,6 +189,36 @@ async fn mcp_listing_dispatch_confirmation_and_lifecycle_use_plugin_authority()
|
||||
assert!(spin.await.unwrap().is_err(), "command budget interrupts wasm");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn plugin_tools_take_the_project_path_and_refuse_an_untrusted_project_before_it_loads() {
|
||||
let f = Harness::with_timeout(Duration::from_secs(10));
|
||||
f.host.set_project_trust(&f.root, true, false).await.unwrap();
|
||||
let inventory = f.root.parent().unwrap().join("inventory");
|
||||
std::fs::create_dir(&inventory).unwrap();
|
||||
for (key, value) in [
|
||||
("enabled", serde_json::json!(true)),
|
||||
("backgroundProjects", serde_json::json!("listed")),
|
||||
("backgroundProjectPaths", serde_json::json!([inventory])),
|
||||
] {
|
||||
let key = format!("mcpServer.{key}");
|
||||
f.host.global_settings.set(ide_workspace::SettingsScope::Global, &key, value).unwrap();
|
||||
}
|
||||
let registry = Registry::new(f.host.clone());
|
||||
// A connection without a project of its own lists the tool with `projectPath`, which its
|
||||
// calls have to pass, and the plugin's strict schema still takes the call.
|
||||
let listed = registry.tools_without_project();
|
||||
let echo = listed.iter().find(|t| t.name == "test_data_tools__echo").unwrap();
|
||||
assert!(echo.input_schema["properties"]["projectPath"].is_object(), "{}", echo.input_schema);
|
||||
let arguments = serde_json::json!({ "text": "hello", "projectPath": f.root }).to_string();
|
||||
let result = registry.call(&f.root, "test_data_tools__echo", &arguments, CancellationToken::new()).unwrap();
|
||||
assert!(result.contains("hello"), "{result}");
|
||||
// A tool that writes refuses the untrusted folder, and nothing loads.
|
||||
let refused = registry.call(&inventory, "test_data_tools__write", "{}", CancellationToken::new()).unwrap_err();
|
||||
let restricted = "Project is in Restricted Mode. Trust the project to enable execution.";
|
||||
assert_eq!(refused, ToolCallError::Failed(restricted.into()));
|
||||
assert!(f.host.mcp_background.snapshot(&f.host, std::time::Instant::now()).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_plugin_tool_call_holds_its_background_project_until_it_ends() {
|
||||
use ide_host::mcp::{BackgroundProjects, McpBackgroundHold};
|
||||
|
||||
@@ -9,7 +9,11 @@
|
||||
//! `Origin` or `Host` are refused (DNS rebinding).
|
||||
//! - **Projects:** the `X-OpenIDEA-Project` header or the `?project=` query
|
||||
//! names a folder; the server picks the open project containing it, or the
|
||||
//! project the IDE serves it from without a window.
|
||||
//! project the IDE serves it from without a window. A connection whose
|
||||
//! folder no project serves lists the tools a trusted project gets, and each
|
||||
//! call names its project with `projectPath`. `openidea/servesFolder`
|
||||
//! answers which project serves the connection's folder (`{"root": null}`
|
||||
//! for none).
|
||||
//! - **Discovery:** `<app-data>/mcp/server.json` (`address`, `port`, `token`,
|
||||
//! `pid`, `version`; readable only by the user) while the server runs.
|
||||
//! - **Stdio:** `<app exe> --mcp-stdio [--project <path>]` reads the discovery
|
||||
@@ -76,6 +80,12 @@ pub trait ToolRegistry: Send + Sync + 'static {
|
||||
/// The tools callable for `project` (one of [`Self::projects`] or a root
|
||||
/// [`Self::resolve`] gave). `Err` says why there are none (an unsupported project).
|
||||
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String>;
|
||||
/// The tools listed on a connection whose project doesn't resolve (a folder no project
|
||||
/// serves, or no folder and not exactly one window): those a trusted project gets. Each
|
||||
/// call still resolves its project and refuses by that project's trust.
|
||||
fn tools_without_project(&self) -> Vec<Tool> {
|
||||
Vec::new()
|
||||
}
|
||||
fn call_with_client(
|
||||
&self,
|
||||
project: &Path,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! MCP over JSON-RPC 2.0: `initialize`, `ping`, `tools/list`, `tools/call`
|
||||
//! and notifications, for one POST body (a message or a batch). Blocking: the
|
||||
//! server runs it on a blocking thread.
|
||||
//! MCP over JSON-RPC 2.0: `initialize`, `ping`, `tools/list`, `tools/call`,
|
||||
//! our own `openidea/servesFolder` and notifications, for one POST body (a
|
||||
//! message or a batch). Blocking: the server runs it on a blocking thread.
|
||||
|
||||
use crate::{CancellationToken, Tool, ToolCallError, ToolRegistry};
|
||||
use serde_json::{Value, json};
|
||||
@@ -26,16 +26,22 @@ impl Drop for InFlight<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a cancellation that arrived before its call is kept.
|
||||
const EARLY_CANCELLATION: std::time::Duration = std::time::Duration::from_secs(60);
|
||||
|
||||
/// The protocol version answered when the client asks for one this server doesn't know.
|
||||
pub(crate) const LATEST: &str = "2025-06-18";
|
||||
pub(crate) const SUPPORTED: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"];
|
||||
|
||||
const PARSE_ERROR: i64 = -32700;
|
||||
const INVALID_REQUEST: i64 = -32600;
|
||||
const METHOD_NOT_FOUND: i64 = -32601;
|
||||
pub(crate) const METHOD_NOT_FOUND: i64 = -32601;
|
||||
const INVALID_PARAMS: i64 = -32602;
|
||||
/// The requested folder isn't in a project the IDE serves (or has no tools there).
|
||||
pub(crate) const NOT_OPEN: i64 = -32001;
|
||||
/// Which project serves the connection's folder: `{"root": "<path>"}`, or `{"root": null}`
|
||||
/// for none. The stdio bridge asks it to pick the IDE process for its folder.
|
||||
pub(crate) const SERVES_FOLDER: &str = "openidea/servesFolder";
|
||||
|
||||
pub(crate) struct RpcError {
|
||||
code: i64,
|
||||
@@ -105,7 +111,12 @@ impl Session<'_> {
|
||||
let mut state = self.requests.0.lock().unwrap();
|
||||
if let Some(cancel) = state.running.get(&key) {
|
||||
cancel.cancel();
|
||||
} else if state.early.len() < 1024 {
|
||||
return None;
|
||||
}
|
||||
// The stdio bridge sends a cancellation to every server, so one that runs few
|
||||
// calls drops the stale ones here as well.
|
||||
state.early.retain(|_, at| at.elapsed() < EARLY_CANCELLATION);
|
||||
if state.early.len() < 1024 {
|
||||
state.early.insert(key, std::time::Instant::now());
|
||||
}
|
||||
}
|
||||
@@ -116,7 +127,7 @@ impl Session<'_> {
|
||||
let cancel = self.cancel.child_token();
|
||||
{
|
||||
let mut requests = self.requests.0.lock().unwrap();
|
||||
requests.early.retain(|_, at| at.elapsed() < std::time::Duration::from_secs(60));
|
||||
requests.early.retain(|_, at| at.elapsed() < EARLY_CANCELLATION);
|
||||
if requests.running.contains_key(&key) {
|
||||
return Some(error_response(id, INVALID_REQUEST, "request id already in flight"));
|
||||
}
|
||||
@@ -139,11 +150,18 @@ impl Session<'_> {
|
||||
"initialize" => Ok(self.initialize(¶ms)),
|
||||
"ping" => Ok(json!({})),
|
||||
"tools/list" => {
|
||||
let project = self.project()?;
|
||||
let tools = self.registry.tools(&project).map_err(|e| RpcError::new(NOT_OPEN, e))?;
|
||||
let tools = match self.project() {
|
||||
Ok(project) => self.registry.tools(&project).map_err(|e| RpcError::new(NOT_OPEN, e))?,
|
||||
Err(_) => self.registry.tools_without_project(),
|
||||
};
|
||||
Ok(json!({ "tools": tools.iter().map(tool_json).collect::<Vec<_>>() }))
|
||||
}
|
||||
"tools/call" => self.call(params, cancel),
|
||||
SERVES_FOLDER => {
|
||||
// A root without tools here (a remote window's) is another server's to serve.
|
||||
let root = self.project().ok().filter(|root| self.registry.tools(root).is_ok());
|
||||
Ok(json!({ "root": root.map(|root| root.display().to_string()) }))
|
||||
}
|
||||
_ => Err(RpcError::new(METHOD_NOT_FOUND, format!("no method {method:?}"))),
|
||||
}
|
||||
}
|
||||
@@ -157,9 +175,13 @@ impl Session<'_> {
|
||||
}
|
||||
let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or(LATEST);
|
||||
let version = if SUPPORTED.contains(&asked) { asked } else { LATEST };
|
||||
let about = match self.project() {
|
||||
Ok(root) => format!("the project OpenIDEA serves at {}", root.display()),
|
||||
Err(_) => "a project open in OpenIDEA or served in the background".to_owned(),
|
||||
let (about, without_project) = match self.project() {
|
||||
Ok(root) => (format!("the project OpenIDEA serves at {}", root.display()), ""),
|
||||
Err(_) => (
|
||||
"a project open in OpenIDEA or served in the background".to_owned(),
|
||||
" This connection has no project of its own: pass `projectPath`, a folder inside a project \
|
||||
OpenIDEA serves, in every call, `get_workspace_roots` included.",
|
||||
),
|
||||
};
|
||||
json!({
|
||||
"protocolVersion": version,
|
||||
@@ -174,7 +196,7 @@ impl Session<'_> {
|
||||
its `roots` are every project in the IDE workspace. That is the scope to search and read, \
|
||||
not a list of projects to change; it doesn't change your working directory or \
|
||||
permissions. Pass another root as `projectPath` to reach that project. Call it again \
|
||||
when the user switches projects or attaches one."
|
||||
when the user switches projects or attaches one.{without_project}"
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! running IDE's server, found through the discovery file.
|
||||
|
||||
use crate::discovery::Discovery;
|
||||
use crate::protocol::{NOT_OPEN, error_response};
|
||||
use crate::protocol::{METHOD_NOT_FOUND, NOT_OPEN, SERVES_FOLDER, error_response};
|
||||
use bytes::Bytes;
|
||||
use http_body_util::{BodyExt, Full};
|
||||
use hyper::{Request, StatusCode, header};
|
||||
@@ -17,7 +17,11 @@ use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt};
|
||||
|
||||
#[derive(Default)]
|
||||
struct BridgeState {
|
||||
preferred: Option<SocketAddr>,
|
||||
/// The server that serves the connection's folder, or the first one when none does. A
|
||||
/// server restarted on its port is another one: its entry names another process or token.
|
||||
preferred: Option<Discovery>,
|
||||
/// The servers there were when `preferred` was picked: one started since may serve the folder.
|
||||
picked_among: Vec<Discovery>,
|
||||
init_message: Option<Value>,
|
||||
initialized_on: HashSet<SocketAddr>,
|
||||
}
|
||||
@@ -171,18 +175,28 @@ async fn post(
|
||||
if candidates.is_empty() {
|
||||
return Err(not_running());
|
||||
}
|
||||
if let Some(preferred) = state.lock().unwrap().preferred
|
||||
&& let Some(pos) = candidates.iter().position(|c| SocketAddr::new(c.address, c.port) == preferred)
|
||||
{
|
||||
if message.get("method").and_then(Value::as_str) == Some("notifications/cancelled") {
|
||||
return cancel_everywhere(candidates, project, message, scope, sent).await.ok_or_else(not_running);
|
||||
}
|
||||
let preferred = state.lock().unwrap().preferred.clone();
|
||||
if let Some(pos) = preferred.and_then(|preferred| candidates.iter().position(|c| *c == preferred)) {
|
||||
let chosen = candidates.remove(pos);
|
||||
candidates.insert(0, chosen);
|
||||
}
|
||||
// `initialize` picks the server that serves the connection's folder, and later messages
|
||||
// keep it: a call whose `projectPath` another server serves doesn't move `tools/list`
|
||||
// there. A message after that server stopped, or after another one started, picks again.
|
||||
let initializing = is_initialize(message);
|
||||
let mut fallback: Option<(SocketAddr, Answer)> = None;
|
||||
if !initializing {
|
||||
pick_again(&mut candidates, project, scope, state).await;
|
||||
}
|
||||
let listed = candidates.clone();
|
||||
let mut answered = None;
|
||||
let mut fallback: Option<(Discovery, Answer)> = None;
|
||||
let mut last_error: Option<String> = None;
|
||||
let total = candidates.len();
|
||||
for (idx, info) in candidates.into_iter().enumerate() {
|
||||
let at = SocketAddr::new(info.address, info.port);
|
||||
let at = address(&info);
|
||||
if !initializing {
|
||||
let init = {
|
||||
let guard = state.lock().unwrap();
|
||||
@@ -190,7 +204,7 @@ async fn post(
|
||||
};
|
||||
if let Some(mut init_msg) = init {
|
||||
if let Some(obj) = init_msg.as_object_mut() {
|
||||
obj.insert("id".into(), Value::String(format!("__openidea_init_{idx}__")));
|
||||
obj.insert("id".into(), Value::String(own_id("init")));
|
||||
}
|
||||
if post_one(&info, project, &init_msg, scope, sent).await.is_ok() {
|
||||
state.lock().unwrap().initialized_on.insert(at);
|
||||
@@ -202,34 +216,120 @@ async fn post(
|
||||
if initializing {
|
||||
state.lock().unwrap().initialized_on.insert(at);
|
||||
if total > 1 && !serves_project(&info, project, scope).await {
|
||||
fallback.get_or_insert((at, answer));
|
||||
fallback.get_or_insert((info, answer));
|
||||
continue;
|
||||
}
|
||||
} else if idx + 1 < total && is_not_open_reply(&answer) {
|
||||
fallback = Some((at, answer));
|
||||
fallback = Some((info, answer));
|
||||
continue;
|
||||
}
|
||||
state.lock().unwrap().preferred = Some(at);
|
||||
return Ok(answer);
|
||||
answered = Some((info, answer));
|
||||
break;
|
||||
}
|
||||
Err(err) => last_error = Some(err),
|
||||
}
|
||||
}
|
||||
if let Some((at, answer)) = fallback {
|
||||
state.lock().unwrap().preferred = Some(at);
|
||||
return Ok(answer);
|
||||
let Some((info, answer)) = answered.or(fallback) else {
|
||||
return Err(last_error.unwrap_or_else(not_running));
|
||||
};
|
||||
if initializing {
|
||||
let mut state = state.lock().unwrap();
|
||||
state.preferred = Some(info);
|
||||
state.picked_among = listed;
|
||||
}
|
||||
Err(last_error.unwrap_or_else(not_running))
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// Whether the server of `info` has `project` open: its `tools/list` doesn't answer "not open".
|
||||
async fn serves_project(info: &Discovery, project: &Path, scope: &str) -> bool {
|
||||
let probe = serde_json::json!({ "jsonrpc": "2.0", "id": "__openidea_probe__", "method": "tools/list" });
|
||||
let (discard, _) = tokio::sync::mpsc::unbounded_channel();
|
||||
match post_one(info, project, &probe, scope, &discard).await {
|
||||
Ok(answer @ Answer::Body(StatusCode::OK, _)) => !is_not_open_reply(&answer),
|
||||
_ => false,
|
||||
fn address(info: &Discovery) -> SocketAddr {
|
||||
SocketAddr::new(info.address, info.port)
|
||||
}
|
||||
|
||||
/// An id of the bridge's own for a request it makes: concurrent messages can make one to the
|
||||
/// same server at once, and a server refuses an id that is already in flight.
|
||||
fn own_id(kind: &str) -> String {
|
||||
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
format!("__openidea_{kind}_{}__", NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// How long a server has to answer a probe or take a cancellation.
|
||||
const PROBE_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// Sends a cancellation to every server at once, since the call may run in any of them (its
|
||||
/// `projectPath` picks one); the answer of one that took it. A server that doesn't run the call
|
||||
/// keeps the id for a while, in case the call reaches it later. One that doesn't answer in
|
||||
/// time holds up neither the others nor the bridge.
|
||||
async fn cancel_everywhere(
|
||||
candidates: Vec<Discovery>,
|
||||
project: &Path,
|
||||
message: &Value,
|
||||
scope: &str,
|
||||
sent: &tokio::sync::mpsc::UnboundedSender<Value>,
|
||||
) -> Option<Answer> {
|
||||
let mut posts = tokio::task::JoinSet::new();
|
||||
for info in candidates {
|
||||
let (project, message, scope, sent) = (project.to_owned(), message.clone(), scope.to_owned(), sent.clone());
|
||||
posts.spawn(async move {
|
||||
tokio::time::timeout(PROBE_WAIT, post_one(&info, &project, &message, &scope, &sent)).await
|
||||
});
|
||||
}
|
||||
let mut accepted = None;
|
||||
while let Some(posted) = posts.join_next().await {
|
||||
if let Ok(Ok(Ok(answer))) = posted {
|
||||
accepted.get_or_insert(answer);
|
||||
}
|
||||
}
|
||||
accepted
|
||||
}
|
||||
|
||||
/// Picks the server for the connection's folder again when the one picked is gone or another
|
||||
/// server started since, as `initialize` picks it: the first of `candidates` (the one picked
|
||||
/// before leads) that serves the folder, else the first. Puts it first.
|
||||
async fn pick_again(candidates: &mut Vec<Discovery>, project: &Path, scope: &str, state: &Mutex<BridgeState>) {
|
||||
{
|
||||
let state = state.lock().unwrap();
|
||||
let kept = state.preferred.as_ref().is_some_and(|preferred| candidates.contains(preferred));
|
||||
if kept && candidates.iter().all(|c| state.picked_among.contains(c)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let mut chosen = 0;
|
||||
if candidates.len() > 1 {
|
||||
for (pos, info) in candidates.iter().enumerate() {
|
||||
if serves_project(info, project, scope).await {
|
||||
chosen = pos;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let picked = candidates.remove(chosen);
|
||||
candidates.insert(0, picked);
|
||||
let mut state = state.lock().unwrap();
|
||||
state.preferred = Some(candidates[0].clone());
|
||||
state.picked_among = candidates.clone();
|
||||
}
|
||||
|
||||
/// Whether the server of `info` serves `project`: its `openidea/servesFolder` names a root.
|
||||
/// An IDE older than that method answers "method not found"; its `tools/list` answers "not
|
||||
/// open" for a folder it doesn't serve, so that answers instead. A server that doesn't answer
|
||||
/// in time doesn't serve it.
|
||||
async fn serves_project(info: &Discovery, project: &Path, scope: &str) -> bool {
|
||||
let probe = |method| serde_json::json!({ "jsonrpc": "2.0", "id": own_id("probe"), "method": method });
|
||||
let (discard, _) = tokio::sync::mpsc::unbounded_channel();
|
||||
let ask = async {
|
||||
let reply = match post_one(info, project, &probe(SERVES_FOLDER), scope, &discard).await {
|
||||
Ok(Answer::Body(StatusCode::OK, body)) => serde_json::from_slice::<Value>(&body).ok(),
|
||||
_ => None,
|
||||
};
|
||||
let Some(reply) = reply else { return false };
|
||||
if reply.pointer("/error/code").and_then(Value::as_i64) == Some(METHOD_NOT_FOUND) {
|
||||
return match post_one(info, project, &probe("tools/list"), scope, &discard).await {
|
||||
Ok(answer @ Answer::Body(StatusCode::OK, _)) => !is_not_open_reply(&answer),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
reply.pointer("/result/root").is_some_and(Value::is_string)
|
||||
};
|
||||
tokio::time::timeout(PROBE_WAIT, ask).await.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn is_not_open_reply(answer: &Answer) -> bool {
|
||||
@@ -253,7 +353,7 @@ async fn post_one(
|
||||
project.display()
|
||||
)
|
||||
};
|
||||
let at = SocketAddr::new(info.address, info.port);
|
||||
let at = address(info);
|
||||
let stream = tokio::net::TcpStream::connect(at).await.map_err(|_| not_running())?;
|
||||
let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream))
|
||||
.await
|
||||
|
||||
@@ -5,7 +5,7 @@ use ide_mcp::{Discovery, McpServer, ServerOptions, Tool, ToolCallError, ToolRegi
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
struct Registry {
|
||||
project: PathBuf,
|
||||
@@ -28,6 +28,10 @@ impl ToolRegistry for Registry {
|
||||
}])
|
||||
}
|
||||
|
||||
fn tools_without_project(&self) -> Vec<Tool> {
|
||||
vec![named("everything")]
|
||||
}
|
||||
|
||||
fn call(
|
||||
&self,
|
||||
project: &Path,
|
||||
@@ -48,6 +52,18 @@ impl ToolRegistry for Registry {
|
||||
}
|
||||
}
|
||||
|
||||
/// A read-only tool with no arguments.
|
||||
fn named(name: &str) -> Tool {
|
||||
Tool {
|
||||
name: name.into(),
|
||||
description: format!("The tool {name}"),
|
||||
input_schema: json!({ "type": "object" }),
|
||||
read_only: true,
|
||||
destructive: false,
|
||||
output_schema: None,
|
||||
}
|
||||
}
|
||||
|
||||
struct Setup {
|
||||
_tmp: tempfile::TempDir,
|
||||
project: PathBuf,
|
||||
@@ -215,25 +231,30 @@ async fn requests_without_the_token_or_from_web_pages_are_refused() {
|
||||
async fn folders_that_are_not_open_are_named_in_the_error() {
|
||||
let s = setup();
|
||||
let elsewhere = s.project.parent().unwrap().join("elsewhere");
|
||||
let header = format!("X-OpenIDEA-Project: {}", elsewhere.display());
|
||||
let (status, body) =
|
||||
post(&s, "/mcp", &[&bearer(&s), &header], &json!({"jsonrpc":"2.0","id":3,"method":"tools/list"})).await;
|
||||
assert_eq!(status, 200);
|
||||
let reply: Value = serde_json::from_str(&body).unwrap();
|
||||
assert!(reply["error"]["message"].as_str().unwrap().contains("isn't open in OpenIDEA"));
|
||||
// The connection's folder isn't open: the list is the one without a project, and a call
|
||||
// that names no project of its own is refused with the folder named.
|
||||
let list = rpc_for(&s, &elsewhere, "tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["name"], "everything", "{list}");
|
||||
let call = rpc_for(&s, &elsewhere, "tools/call", json!({ "name": "echo" })).await;
|
||||
assert_eq!(call["error"]["code"], -32001, "{call}");
|
||||
let message = call["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("isn't open in OpenIDEA") && message.contains(elsewhere.to_str().unwrap()), "{message}");
|
||||
// No folder named and one window: that window's project lists its tools.
|
||||
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &json!({"jsonrpc":"2.0","id":3,"method":"tools/list"})).await;
|
||||
assert!(serde_json::from_str::<Value>(&body).unwrap()["result"]["tools"].is_array());
|
||||
assert_eq!(serde_json::from_str::<Value>(&body).unwrap()["result"]["tools"][0]["name"], "echo");
|
||||
}
|
||||
|
||||
/// One project open in a window and the folders served without a window.
|
||||
/// One project open in a window, the folders served without a window and, optionally, the
|
||||
/// root of a window on a remote host (which has no tools here).
|
||||
struct WithBackground {
|
||||
open: PathBuf,
|
||||
background: Vec<PathBuf>,
|
||||
remote: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl ToolRegistry for WithBackground {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
vec![self.open.clone()]
|
||||
std::iter::once(self.open.clone()).chain(self.remote.clone()).collect()
|
||||
}
|
||||
/// The innermost served folder containing `path`, strictly inside `within`, as the
|
||||
/// background policy answers.
|
||||
@@ -242,7 +263,13 @@ impl ToolRegistry for WithBackground {
|
||||
let served = self.background.iter().filter(|root| path.starts_with(root)).filter(inside);
|
||||
served.max_by_key(|root| root.components().count()).cloned()
|
||||
}
|
||||
fn tools_without_project(&self) -> Vec<Tool> {
|
||||
vec![named("anything")]
|
||||
}
|
||||
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String> {
|
||||
if self.remote.as_deref() == Some(project) {
|
||||
return Err("project is on a remote host".into());
|
||||
}
|
||||
Ok(vec![Tool {
|
||||
name: "where".into(),
|
||||
description: format!("Names {}", project.display()),
|
||||
@@ -257,20 +284,23 @@ impl ToolRegistry for WithBackground {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops the server of `s` and serves `registry` in its place.
|
||||
fn restart(s: &mut Setup, registry: impl ToolRegistry) {
|
||||
s.server.take().unwrap().stop();
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
s.server = Some(McpServer::start_with(Arc::new(registry), None, &runtime, ServerOptions::default()).unwrap());
|
||||
}
|
||||
|
||||
/// The server over [`WithBackground`] serving the `served` folders, relative to the folder
|
||||
/// that holds the open project; the folder `inventory` next to the open project.
|
||||
fn setup_with_background(served: &[&str]) -> (Setup, PathBuf) {
|
||||
let mut s = setup();
|
||||
s.server.take().unwrap().stop();
|
||||
let base = s.project.parent().unwrap().to_path_buf();
|
||||
let inventory = base.join("inventory");
|
||||
std::fs::create_dir_all(inventory.join("src")).unwrap();
|
||||
let background = served.iter().map(|folder| base.join(folder).components().collect()).collect();
|
||||
let registry = WithBackground { open: s.project.clone(), background };
|
||||
s.server = Some(
|
||||
McpServer::start_with(Arc::new(registry), None, &tokio::runtime::Handle::current(), ServerOptions::default())
|
||||
.unwrap(),
|
||||
);
|
||||
let registry = WithBackground { open: s.project.clone(), background, remote: None };
|
||||
restart(&mut s, registry);
|
||||
(s, inventory)
|
||||
}
|
||||
|
||||
@@ -291,6 +321,7 @@ async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
|
||||
assert!(instructions.contains(inventory.to_str().unwrap()), "{instructions}");
|
||||
// Clients that load tool descriptions lazily still learn to establish the workspace first (#5751).
|
||||
assert!(instructions.contains("first project-related operation in a session, call `get_workspace_roots`"));
|
||||
assert!(!instructions.contains("no project of its own"), "{instructions}");
|
||||
let list = rpc_for(&s, &inside, "tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", inventory.display()), "{list}");
|
||||
let call = rpc_for(&s, &inside, "tools/call", json!({ "name": "where" })).await;
|
||||
@@ -334,16 +365,41 @@ async fn the_innermost_project_answers_whether_a_window_has_it_open_or_it_is_ser
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_folder_that_is_neither_open_nor_served_in_the_background_says_where_to_turn_it_on() {
|
||||
let (s, inventory) = setup_with_background(&[]);
|
||||
for (method, params) in [("tools/list", json!({})), ("tools/call", json!({ "name": "where" }))] {
|
||||
let reply = rpc_for(&s, &inventory, method, params).await;
|
||||
assert_eq!(reply["error"]["code"], -32001, "{method}: {reply}");
|
||||
let message = reply["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("isn't open in OpenIDEA and isn't served in the background"), "{message}");
|
||||
assert!(message.contains("Settings › Agents › IDE MCP Server"), "{message}");
|
||||
assert!(message.contains(inventory.to_str().unwrap()) && message.contains(s.project.to_str().unwrap()));
|
||||
}
|
||||
let list = rpc_for(&s, &inventory, "tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["name"], "anything", "{list}");
|
||||
let reply = rpc_for(&s, &inventory, "tools/call", json!({ "name": "where" })).await;
|
||||
assert_eq!(reply["error"]["code"], -32001, "{reply}");
|
||||
let message = reply["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("isn't open in OpenIDEA and isn't served in the background"), "{message}");
|
||||
assert!(message.contains("Settings › Agents › IDE MCP Server"), "{message}");
|
||||
assert!(message.contains(inventory.to_str().unwrap()) && message.contains(s.project.to_str().unwrap()));
|
||||
let init = rpc_for(&s, &inventory, "initialize", json!({})).await;
|
||||
assert!(init["result"]["instructions"].is_string(), "initialize answers without a project: {init}");
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
assert!(
|
||||
instructions.contains("pass `projectPath`, a folder inside a project OpenIDEA serves, in every call"),
|
||||
"{instructions}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn serves_folder_names_the_project_that_answers_for_the_connection_folder() {
|
||||
let (mut s, inventory) = setup_with_background(&[]);
|
||||
let base = s.project.parent().unwrap().to_owned();
|
||||
let remote = base.join("remote");
|
||||
let registry =
|
||||
WithBackground { open: s.project.clone(), background: vec![inventory.clone()], remote: Some(remote.clone()) };
|
||||
restart(&mut s, registry);
|
||||
let cases = [
|
||||
(s.project.join("src"), json!(s.project)),
|
||||
(inventory.join("src"), json!(inventory)),
|
||||
(base.join("elsewhere"), Value::Null),
|
||||
// A remote window's root is that host's to serve.
|
||||
(remote, Value::Null),
|
||||
];
|
||||
for (folder, root) in cases {
|
||||
let reply = rpc_for(&s, &folder, "openidea/servesFolder", json!({})).await;
|
||||
assert_eq!(reply["result"], json!({ "root": root }), "{}: {reply}", folder.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -413,6 +469,9 @@ async fn routing_an_argument_overrides_the_header_and_ambiguity_lists_projects()
|
||||
fn tools(&self, _: &Path) -> Result<Vec<Tool>, String> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn tools_without_project(&self) -> Vec<Tool> {
|
||||
vec![named("anywhere")]
|
||||
}
|
||||
fn call(
|
||||
&self,
|
||||
project: &Path,
|
||||
@@ -436,8 +495,14 @@ async fn routing_an_argument_overrides_the_header_and_ambiguity_lists_projects()
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
// No folder named and two windows: the list without a project, and a call has to name one.
|
||||
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &json!({"jsonrpc":"2.0","id":1,"method":"tools/list"})).await;
|
||||
let list: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(list["result"]["tools"][0]["name"], "anywhere", "{list}");
|
||||
let call = json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"where"}});
|
||||
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &call).await;
|
||||
let reply: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(reply["error"]["code"], -32602, "{reply}");
|
||||
let message = reply["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains(s.project.to_str().unwrap()) && message.contains(second.to_str().unwrap()));
|
||||
let result = rpc(&s, "tools/call", json!({"name":"where","arguments":{"projectPath":second.join("nested")}})).await;
|
||||
@@ -624,3 +689,360 @@ async fn multiple_servers_sharing_app_data_route_by_project_and_survive_one_clos
|
||||
server_a.stop();
|
||||
assert!(!discovery.exists());
|
||||
}
|
||||
|
||||
/// The stdio bridge started in `folder`, driven as MCP clients drive it: each request goes
|
||||
/// out once the answer to the one before has come back.
|
||||
struct Client {
|
||||
input: tokio::io::DuplexStream,
|
||||
output: tokio::io::Lines<tokio::io::BufReader<tokio::io::DuplexStream>>,
|
||||
bridge: tokio::task::JoinHandle<std::io::Result<()>>,
|
||||
id: u64,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
fn start(discovery: &Path, folder: &Path) -> Self {
|
||||
let (input, bridge_input) = tokio::io::duplex(1 << 16);
|
||||
let (bridge_output, output) = tokio::io::duplex(1 << 16);
|
||||
let (discovery, folder) = (discovery.to_owned(), folder.to_owned());
|
||||
let bridge = tokio::spawn(async move {
|
||||
stdio::bridge(&discovery, &folder, tokio::io::BufReader::new(bridge_input), bridge_output).await
|
||||
});
|
||||
Self { input, output: tokio::io::BufReader::new(output).lines(), bridge, id: 0 }
|
||||
}
|
||||
|
||||
/// Sends a request without waiting for its answer; its id.
|
||||
async fn send(&mut self, method: &str, params: Value) -> u64 {
|
||||
self.id += 1;
|
||||
self.notify(json!({ "jsonrpc": "2.0", "id": self.id, "method": method, "params": params })).await;
|
||||
self.id
|
||||
}
|
||||
|
||||
async fn notify(&mut self, message: Value) {
|
||||
self.input.write_all(format!("{message}\n").as_bytes()).await.unwrap();
|
||||
}
|
||||
|
||||
async fn answer(&mut self, id: u64) -> Value {
|
||||
let answer = async {
|
||||
loop {
|
||||
let line = self.output.next_line().await.unwrap().expect("the bridge answers");
|
||||
let reply: Value = serde_json::from_str(&line).unwrap();
|
||||
if reply["id"] == id {
|
||||
return reply;
|
||||
}
|
||||
}
|
||||
};
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), answer).await.expect("an answer in time")
|
||||
}
|
||||
|
||||
async fn ask(&mut self, method: &str, params: Value) -> Value {
|
||||
let id = self.send(method, params).await;
|
||||
self.answer(id).await
|
||||
}
|
||||
|
||||
async fn close(self) {
|
||||
let Self { input, output, bridge, .. } = self;
|
||||
drop(input);
|
||||
bridge.await.unwrap().unwrap();
|
||||
drop(output);
|
||||
}
|
||||
}
|
||||
|
||||
fn start_in(discovery: &Path, registry: impl ToolRegistry) -> McpServer {
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
McpServer::start_with(Arc::new(registry), Some(discovery.to_owned()), &runtime, ServerOptions::default()).unwrap()
|
||||
}
|
||||
|
||||
/// A temporary folder holding `folders` (each with a `src`), and the discovery file of the
|
||||
/// servers that share its data directory.
|
||||
fn layout(folders: &[&str]) -> (tempfile::TempDir, PathBuf, PathBuf) {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
for folder in folders {
|
||||
std::fs::create_dir_all(base.join(folder).join("src")).unwrap();
|
||||
}
|
||||
let discovery = discovery_path(&base.join("app-data"));
|
||||
(tmp, base, discovery)
|
||||
}
|
||||
|
||||
impl WithBackground {
|
||||
/// A window on `open` and `background` served without one.
|
||||
fn serving(open: &Path, background: &Path) -> Self {
|
||||
Self { open: open.to_owned(), background: vec![background.to_owned()], remote: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// What an MCP client started in a folder of `proj-b` gets when two servers share the
|
||||
/// discovery directory: A has `proj-a` in a window, B serves `proj-b` in the background.
|
||||
/// Each order makes the other server the one in `server.json`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_bridge_sends_a_folder_to_the_process_that_serves_it_in_either_order() {
|
||||
for b_first in [false, true] {
|
||||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||||
let a = || Registry { project: proj_a.clone() };
|
||||
let b = || WithBackground::serving(&proj_c, &proj_b);
|
||||
let servers = if b_first {
|
||||
[start_in(&discovery, b()), start_in(&discovery, a())]
|
||||
} else {
|
||||
[start_in(&discovery, a()), start_in(&discovery, b())]
|
||||
};
|
||||
|
||||
let mut client = Client::start(&discovery, &proj_b.join("src"));
|
||||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
assert!(instructions.contains(proj_b.to_str().unwrap()), "b_first {b_first}: {instructions}");
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", proj_b.display()), "{list}");
|
||||
let call = client.ask("tools/call", json!({ "name": "where" })).await;
|
||||
assert_eq!(call["result"]["structuredContent"]["project"], json!(proj_b), "{call}");
|
||||
client.close().await;
|
||||
for server in servers {
|
||||
server.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A client started in `work`, a folder neither server serves: the tools of the server
|
||||
/// `initialize` picked, and each call goes where its `projectPath` is served.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_bridge_in_a_folder_no_process_serves_lists_tools_and_routes_each_call_by_project_path() {
|
||||
for b_first in [false, true] {
|
||||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-c", "work/repo"]);
|
||||
let (proj_a, proj_c, work) = (base.join("proj-a"), base.join("proj-c"), base.join("work"));
|
||||
let repo = work.join("repo");
|
||||
let a = || Registry { project: proj_a.clone() };
|
||||
let b = || WithBackground::serving(&proj_c, &repo);
|
||||
// The server started last is in `server.json`; with neither serving the folder,
|
||||
// `initialize` settles on it.
|
||||
let (servers, listed) = if b_first {
|
||||
([start_in(&discovery, b()), start_in(&discovery, a())], "everything")
|
||||
} else {
|
||||
([start_in(&discovery, a()), start_in(&discovery, b())], "anything")
|
||||
};
|
||||
|
||||
let mut client = Client::start(&discovery, &work);
|
||||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
assert!(instructions.contains("no project of its own"), "{instructions}");
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["name"], listed, "b_first {b_first}: {list}");
|
||||
|
||||
let in_repo = json!({ "name": "echo", "arguments": { "text": "x", "projectPath": repo.join("src") } });
|
||||
let call = client.ask("tools/call", in_repo).await;
|
||||
assert_eq!(call["result"]["structuredContent"]["project"], json!(repo), "{call}");
|
||||
let in_a = json!({ "name": "echo", "arguments": { "text": "x", "projectPath": proj_a } });
|
||||
let call = client.ask("tools/call", in_a).await;
|
||||
assert_eq!(call["result"]["content"][0]["text"], format!("x in {}", proj_a.display()), "{call}");
|
||||
let unnamed = client.ask("tools/call", json!({ "name": "echo", "arguments": { "text": "x" } })).await;
|
||||
assert_eq!(unnamed["error"]["code"], -32001, "{unnamed}");
|
||||
// A call sent to the other server doesn't move the connection there.
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["name"], listed, "b_first {b_first}: {list}");
|
||||
client.close().await;
|
||||
for server in servers {
|
||||
server.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The server `initialize` picked stops, or one that serves the folder starts later: the
|
||||
/// next message picks again, as `initialize` does.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_bridge_picks_the_server_again_when_the_servers_change() {
|
||||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||||
let a = || Registry { project: proj_a.clone() };
|
||||
let b = || WithBackground::serving(&proj_c, &proj_b);
|
||||
let serving_b = format!("Names {}", proj_b.display());
|
||||
|
||||
// Only A runs at `initialize`; B starts afterwards.
|
||||
let server_a = start_in(&discovery, a());
|
||||
let mut client = Client::start(&discovery, &proj_b.join("src"));
|
||||
client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
let server_b = start_in(&discovery, b());
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], serving_b, "a server started later: {list}");
|
||||
|
||||
// B restarts, and A restarts after it, so A is first in the discovery file.
|
||||
server_b.stop();
|
||||
let server_b = start_in(&discovery, b());
|
||||
server_a.stop();
|
||||
let server_a = start_in(&discovery, a());
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], serving_b, "the picked server restarted: {list}");
|
||||
client.close().await;
|
||||
server_a.stop();
|
||||
server_b.stop();
|
||||
}
|
||||
|
||||
/// A server restarted on the port it had (a fixed port in the settings) is another server: one
|
||||
/// that didn't serve the folder may serve it now.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_bridge_picks_the_server_again_after_a_restart_on_the_same_port() {
|
||||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||||
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
|
||||
let fixed = ServerOptions { port: Some(port), ..Default::default() };
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
let start_b = |registry: WithBackground| {
|
||||
McpServer::start_with(Arc::new(registry), Some(discovery.clone()), &runtime, fixed.clone()).unwrap()
|
||||
};
|
||||
// Neither serves `proj-b` at `initialize`, which settles on A, the server started last.
|
||||
let server_b = start_b(WithBackground { open: proj_c.clone(), background: Vec::new(), remote: None });
|
||||
let server_a = start_in(&discovery, Registry { project: proj_a.clone() });
|
||||
let mut client = Client::start(&discovery, &proj_b.join("src"));
|
||||
client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["name"], "everything", "{list}");
|
||||
|
||||
server_b.stop();
|
||||
let server_b = start_b(WithBackground::serving(&proj_c, &proj_b));
|
||||
assert_eq!(server_b.port(), port);
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", proj_b.display()), "{list}");
|
||||
client.close().await;
|
||||
server_a.stop();
|
||||
server_b.stop();
|
||||
}
|
||||
|
||||
/// Holds every call until it is cancelled: a window on `open`, `background` served without one.
|
||||
struct Holding {
|
||||
open: PathBuf,
|
||||
background: PathBuf,
|
||||
}
|
||||
|
||||
impl ToolRegistry for Holding {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
vec![self.open.clone()]
|
||||
}
|
||||
fn resolve(&self, path: &Path, _: Option<&Path>) -> Option<PathBuf> {
|
||||
path.starts_with(&self.background).then(|| self.background.clone())
|
||||
}
|
||||
fn tools(&self, _: &Path) -> Result<Vec<Tool>, String> {
|
||||
Ok(vec![named("hold")])
|
||||
}
|
||||
fn call(&self, _: &Path, _: &str, _: &str, cancel: ide_mcp::CancellationToken) -> Result<String, ToolCallError> {
|
||||
tokio::runtime::Handle::current().block_on(cancel.cancelled());
|
||||
Err(ToolCallError::Failed("cancelled".into()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The connection is A's, and a call whose `projectPath` B serves runs in B: its
|
||||
/// cancellation reaches B.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_cancellation_reaches_the_server_that_runs_the_call() {
|
||||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||||
let server_b = start_in(&discovery, Holding { open: proj_c, background: proj_b.clone() });
|
||||
let server_a = start_in(&discovery, Registry { project: proj_a.clone() });
|
||||
|
||||
let mut client = Client::start(&discovery, &proj_a);
|
||||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
assert!(init["result"]["instructions"].as_str().unwrap().contains(proj_a.to_str().unwrap()), "{init}");
|
||||
let call = client.send("tools/call", json!({ "name": "hold", "arguments": { "projectPath": proj_b } })).await;
|
||||
client
|
||||
.notify(json!({ "jsonrpc": "2.0", "method": "notifications/cancelled", "params": { "requestId": call } }))
|
||||
.await;
|
||||
let answer = client.answer(call).await;
|
||||
assert_eq!(answer["result"]["isError"], true, "{answer}");
|
||||
client.close().await;
|
||||
server_a.stop();
|
||||
server_b.stop();
|
||||
}
|
||||
|
||||
/// An OpenIDEA older than `openidea/servesFolder`, registered in `discovery`: it answers
|
||||
/// "method not found" to that, and "not open" to `tools/list` and `tools/call` for a folder
|
||||
/// outside `serves`.
|
||||
async fn fake_older_ide(discovery: &Path, serves: Option<PathBuf>) -> tokio::task::JoinHandle<()> {
|
||||
use http_body_util::{BodyExt, Full};
|
||||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = tokio::spawn(async move {
|
||||
while let Ok((stream, _)) = listener.accept().await {
|
||||
let serves = serves.clone();
|
||||
let service = hyper::service::service_fn(move |request: hyper::Request<hyper::body::Incoming>| {
|
||||
let serves = serves.clone();
|
||||
async move {
|
||||
let query = request.uri().query().unwrap_or_default().to_owned();
|
||||
let folder = query.strip_prefix("project=").unwrap_or_default();
|
||||
let folder =
|
||||
PathBuf::from(percent_encoding::percent_decode_str(folder).decode_utf8_lossy().as_ref());
|
||||
let body = request.into_body().collect().await.unwrap().to_bytes();
|
||||
let message: Value = serde_json::from_slice(&body).unwrap();
|
||||
let served = serves.as_ref().is_some_and(|root| folder.starts_with(root));
|
||||
let id = message["id"].clone();
|
||||
let reply = match message["method"].as_str().unwrap_or_default() {
|
||||
_ if id.is_null() => None,
|
||||
"initialize" => Some(json!({ "jsonrpc": "2.0", "id": id, "result": {
|
||||
"protocolVersion": "2025-06-18", "capabilities": { "tools": {} },
|
||||
"serverInfo": { "name": "OpenIDEA", "version": "0.1.0" },
|
||||
"instructions": "an older OpenIDEA" } })),
|
||||
"tools/list" if served => {
|
||||
Some(json!({ "jsonrpc": "2.0", "id": id, "result": { "tools": [] } }))
|
||||
}
|
||||
"tools/call" if served => Some(json!({ "jsonrpc": "2.0", "id": id, "result": {
|
||||
"content": [{ "type": "text", "text": "older" }], "isError": false } })),
|
||||
"tools/list" | "tools/call" => Some(
|
||||
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32001, "message": "not open" } }),
|
||||
),
|
||||
_ => Some(
|
||||
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32601, "message": "no method" } }),
|
||||
),
|
||||
};
|
||||
let response = match reply {
|
||||
Some(reply) => hyper::Response::builder()
|
||||
.header("content-type", "application/json")
|
||||
.body(Full::new(bytes::Bytes::from(reply.to_string()))),
|
||||
None => hyper::Response::builder().status(202).body(Full::new(bytes::Bytes::new())),
|
||||
};
|
||||
Ok::<_, std::convert::Infallible>(response.unwrap())
|
||||
}
|
||||
});
|
||||
tokio::spawn(async move {
|
||||
let io = hyper_util::rt::TokioIo::new(stream);
|
||||
let _ = hyper::server::conn::http1::Builder::new().serve_connection(io, service).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
// Written once it listens, so the stale-entry sweep of the next server keeps it.
|
||||
let info = Discovery {
|
||||
address: std::net::Ipv4Addr::LOCALHOST.into(),
|
||||
port,
|
||||
token: "test-token-older".into(),
|
||||
pid: std::process::id(),
|
||||
version: "0.1.0".into(),
|
||||
};
|
||||
info.write(discovery).unwrap();
|
||||
server
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_older_ide_without_serves_folder_is_probed_with_tools_list() {
|
||||
for older_serves in [false, true] {
|
||||
let (_tmp, base, discovery) = layout(&["proj-c", "inventory"]);
|
||||
let (proj_c, folder) = (base.join("proj-c"), base.join("inventory"));
|
||||
// Either way the server that doesn't serve the folder is in `server.json`.
|
||||
let (older, real) = if older_serves {
|
||||
let older = fake_older_ide(&discovery, Some(folder.clone())).await;
|
||||
(older, start_in(&discovery, Registry { project: proj_c.clone() }))
|
||||
} else {
|
||||
let real = start_in(&discovery, WithBackground::serving(&proj_c, &folder));
|
||||
(fake_older_ide(&discovery, None).await, real)
|
||||
};
|
||||
|
||||
let mut client = Client::start(&discovery, &folder.join("src"));
|
||||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
let expected = if older_serves { "an older OpenIDEA".to_owned() } else { folder.display().to_string() };
|
||||
assert!(instructions.contains(&expected), "older_serves {older_serves}: {instructions}");
|
||||
let call = client.ask("tools/call", json!({ "name": "where" })).await;
|
||||
let answered = match older_serves {
|
||||
true => call["result"]["content"][0]["text"] == "older",
|
||||
false => call["result"]["structuredContent"]["project"] == json!(folder),
|
||||
};
|
||||
assert!(answered, "older_serves {older_serves}: {call}");
|
||||
client.close().await;
|
||||
real.stop();
|
||||
older.abort();
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,8 @@ Use the executable path from **Copy Stdio Config**; the macOS path above is only
|
||||
|
||||
OpenIDEA must be running for the tools to work, and the project must be open in a window or served as a [background project](#background-projects). A client may name any folder inside such a project, and the server picks the innermost project that contains it, whether a window has it open or it is served in the background. A project served in the background inside a project open in a window answers for its own folders, so relative paths in a call are relative to its root. For example, with **Trusted projects** a repository inside a trusted location, a Git submodule among them, loads as a background project of its own when a call names its folder, even while a window has the project around it open. HTTP clients name it with the `X-OpenIDEA-Project` header or the `?project=` query.
|
||||
|
||||
A client started in a folder outside every project, such as a folder that only holds repositories, still gets the tools. Each call then names its project with `projectPath`, and the server refuses a call without one.
|
||||
|
||||
While the server runs, OpenIDEA writes its port and token to `mcp/server.json` in its application data directory (readable only by you); the stdio bridge reads it from there.
|
||||
|
||||
## Tools
|
||||
@@ -175,7 +177,7 @@ A background project has no window, so some tools differ:
|
||||
|
||||
## Safety
|
||||
|
||||
- **Untrusted projects** expose only the read-only tools. Tools that write files, rename, reformat, build or run need a project you have trusted.
|
||||
- **Untrusted projects** expose only the read-only tools. Tools that write files, rename, reformat, build or run need a project you have trusted. A client started outside every project sees every tool, and so does one that names no project while no window or several windows are open. A tool that writes or runs still refuses a project you have not trusted.
|
||||
- **Running and building ask first.** `execute_run_configuration`, `build_project`, `run_command` and `http_run_request` show a dialog in OpenIDEA naming the client, the project, the tool and what will run. Choose **Allow** or **Deny**; several requests queue up.
|
||||
- Tools that write refuse paths outside the project.
|
||||
- **Background projects.** Anyone with the token can make the IDE load a project that **Serve without a window** serves, so the setting and the token decide who can open folders on this computer. Listed folders you have not trusted open in Restricted Mode and get only the read-only tools. Keep the list to folders you want agents to reach.
|
||||
|
||||
@@ -78,6 +78,8 @@ stdio 配置大致如下(路径以你机器上的为准):
|
||||
|
||||
工具只在 OpenIDEA 运行,且项目已在窗口中打开或作为[后台项目](#后台项目)提供服务时可用。客户端可以指定这类项目中的任意目录,服务器会选出包含它的最内层项目,无论该项目在窗口中打开还是作为后台项目提供服务。位于窗口项目之内的后台项目负责它自己的目录,调用中的相对路径以它的根目录为准。例如在 **受信任的项目** 模式下,受信任位置中的仓库(包括 Git 子模块)在调用指定它的目录时会作为单独的后台项目加载,即使外层项目已在窗口中打开。HTTP 客户端通过 `X-OpenIDEA-Project` 请求头或 `?project=` 查询参数指定项目。
|
||||
|
||||
如果客户端在所有项目之外的目录中启动,例如只存放仓库的目录,它仍能拿到工具。此时每次调用都要用 `projectPath` 指定项目,服务器会拒绝没有指定项目的调用。
|
||||
|
||||
服务器运行期间,OpenIDEA 会把端口和令牌写入应用数据目录下的 `mcp/server.json`(只有你自己可读),stdio 转发程序从这里读取。
|
||||
|
||||
## 工具
|
||||
@@ -174,7 +176,7 @@ stdio 配置大致如下(路径以你机器上的为准):
|
||||
|
||||
## 安全
|
||||
|
||||
- **未受信任的项目** 只开放只读工具。写文件、重命名、重新格式化、构建或运行的工具都要求项目已被信任。
|
||||
- **未受信任的项目** 只开放只读工具。写文件、重命名、重新格式化、构建或运行的工具都要求项目已被信任。在所有项目之外启动的客户端能看到全部工具;没有打开窗口或打开了多个窗口时,未指定项目的客户端也是如此。会写入或运行的工具仍会拒绝你没有信任的项目。
|
||||
- **运行和构建会先询问。** `execute_run_configuration`、`build_project`、`run_command` 和 `http_run_request` 会在 OpenIDEA 中弹出对话框,说明是哪个客户端、哪个项目、哪个工具以及要运行什么,选择 **允许** 或 **拒绝**;多个请求会排队。
|
||||
- 会写入的工具拒绝项目之外的路径。
|
||||
- **后台项目。** 任何持有令牌的人都能让 IDE 加载 **无窗口时提供服务** 所提供的项目,所以这项设置和令牌共同决定谁能在这台电脑上打开文件夹。你没有信任的列出文件夹会以受限模式打开,只开放只读工具。列表里只放你愿意让智能体访问的文件夹。
|
||||
|
||||
@@ -10,6 +10,7 @@ const config: KnipConfig = {
|
||||
"!src/editor/core/cm/jsp/parser.terms.ts",
|
||||
"!src/editor/core/cm/astro/parser.terms.ts",
|
||||
"!src/editor/core/cm/django/parser.terms.ts",
|
||||
"!src/editor/core/cm/freemarker/parser.terms.ts",
|
||||
"scripts/**/*.ts",
|
||||
"perf/**/*.ts",
|
||||
"evals/**/*.ts",
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"gen:angular-grammar": "lezer-generator src/editor/core/cm/angular/angular.grammar --typeScript -o src/editor/core/cm/angular/parser.ts",
|
||||
"gen:jsp-grammar": "lezer-generator src/editor/core/cm/jsp/jsp.grammar --typeScript -o src/editor/core/cm/jsp/parser.ts",
|
||||
"gen:django-grammar": "lezer-generator src/editor/core/cm/django/django.grammar --typeScript -o src/editor/core/cm/django/parser.ts",
|
||||
"gen:freemarker-grammar": "lezer-generator src/editor/core/cm/freemarker/freemarker.grammar --typeScript -o src/editor/core/cm/freemarker/parser.ts",
|
||||
"gen:astro-grammar": "lezer-generator src/editor/core/cm/astro/astro.grammar --typeScript -o src/editor/core/cm/astro/parser.ts",
|
||||
"gen:theme-docs": "node scripts/theme/gen-docs.ts",
|
||||
"gen:plugin-catalog": "node scripts/gen-plugin-catalog.ts",
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
/**
|
||||
* FreeMarker editor mode: HTML outside the template syntax, FreeMarker inside
|
||||
* directives (`<#if …>`, `<@macro …/>`), interpolations (`${…}`) and comments.
|
||||
* The first directive fixes the tag syntax, angle (`<#if>`) or square (`[#if]`),
|
||||
* as FreeMarker itself does; `[=…]` interpolations count only in square syntax.
|
||||
*/
|
||||
import { LanguageSupport, StreamLanguage, StringStream, type StreamParser } from "@codemirror/language";
|
||||
import { tags } from "@lezer/highlight";
|
||||
|
||||
type State<H> = {
|
||||
html: H;
|
||||
mode: "comment" | "directive" | "interpolation" | null;
|
||||
/** Tag syntax: `null` until the first directive, then square or not. */
|
||||
square: boolean | null;
|
||||
/** What ends the current comment, directive or interpolation. */
|
||||
close: string;
|
||||
/** Brackets open inside the expression; the closer counts only at 0. */
|
||||
depth: number;
|
||||
/** The directive's name comes next. */
|
||||
name: "#" | "@" | null;
|
||||
};
|
||||
|
||||
// `(?=…)` lookahead only: WebKit lacks lookbehind.
|
||||
const OPENER = /<#--|\[#--|<\/?[#@](?=[A-Za-z_])|\[\/?[#@](?=[A-Za-z_])|\$\{|\[=/g;
|
||||
const KEYWORDS = new Set(["as", "in", "using", "gt", "gte", "lt", "lte"]);
|
||||
|
||||
function nextOpener(line: string, from: number, square: boolean | null): RegExpExecArray | null {
|
||||
OPENER.lastIndex = from;
|
||||
for (let m = OPENER.exec(line); m; m = OPENER.exec(line)) {
|
||||
const text = m[0];
|
||||
if (text === "${") return m;
|
||||
if (text === "[=" ? square === true : square === null || square === (text[0] === "[")) return m;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function tokenComment<H>(stream: StringStream, state: State<H>): string {
|
||||
const end = stream.string.indexOf(state.close, stream.pos);
|
||||
stream.pos = end < 0 ? stream.string.length : end + state.close.length;
|
||||
if (end >= 0) state.mode = null;
|
||||
return "comment";
|
||||
}
|
||||
|
||||
function tokenExpression<H>(stream: StringStream, state: State<H>): string | null {
|
||||
if (stream.eatSpace()) return null;
|
||||
if (state.depth === 0 && stream.match(state.close)) {
|
||||
state.mode = null;
|
||||
return "ftlDelimiter";
|
||||
}
|
||||
if (state.depth === 0 && state.mode === "directive" && stream.match("/" + state.close)) {
|
||||
state.mode = null;
|
||||
return "ftlDelimiter";
|
||||
}
|
||||
if (stream.match(/^r?"(?:[^"\\]|\\.)*"?/) || stream.match(/^r?'(?:[^'\\]|\\.)*'?/)) return "string";
|
||||
if (stream.match(/^\d+(?:\.\d+)?/)) return "number";
|
||||
if (stream.match("??")) return "operator";
|
||||
if (stream.match(/^\?[A-Za-z_]\w*/)) return "ftlBuiltin";
|
||||
if (stream.match(/^\.[A-Za-z_]\w*/)) return "propertyName";
|
||||
if (stream.match(/^[A-Za-z_$][\w$]*/)) {
|
||||
const word = stream.current();
|
||||
if (word === "true" || word === "false") return "bool";
|
||||
return KEYWORDS.has(word) ? "keyword" : "variableName";
|
||||
}
|
||||
const ch = stream.next()!;
|
||||
if ("([{".includes(ch)) {
|
||||
state.depth++;
|
||||
return "bracket";
|
||||
}
|
||||
if (")]}".includes(ch)) {
|
||||
state.depth = Math.max(0, state.depth - 1);
|
||||
return "bracket";
|
||||
}
|
||||
if (ch === "." && stream.match(/^\.[<!*]?/)) return "operator";
|
||||
return "+-*/%!=<>&|:,;.".includes(ch) ? "operator" : null;
|
||||
}
|
||||
|
||||
function freemarkerParser<H>(html: StreamParser<H>): StreamParser<State<H>> {
|
||||
const copy = (state: H): H =>
|
||||
html.copyState
|
||||
? html.copyState(state)
|
||||
: (Object.fromEntries(
|
||||
Object.entries(state as object).map(([k, v]) => [k, Array.isArray(v) ? v.slice() : v]),
|
||||
) as H);
|
||||
|
||||
/** Runs the HTML mode on `stream` cut at `end`, then advances `stream` to where it stopped. */
|
||||
const tokenHtml = (stream: StringStream, end: number, state: H): string | null => {
|
||||
const sub = new StringStream(stream.string.slice(0, end), 4, stream.indentUnit);
|
||||
sub.pos = stream.pos;
|
||||
sub.start = stream.start;
|
||||
const style = html.token(sub, state);
|
||||
stream.pos = Math.max(sub.pos, stream.pos + (sub.pos === stream.pos ? 1 : 0));
|
||||
return style;
|
||||
};
|
||||
|
||||
return {
|
||||
name: "freemarker",
|
||||
languageData: { ...html.languageData, commentTokens: { block: { open: "<#--", close: "-->" } } },
|
||||
tokenTable: {
|
||||
...html.tokenTable,
|
||||
ftlDelimiter: tags.special(tags.brace),
|
||||
ftlBuiltin: tags.standard(tags.function(tags.variableName)),
|
||||
ftlMacro: tags.function(tags.variableName),
|
||||
},
|
||||
startState: (indentUnit) => ({
|
||||
html: html.startState!(indentUnit),
|
||||
mode: null,
|
||||
square: null,
|
||||
close: "",
|
||||
depth: 0,
|
||||
name: null,
|
||||
}),
|
||||
copyState: (s) => ({ ...s, html: copy(s.html) }),
|
||||
blankLine: (s, unit) => (s.mode ? undefined : html.blankLine?.(s.html, unit)),
|
||||
indent: (s, text, cx) => (s.mode ? null : (html.indent?.(s.html, text, cx) ?? null)),
|
||||
token(stream, state) {
|
||||
if (state.mode === "comment") return tokenComment(stream, state);
|
||||
if (state.name) {
|
||||
const sigil = state.name;
|
||||
state.name = null;
|
||||
if (stream.match(/^[A-Za-z_][\w.:-]*/)) return sigil === "#" ? "keyword" : "ftlMacro";
|
||||
}
|
||||
if (state.mode) return tokenExpression(stream, state);
|
||||
|
||||
const open = nextOpener(stream.string, stream.pos, state.square);
|
||||
if (open?.index !== stream.pos) {
|
||||
return tokenHtml(stream, open ? open.index : stream.string.length, state.html);
|
||||
}
|
||||
const text = open[0];
|
||||
stream.pos += text.length;
|
||||
const square = text[0] === "[";
|
||||
state.depth = 0;
|
||||
if (text.endsWith("--")) {
|
||||
state.mode = "comment";
|
||||
state.close = square ? "--]" : "-->";
|
||||
return tokenComment(stream, state);
|
||||
}
|
||||
if (text === "${" || text === "[=") {
|
||||
state.mode = "interpolation";
|
||||
state.close = text === "${" ? "}" : "]";
|
||||
return "ftlDelimiter";
|
||||
}
|
||||
state.square ??= square;
|
||||
state.mode = "directive";
|
||||
state.close = square ? "]" : ">";
|
||||
state.name = text.endsWith("@") ? "@" : "#";
|
||||
return "ftlDelimiter";
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function freemarker(): Promise<LanguageSupport> {
|
||||
const { html } = await import("@codemirror/legacy-modes/mode/xml");
|
||||
return new LanguageSupport(StreamLanguage.define(freemarkerParser(html)));
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// FreeMarker templates: the template layer. Directives (`<#if …>`), user-defined
|
||||
// directive calls (`<@badge …/>`), interpolations (`${…}`) and comments are parsed
|
||||
// here; the text between them is HTML, mounted by `./index.ts`. The first directive
|
||||
// fixes the tag syntax, angle (`<#if>`) or square (`[#if]`), as FreeMarker does.
|
||||
// Block directives nest (`<#if>…<#elseif>…<#else>…</#if>`); others stand alone.
|
||||
// Regenerate with `pnpm gen:freemarker-grammar`.
|
||||
|
||||
@context blocks from "./tokens"
|
||||
|
||||
@top Template { node* }
|
||||
|
||||
node {
|
||||
Text |
|
||||
Comment |
|
||||
Interpolation |
|
||||
Tag |
|
||||
Element |
|
||||
RawElement |
|
||||
StrayEndTag
|
||||
}
|
||||
|
||||
// A block directive or user-defined directive call, its middle tags
|
||||
// (`elseif`, `else`, `recover`, `case`…) and its end tag.
|
||||
Element { OpenTag node* (MidTag node*)* EndTag }
|
||||
|
||||
// `<#noparse>…</#noparse>`, `<#comment>…</#comment>`: the content is not parsed.
|
||||
RawElement { RawTag RawBody? EndTag }
|
||||
|
||||
@skip { space } {
|
||||
OpenTag { OpenTagStart tagName argument* TagEnd }
|
||||
RawTag { RawTagStart tagName argument* TagEnd }
|
||||
MidTag { MidTagStart tagName argument* (TagEnd | SelfCloseEnd) }
|
||||
EndTag { EndTagStart tagName? TagEnd }
|
||||
// An end tag without its start tag, or of a directive that may or may not be a block (`</#sep>`).
|
||||
StrayEndTag { StrayEndTagStart tagName? TagEnd }
|
||||
Tag { TagStart tagName argument* (TagEnd | SelfCloseEnd) }
|
||||
|
||||
Interpolation { InterpolationStart argument* InterpolationEnd }
|
||||
|
||||
argument {
|
||||
VariableName |
|
||||
Member { "." PropertyName } |
|
||||
BuiltIn { "?" BuiltInName } |
|
||||
String |
|
||||
Number |
|
||||
Operator |
|
||||
CompareOp |
|
||||
kw<"as"> | kw<"in"> | kw<"using"> |
|
||||
kw<"gt"> | kw<"gte"> | kw<"lt"> | kw<"lte"> |
|
||||
@specialize[@name=BooleanLiteral]<identifier, "true" | "false"> |
|
||||
ParenGroup { "(" argument* ")" } |
|
||||
BracketGroup { "[" argument* "]" } |
|
||||
HashGroup { "{" argument* "}" }
|
||||
}
|
||||
}
|
||||
|
||||
tagName { DirectiveName | MacroName }
|
||||
|
||||
VariableName { identifier }
|
||||
|
||||
PropertyName { identifier }
|
||||
|
||||
BuiltInName { identifier }
|
||||
|
||||
kw<term> { @specialize[@name={term}]<identifier, term> }
|
||||
|
||||
// Tried in this order, before the tokens below.
|
||||
@external tokens comment from "./tokens" { Comment }
|
||||
@external tokens rawBody from "./tokens" { RawBody }
|
||||
@external tokens text from "./tokens" { Text }
|
||||
@external tokens tagStart from "./tokens" {
|
||||
OpenTagStart, RawTagStart, MidTagStart, EndTagStart, StrayEndTagStart, TagStart, InterpolationStart
|
||||
}
|
||||
@external tokens tagName from "./tokens" { DirectiveName, MacroName }
|
||||
@external tokens tagEnd from "./tokens" { TagEnd, SelfCloseEnd, InterpolationEnd }
|
||||
|
||||
@tokens {
|
||||
space { $[ \t\n\r]+ }
|
||||
|
||||
identifier { $[a-zA-Z_$\u{a1}-\u{10ffff}] $[a-zA-Z0-9_$\u{a1}-\u{10ffff}]* }
|
||||
|
||||
Number { @digit+ ("." @digit+)? }
|
||||
|
||||
String {
|
||||
"r"? '"' (!["\\] | "\\" _)* '"'? |
|
||||
"r"? "'" (!['\\] | "\\" _)* "'"?
|
||||
}
|
||||
|
||||
Operator {
|
||||
"+" | "-" | "*" | "/" | "%" | "!" | "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "++" | "--" |
|
||||
"&&" | "||" | "&" | "|" | "??" | ".." | "..<" | "..!" | "..*" | "," | ":" | ";" | "->"
|
||||
}
|
||||
|
||||
CompareOp { "==" | "!=" | "<" | "<=" | ">=" | ">" }
|
||||
|
||||
@precedence { String, identifier }
|
||||
|
||||
"." "?" "(" ")" "[" "]" "{" "}"
|
||||
}
|
||||
|
||||
@detectDelim
|
||||
@@ -0,0 +1,202 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { CompletionContext, type CompletionResult, type CompletionSource } from "@codemirror/autocomplete";
|
||||
import { foldable, getIndentation, indentUnit, matchBrackets } from "@codemirror/language";
|
||||
import { buildParserFile } from "@lezer/generator";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
import { completedSyntaxState, completedSyntaxTree } from "@/test/syntax";
|
||||
import { commentBlock } from "../comments";
|
||||
import { freemarker, freemarkerLanguage } from "./index";
|
||||
|
||||
const highlighter = tagHighlighter([
|
||||
{ tag: t.special(t.brace), class: "delim" },
|
||||
{ tag: t.blockComment, class: "comment" },
|
||||
{ tag: t.keyword, class: "keyword" },
|
||||
{ tag: t.variableName, class: "var" },
|
||||
{ tag: t.propertyName, class: "prop" },
|
||||
{ tag: t.attributeName, class: "attr" },
|
||||
{ tag: t.string, class: "str" },
|
||||
{ tag: t.tagName, class: "tag" },
|
||||
]);
|
||||
|
||||
function state(doc: string, selection?: number): EditorState {
|
||||
return completedSyntaxState(
|
||||
EditorState.create({
|
||||
doc,
|
||||
selection: selection == undefined ? undefined : EditorSelection.cursor(selection),
|
||||
extensions: [freemarker(), indentUnit.of(" ")],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** `text:class` of the styled tokens of `doc`, HTML and embedded languages included. */
|
||||
function tokens(doc: string): string[] {
|
||||
const out: string[] = [];
|
||||
highlightTree(completedSyntaxTree(state(doc)), highlighter, (from, to, cls) =>
|
||||
out.push(`${doc.slice(from, to)}:${cls}`),
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The error nodes of `doc`'s template layer, with the text they start. */
|
||||
function errors(doc: string): string[] {
|
||||
const out: string[] = [];
|
||||
freemarkerLanguage.parser.parse(doc).iterate({
|
||||
enter: (node) => void (node.type.isError && out.push(doc.slice(node.from, node.from + 12))),
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
const outline = (doc: string) => freemarkerLanguage.parser.parse(doc).toString();
|
||||
|
||||
/** A view on `doc` with `|` marking the caret. */
|
||||
function view(marked: string): EditorView {
|
||||
const at = marked.indexOf("|");
|
||||
return new EditorView({ state: state(marked.slice(0, at) + marked.slice(at + 1), at) });
|
||||
}
|
||||
|
||||
/** Types `text` at the caret through the input handlers, like a keystroke. */
|
||||
function type(v: EditorView, text: string): string {
|
||||
const { from, to } = v.state.selection.main;
|
||||
const handled = v.state.facet(EditorView.inputHandler).some((h) => h(v, from, to, text, () => v.state.update({})));
|
||||
if (!handled)
|
||||
v.dispatch({ changes: { from, to, insert: text }, selection: EditorSelection.cursor(from + text.length) });
|
||||
const head = v.state.selection.main.head;
|
||||
return v.state.sliceDoc(0, head) + "|" + v.state.sliceDoc(head);
|
||||
}
|
||||
|
||||
/** The labels completion offers at the end of `doc`. */
|
||||
function complete(doc: string): string[] | undefined {
|
||||
const s = state(doc);
|
||||
const sources = s.languageDataAt<CompletionSource>("autocomplete", doc.length);
|
||||
const result = sources.map((src) => src(new CompletionContext(s, doc.length, true))).find(Boolean) as
|
||||
| CompletionResult
|
||||
| undefined;
|
||||
return result?.options.map((o) => o.label);
|
||||
}
|
||||
|
||||
describe("FreeMarker template layer", () => {
|
||||
it("nests block directives with their middle tags and leaves other directives alone", () => {
|
||||
expect(outline("<#if a>x<#elseif b>y<#else>z</#if><#assign n = 1>")).toBe(
|
||||
"Template(Element(OpenTag(OpenTagStart,DirectiveName,VariableName,TagEnd),Text," +
|
||||
"MidTag(MidTagStart,DirectiveName,VariableName,TagEnd),Text,MidTag(MidTagStart,DirectiveName,TagEnd),Text," +
|
||||
"EndTag(EndTagStart,DirectiveName,TagEnd)),Tag(TagStart,DirectiveName,VariableName,Operator,Number,TagEnd))",
|
||||
);
|
||||
// `assign` without `=` captures its content; a call with content is a block, one without isn't.
|
||||
expect(outline("<#assign x>v</#assign><@m/><@m>c</@m>")).toMatch(
|
||||
/^Template\(Element\(.*\),Tag\(.*SelfCloseEnd\),Element\(.*\)\)$/,
|
||||
);
|
||||
});
|
||||
|
||||
it("doesn't parse the content of noparse and comment", () => {
|
||||
expect(outline("<#noparse><#if>${x}</#noparse>")).toBe(
|
||||
"Template(RawElement(RawTag(RawTagStart,DirectiveName,TagEnd),RawBody,EndTag(EndTagStart,DirectiveName,TagEnd)))",
|
||||
);
|
||||
});
|
||||
|
||||
it("parses common templates without errors", () => {
|
||||
const doc = [
|
||||
'<#ftl output_format="HTML">',
|
||||
'<#import "/lib/ui.ftl" as ui>',
|
||||
"<#macro row item><tr><td>${item.name}</td></tr></#macro>",
|
||||
"<#function total xs><#local s = 0><#list xs as x><#local s += x.price></#list><#return s></#function>",
|
||||
"<#list orders?filter(o -> o.paid) as order><@row item=order/><#sep>, </#sep><#else>none</#list>",
|
||||
'<#switch kind><#case "a">A<#break><#default>B</#switch>',
|
||||
"<#attempt>${risky}<#recover>failed</#attempt>",
|
||||
"<#if (a > 1) && b?? && c?has_content>${a..<5}</#if>",
|
||||
'<@ui.card title="x" items=[1, 2] opts={"k": true}>c</@ui.card>',
|
||||
"<#list map as k, v>${k}=${v}</#list>",
|
||||
].join("\n");
|
||||
expect(errors(doc)).toEqual([]);
|
||||
});
|
||||
|
||||
it("highlights script and style content as JavaScript and CSS", () => {
|
||||
const out = tokens('<script>let a = "${x}";</script><style>p { color: red }</style>');
|
||||
expect(out).toContain("let:keyword");
|
||||
expect(out).toContain("x:var");
|
||||
expect(out).toContain("color:prop");
|
||||
});
|
||||
|
||||
it("nests markup across directives", () => {
|
||||
const out = tokens('<#if a><div class="x"></#if><#if a></div></#if>');
|
||||
expect(out.filter((t) => t == "div:tag")).toHaveLength(2);
|
||||
expect(out).toContain("class:attr");
|
||||
});
|
||||
|
||||
it("is generated from freemarker.grammar", () => {
|
||||
const dir = import.meta.dirname;
|
||||
const { parser, terms } = buildParserFile(readFileSync(resolve(dir, "freemarker.grammar"), "utf8"), {
|
||||
fileName: "src/editor/core/cm/freemarker/freemarker.grammar",
|
||||
moduleStyle: "es",
|
||||
typeScript: true,
|
||||
});
|
||||
const lf = (s: string) => s.replace(/\r\n/g, "\n");
|
||||
expect(lf(parser)).toBe(lf(readFileSync(resolve(dir, "parser.ts"), "utf8")));
|
||||
expect(lf(terms)).toBe(lf(readFileSync(resolve(dir, "parser.terms.ts"), "utf8")));
|
||||
});
|
||||
});
|
||||
|
||||
describe("FreeMarker template editing", () => {
|
||||
it("folds blocks", () => {
|
||||
const doc = "<#list xs as x>\n <p>${x}</p>\n</#list>\n";
|
||||
expect(foldable(state(doc), 0, doc.indexOf("\n"))).toEqual({ from: doc.indexOf(">") + 1, to: doc.indexOf("</#") });
|
||||
});
|
||||
|
||||
it("indents a block's content and puts its middle and end tags back", () => {
|
||||
const s = state("<#if a>\nx\n<#else>\ny\n</#if>");
|
||||
const lineStart = (n: number) => s.doc.line(n).from;
|
||||
expect(getIndentation(s, lineStart(2))).toBe(2);
|
||||
expect(getIndentation(s, lineStart(3))).toBe(0);
|
||||
expect(getIndentation(s, lineStart(4))).toBe(2);
|
||||
expect(getIndentation(s, lineStart(5))).toBe(0);
|
||||
});
|
||||
|
||||
it("matches a block directive with its end tag", () => {
|
||||
const doc = "<#list xs as x>${x}</#list>";
|
||||
const match = matchBrackets(state(doc), 3, 1);
|
||||
expect(match?.matched).toBe(true);
|
||||
expect(doc.slice(match!.end!.from, match!.end!.to)).toBe("list");
|
||||
});
|
||||
|
||||
it("adds the end tag of a block directive when its > is typed", () => {
|
||||
expect(type(view("<#if a|"), ">")).toBe("<#if a>|</#if>");
|
||||
expect(type(view("<@card title=t|"), ">")).toBe("<@card title=t>|</@card>");
|
||||
expect(type(view("[#ftl][#list xs as x|"), "]")).toBe("[#ftl][#list xs as x]|[/#list]");
|
||||
// It has one already.
|
||||
expect(type(view("<#if a|\n</#if>"), ">")).toBe("<#if a>|\n</#if>");
|
||||
// Not a block, or closed by `/>`.
|
||||
expect(type(view("<#include 'a.ftl'|"), ">")).toBe("<#include 'a.ftl'>|");
|
||||
expect(type(view("<@card /|"), ">")).toBe("<@card />|");
|
||||
// A capturing assign only without `=`.
|
||||
expect(type(view("<#assign x|"), ">")).toBe("<#assign x>|</#assign>");
|
||||
// Not in a script.
|
||||
expect(type(view("<script>if (a <#b|</script>"), ">")).toBe("<script>if (a <#b>|</script>");
|
||||
});
|
||||
|
||||
it("completes directives, the open blocks' end tags and built-ins", () => {
|
||||
expect(complete("<p><#")).toContain("list");
|
||||
expect(complete("<#list xs as x><@card><#if a></")).toEqual(["#if", "@card", "#list"]);
|
||||
expect(complete("<#list xs as x><@card><#if a></#")).toEqual(["#if", "@card", "#list"]);
|
||||
expect(complete("${name?")).toContain("upper_case");
|
||||
expect(complete("<p>Why?")).not.toContain("upper_case");
|
||||
});
|
||||
|
||||
it("comments with <#-- -->", () => {
|
||||
const v = view("|<p>a</p>");
|
||||
v.dispatch({ selection: EditorSelection.range(0, v.state.doc.length) });
|
||||
commentBlock(v);
|
||||
expect(v.state.doc.toString()).toBe("<#-- <p>a</p> -->");
|
||||
const square = view("[#ftl]\n|<p>a</p>");
|
||||
square.dispatch({ selection: EditorSelection.range(7, square.state.doc.length) });
|
||||
commentBlock(square);
|
||||
expect(square.state.doc.toString()).toBe("[#ftl]\n[#-- <p>a</p> --]");
|
||||
// JavaScript keeps its own.
|
||||
const script = view("<script>|a()</script>");
|
||||
script.dispatch({ selection: EditorSelection.range(8, 11) });
|
||||
commentBlock(script);
|
||||
expect(script.state.doc.toString()).toBe("<script>/* a() */</script>");
|
||||
});
|
||||
});
|
||||
+14
-4
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { completedSyntaxTree } from "@/test/syntax";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
import { findLanguageDescription, loadSupport } from "./languages";
|
||||
import { findLanguageDescription, loadSupport } from "../languages";
|
||||
|
||||
const highlighter = tagHighlighter([
|
||||
{ tag: t.keyword, class: "keyword" },
|
||||
@@ -25,9 +25,19 @@ async function tokens(source: string) {
|
||||
const support = await loadSupport(desc);
|
||||
const state = EditorState.create({ doc: source, extensions: [support!] });
|
||||
const result: { text: string; style: string }[] = [];
|
||||
highlightTree(completedSyntaxTree(state), highlighter, (from, to, style) =>
|
||||
result.push({ text: source.slice(from, to), style }),
|
||||
);
|
||||
let last = { to: -1, style: "" };
|
||||
// One span per run of a style on a line, as the editor draws it.
|
||||
highlightTree(completedSyntaxTree(state), highlighter, (from, to, style) => {
|
||||
source
|
||||
.slice(from, to)
|
||||
.split("\n")
|
||||
.forEach((text, i) => {
|
||||
const prev = result.at(-1);
|
||||
if (i == 0 && prev && last.to == from && last.style == style) prev.text += text;
|
||||
else result.push({ text, style });
|
||||
});
|
||||
last = { to, style };
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
/**
|
||||
* FreeMarker templates: `freemarker.grammar` parses the template layer (directives,
|
||||
* user-defined directive calls, interpolations, comments), and the text between its
|
||||
* elements is one HTML document, an overlay as in Django and JSP templates, so markup
|
||||
* split by a directive still nests, `href="${url}"` is an attribute with a hole, and
|
||||
* `<script>` / `<style>` get JavaScript and CSS. Block directives fold, indent their
|
||||
* content and match their end tags; finishing a block directive adds its end tag.
|
||||
* Completion offers directives after `<#`, the open blocks' end tags after `</` and
|
||||
* built-ins after `?`.
|
||||
*/
|
||||
import {
|
||||
LRLanguage,
|
||||
LanguageSupport,
|
||||
bracketMatchingHandle,
|
||||
foldNodeProp,
|
||||
indentNodeProp,
|
||||
syntaxTree,
|
||||
type TreeIndentContext,
|
||||
} from "@codemirror/language";
|
||||
import { html } from "@codemirror/lang-html";
|
||||
import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";
|
||||
import { EditorSelection, EditorState, Prec, type Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { styleTags, tags as t } from "@lezer/highlight";
|
||||
import { NodeProp, parseMixed, type SyntaxNode, type SyntaxNodeRef } from "@lezer/common";
|
||||
import { VERSIONED_SCRIPT_TYPES } from "../htmlScripts";
|
||||
import { parser } from "./parser";
|
||||
import { BLOCK_DIRECTIVES, CAPTURING, DIRECTIVES, RAW_DIRECTIVES } from "./tokens";
|
||||
|
||||
const baseHTML = html({ selfClosingTags: true, nestedLanguages: VERSIONED_SCRIPT_TYPES });
|
||||
|
||||
const FTL_COMMENT = { block: { open: "<#--", close: "-->" } };
|
||||
const SQUARE_COMMENT = { block: { open: "[#--", close: "--]" } };
|
||||
|
||||
const OPENERS = ["OpenTag", "RawTag"];
|
||||
|
||||
const startTagOf = (element: SyntaxNode) => element.firstChild;
|
||||
const endTagOf = (element: SyntaxNode) => (element.lastChild?.name == "EndTag" ? element.lastChild : null);
|
||||
const tagNameOf = (node: SyntaxNode) => node.getChild("DirectiveName") ?? node.getChild("MacroName");
|
||||
|
||||
/** The content of a block: from the end of its start tag to its end tag (or the end of the block). */
|
||||
function foldBlock(element: SyntaxNode, state: EditorState) {
|
||||
const start = startTagOf(element);
|
||||
const end = endTagOf(element);
|
||||
if (!start) return null;
|
||||
// An end tag the parser inserted to recover is empty.
|
||||
const to = end && end.to > end.from ? end.from : element.to;
|
||||
return start.to < to && state.doc.lineAt(start.to).number < state.doc.lineAt(to).number
|
||||
? { from: start.to, to }
|
||||
: null;
|
||||
}
|
||||
|
||||
const MIDDLE = new Set([...BLOCK_DIRECTIVES.values()].flat());
|
||||
const CLOSING_LINE = /^\s*(?:<|\[)(?:\/[#@]|#([A-Za-z]+))/;
|
||||
|
||||
/** A block's content one unit in from its start tag's line; its middle and end tags at that line's indent. */
|
||||
function indentBlock(cx: TreeIndentContext) {
|
||||
const start = startTagOf(cx.node);
|
||||
if (!start) return null;
|
||||
const base = cx.lineIndent(start.from);
|
||||
const m = CLOSING_LINE.exec(cx.textAfter);
|
||||
return m && (!m[1] || MIDDLE.has(m[1])) ? base : base + cx.unit;
|
||||
}
|
||||
|
||||
const templateParser = parser.configure({
|
||||
props: [
|
||||
styleTags({
|
||||
"TagStart OpenTagStart RawTagStart MidTagStart EndTagStart StrayEndTagStart TagEnd SelfCloseEnd InterpolationStart InterpolationEnd":
|
||||
t.special(t.brace),
|
||||
DirectiveName: t.keyword,
|
||||
MacroName: t.function(t.variableName),
|
||||
"Comment RawBody": t.blockComment,
|
||||
VariableName: t.variableName,
|
||||
"PropertyName Member/.": t.propertyName,
|
||||
"BuiltInName BuiltIn/?": t.standard(t.function(t.variableName)),
|
||||
String: t.string,
|
||||
Number: t.number,
|
||||
BooleanLiteral: t.bool,
|
||||
"Operator CompareOp": t.operator,
|
||||
"as in using gt gte lt lte": t.keyword,
|
||||
"( ) [ ] { }": t.bracket,
|
||||
}),
|
||||
foldNodeProp.add({ "Element RawElement": foldBlock }),
|
||||
indentNodeProp.add({
|
||||
Element: indentBlock,
|
||||
// The raw content keeps its own indentation.
|
||||
RawElement: () => null,
|
||||
}),
|
||||
NodeProp.closedBy.add({ "OpenTag RawTag": ["EndTag"] }),
|
||||
NodeProp.openedBy.add({ EndTag: OPENERS }),
|
||||
bracketMatchingHandle.add({ "OpenTag RawTag EndTag": tagNameOf }),
|
||||
],
|
||||
});
|
||||
|
||||
// HTML's document gives no indentation past its last text; there the block around it does.
|
||||
const htmlBase = (baseHTML.language as LRLanguage).parser;
|
||||
const htmlDocumentIndent = htmlBase.nodeSet.types.find((type) => type.name == "Document")?.prop(indentNodeProp);
|
||||
const htmlParser = htmlBase.configure({
|
||||
props: [indentNodeProp.add({ Document: (cx) => htmlDocumentIndent?.(cx) ?? cx.continue() })],
|
||||
});
|
||||
|
||||
// The template text is one HTML document.
|
||||
const htmlMixed = { parser: htmlParser, overlay: (node: SyntaxNodeRef) => node.name == "Text" };
|
||||
|
||||
export const freemarkerLanguage = LRLanguage.define({
|
||||
name: "freemarker",
|
||||
parser: templateParser.configure({ wrap: parseMixed((node) => (node.type.isTop ? htmlMixed : null)) }),
|
||||
});
|
||||
|
||||
/** Where the template layer reaches: FreeMarker's own nodes, or the HTML outside `<script>` and `<style>`. */
|
||||
function inTemplate(state: EditorState, pos: number): boolean {
|
||||
return freemarkerLanguage.isActiveAt(state, pos, -1) || baseHTML.language.isActiveAt(state, pos, -1);
|
||||
}
|
||||
|
||||
const squareSyntaxOf = new WeakMap<Text, boolean>();
|
||||
|
||||
/** The square tag syntax, when the template's first directive uses it. */
|
||||
function squareSyntax(state: EditorState): boolean {
|
||||
let square = squareSyntaxOf.get(state.doc);
|
||||
if (square == undefined) {
|
||||
const head = state.sliceDoc(0, Math.min(state.doc.length, 20_000));
|
||||
square = /<\/?[#@][A-Za-z]|\[\/?[#@][A-Za-z]/.exec(head)?.[0][0] == "[";
|
||||
squareSyntaxOf.set(state.doc, square);
|
||||
}
|
||||
return square;
|
||||
}
|
||||
|
||||
/** The blocks open at `pos`, innermost first, as `#if` / `@badge`. */
|
||||
function openBlocks(state: EditorState, pos: number): string[] {
|
||||
const names: string[] = [];
|
||||
for (let node: SyntaxNode | null = syntaxTree(state).resolve(pos, -1); node; node = node.parent) {
|
||||
if (node.name != "Element" && node.name != "RawElement") continue;
|
||||
const start = startTagOf(node);
|
||||
const name = start && tagNameOf(start);
|
||||
if (start && name && start.to <= pos) {
|
||||
names.push(state.sliceDoc(start.from, name.from).replace(/^[<[]/, "") + state.sliceDoc(name.from, name.to));
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/** Whether the block `name` opened before `pos` has no end tag after it, nested blocks counted. */
|
||||
function unclosed(state: EditorState, sigil: string, name: string, pos: number): boolean {
|
||||
const rest = state.sliceDoc(pos);
|
||||
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const re = new RegExp(`[<\\[](/)?${sigil}${escaped}(?![\\w.:-])`, "g");
|
||||
let depth = 0;
|
||||
for (let m; (m = re.exec(rest));) {
|
||||
if (!m[1]) depth++;
|
||||
else if (depth-- == 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const TAG_BEFORE = /[<[]([#@])([A-Za-z_][\w.:-]*)(?:\s[^<>[\]]*)?$/;
|
||||
|
||||
/** Typing the `>` (`]`) of a block directive or a call with content adds its end tag after the caret. */
|
||||
const closeBlock = EditorView.inputHandler.of((view, from, to, text) => {
|
||||
const { state } = view;
|
||||
if ((text != ">" && text != "]") || from != to || state.selection.ranges.length > 1 || state.readOnly) return false;
|
||||
const square = squareSyntax(state);
|
||||
if ((text == "]") != square) return false;
|
||||
const line = state.doc.lineAt(from);
|
||||
const before = state.sliceDoc(line.from, from);
|
||||
const m = TAG_BEFORE.exec(before);
|
||||
if (!m || before.endsWith("/") || (m[0][0] == "[") != square) return false;
|
||||
const [, sigil, name] = m;
|
||||
// `<#assign x>…</#assign>` captures its content; `<#assign x = 1>` doesn't.
|
||||
const assigns = /(?:^|[^=!<>])=(?!=)/.test(before.slice(before.length - m[0].length + 2 + name!.length));
|
||||
const block = BLOCK_DIRECTIVES.has(name!) || RAW_DIRECTIVES.has(name!) || (CAPTURING.has(name!) && !assigns);
|
||||
if (sigil == "#" && !block) return false;
|
||||
if (!inTemplate(state, from - m[0].length)) return false;
|
||||
if (!unclosed(state, sigil!, name!, from)) return false;
|
||||
const close = square ? `[/${sigil}${name}]` : `</${sigil}${name}>`;
|
||||
view.dispatch({
|
||||
changes: { from, insert: text + close },
|
||||
selection: EditorSelection.cursor(from + 1),
|
||||
userEvent: "input.type",
|
||||
});
|
||||
return true;
|
||||
});
|
||||
|
||||
const DIRECTIVE_OPTIONS: Completion[] = DIRECTIVES.map((label) => ({ label, type: "keyword" }));
|
||||
|
||||
/** Built-ins most templates use, for completion after `?`. */
|
||||
const BUILT_INS = [
|
||||
"api",
|
||||
"boolean",
|
||||
"c",
|
||||
"c_lower_case",
|
||||
"cap_first",
|
||||
"capitalize",
|
||||
"chop_linebreaks",
|
||||
"chunk",
|
||||
"contains",
|
||||
"counter",
|
||||
"date",
|
||||
"datetime",
|
||||
"default",
|
||||
"drop_while",
|
||||
"ends_with",
|
||||
"ensure_ends_with",
|
||||
"ensure_starts_with",
|
||||
"eval",
|
||||
"eval_json",
|
||||
"filter",
|
||||
"first",
|
||||
"groups",
|
||||
"has_content",
|
||||
"has_next",
|
||||
"html",
|
||||
"if_exists",
|
||||
"index",
|
||||
"index_of",
|
||||
"interpret",
|
||||
"is_boolean",
|
||||
"is_date",
|
||||
"is_even_item",
|
||||
"is_first",
|
||||
"is_hash",
|
||||
"is_last",
|
||||
"is_number",
|
||||
"is_odd_item",
|
||||
"is_sequence",
|
||||
"is_string",
|
||||
"item_cycle",
|
||||
"item_parity",
|
||||
"j_string",
|
||||
"join",
|
||||
"js_string",
|
||||
"json_string",
|
||||
"keep_after",
|
||||
"keep_after_last",
|
||||
"keep_before",
|
||||
"keep_before_last",
|
||||
"keys",
|
||||
"last",
|
||||
"last_index_of",
|
||||
"left_pad",
|
||||
"length",
|
||||
"lower_case",
|
||||
"map",
|
||||
"matches",
|
||||
"max",
|
||||
"min",
|
||||
"no_esc",
|
||||
"number",
|
||||
"number_to_date",
|
||||
"number_to_datetime",
|
||||
"remove_beginning",
|
||||
"remove_ending",
|
||||
"replace",
|
||||
"reverse",
|
||||
"right_pad",
|
||||
"round",
|
||||
"seq_contains",
|
||||
"seq_index_of",
|
||||
"size",
|
||||
"sort",
|
||||
"sort_by",
|
||||
"split",
|
||||
"starts_with",
|
||||
"string",
|
||||
"substring",
|
||||
"switch",
|
||||
"take_while",
|
||||
"then",
|
||||
"time",
|
||||
"trim",
|
||||
"truncate",
|
||||
"uncap_first",
|
||||
"upper_case",
|
||||
"url",
|
||||
"values",
|
||||
"word_list",
|
||||
"xhtml",
|
||||
"xml",
|
||||
].map((label): Completion => ({ label, type: "function" }));
|
||||
|
||||
/** `<#…`, `</#…` and `?…` inside the template layer. */
|
||||
function templateCompletion(context: CompletionContext): CompletionResult | null {
|
||||
const { state } = context;
|
||||
const end = context.matchBefore(/[<[]\/(?:[#@][\w.:-]*)?$/);
|
||||
if (end) {
|
||||
const from = end.from + 2;
|
||||
const options = openBlocks(state, from).map((block, i) => ({ label: block, type: "keyword", boost: 99 - i }));
|
||||
return options.length ? { from, options, validFor: /^(?:[#@][\w.:-]*)?$/ } : null;
|
||||
}
|
||||
const directive = context.matchBefore(/[<[]#\w*$/);
|
||||
if (directive) {
|
||||
if ((directive.text[0] == "[") != squareSyntax(state)) return null;
|
||||
const name = /\w*$/.exec(directive.text)![0];
|
||||
return { from: directive.to - name.length, options: DIRECTIVE_OPTIONS, validFor: /^\w*$/ };
|
||||
}
|
||||
const builtIn = context.matchBefore(/\?\w*$/);
|
||||
// The `?` is a built-in's, not text or a string's.
|
||||
const mark = builtIn && syntaxTree(state).resolveInner(builtIn.from + 1, -1);
|
||||
if (builtIn && mark && (mark.name == "BuiltIn" || mark.parent?.name == "BuiltIn")) {
|
||||
return { from: builtIn.from + 1, options: BUILT_INS, validFor: /^\w*$/ };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function freemarker(): LanguageSupport {
|
||||
return new LanguageSupport(freemarkerLanguage, [
|
||||
// Before HTML's, so the template's completions come first.
|
||||
baseHTML.language.data.of({ autocomplete: templateCompletion }),
|
||||
baseHTML.support,
|
||||
// Markup is commented out with a template comment, which FreeMarker drops from the page.
|
||||
baseHTML.language.data.of({ commentTokens: FTL_COMMENT }),
|
||||
freemarkerLanguage.data.of({ autocomplete: templateCompletion, commentTokens: FTL_COMMENT }),
|
||||
// In the square syntax, `[#-- --]`.
|
||||
Prec.highest(
|
||||
EditorState.languageData.of((state, pos) =>
|
||||
squareSyntax(state) && inTemplate(state, pos) ? [{ commentTokens: SQUARE_COMMENT }] : [],
|
||||
),
|
||||
),
|
||||
Prec.high(closeBlock),
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// This file was generated by lezer-generator. You probably shouldn't edit it.
|
||||
export const
|
||||
Comment = 1,
|
||||
RawBody = 2,
|
||||
Text = 3,
|
||||
OpenTagStart = 4,
|
||||
RawTagStart = 5,
|
||||
MidTagStart = 6,
|
||||
EndTagStart = 7,
|
||||
StrayEndTagStart = 8,
|
||||
TagStart = 9,
|
||||
InterpolationStart = 10,
|
||||
DirectiveName = 11,
|
||||
MacroName = 12,
|
||||
TagEnd = 13,
|
||||
SelfCloseEnd = 14,
|
||||
InterpolationEnd = 15,
|
||||
Template = 16,
|
||||
Interpolation = 17,
|
||||
VariableName = 18,
|
||||
PropertyName = 21,
|
||||
BuiltInName = 24,
|
||||
String = 25,
|
||||
Number = 26,
|
||||
Operator = 27,
|
||||
CompareOp = 28,
|
||||
as = 29,
|
||||
_in = 30,
|
||||
using = 31,
|
||||
gt = 32,
|
||||
gte = 33,
|
||||
lt = 34,
|
||||
lte = 35,
|
||||
BooleanLiteral = 36,
|
||||
Tag = 46,
|
||||
Element = 47,
|
||||
OpenTag = 48,
|
||||
MidTag = 49,
|
||||
EndTag = 50,
|
||||
RawElement = 51,
|
||||
RawTag = 52,
|
||||
StrayEndTag = 53
|
||||
@@ -0,0 +1,24 @@
|
||||
// This file was generated by lezer-generator. You probably shouldn't edit it.
|
||||
import {LRParser} from "@lezer/lr"
|
||||
import {comment, rawBody, text, tagStart, tagName, tagEnd, blocks} from "./tokens"
|
||||
const spec_identifier = {__proto__:null,as:58, in:60, using:62, gt:64, gte:66, lt:68, lte:70, true:72, false:72}
|
||||
export const parser = LRParser.deserialize({
|
||||
version: 14,
|
||||
states: "*nQVO]OOO!xQ#SO'#CmO#PQ!rO'#D[O#PQ!rO'#D^O#XO]O'#D]O#PQ!rO'#DbO#cOYO'#DaO#kQ#dO'#DcOOO]'#Dj'#DjOOO]'#Dd'#DdQVO]OOOOQp'#Cn'#CnO#vQ!bO'#CoO#{Q!bO'#CrO$QQ!bO'#DTO$XQ!bO'#DWO$`Q!bO'#DZOOQp'#Dk'#DkOOQp'#De'#DeO$gQ#SO,59XOOO],59X,59XOOQp'#Dm'#DmO$nQ#SO,59vO$xQ#SO,59xO#PQ!rO'#D_O%PO]O'#DfO%ZOWO,59wO%cQ#dO'#D`OOO],59w,59wO#XO]O,59wO%nQ#SO,59|OOO],59{,59{O#fOWO,59{OOO],59},59}O%uQ#SO,59}OOO]-E7b-E7bOOQp'#Cq'#CqOOQp,59Z,59ZOOQp'#Ct'#CtOOQp,59^,59^OOQp,59o,59oO%zQ!bO,59oOOQp,59r,59rO&RQ!bO,59rOOQp,59u,59uO&YQ!bO,59uOOQp-E7c-E7cOOO]1G.s1G.sO&aQ#SO1G/bOOO]1G/b1G/bO&kQ#SO1G/dOOO]1G/d1G/dO&rQ#SO,59yO&|O]O,5:QOOOW-E7d-E7dOOO]1G/c1G/cOOO],59z,59zO'WQ#SO,59zO%ZOWO1G/cO']Q#SO1G/hOOOY1G/h1G/hOOO]1G/g1G/gOOO]1G/i1G/iOOQp1G/Z1G/ZOOQp1G/^1G/^OOQp1G/a1G/aOOO]7+$|7+$|OOO]7+%O7+%OO'dQ#SO1G/eOOO]1G/e1G/eOOO]1G/f1G/fOOO]7+$}7+$}OOOY7+%S7+%SOOO]7+%P7+%P",
|
||||
stateData: "'q~O!]OS~OPWORWOSROTTOWVOXQOYPO~Od[Og]OiaOjaOkaOlaOmaOnaOoaOpaOqaOraOsaOtaOv^Oy_O|`O!`ZO~O_dO~PnOZeO[eO~OUhOVkO~PVOQpOVkO~OZeO[eO]qO~O!`tO~O!`vO~OuxO~PnOxzO~PnO{|O~PnO_!PO~PnO]!RO^!RO~PnO]!TO~PnOU!YXV!YX~PVOUhOVkO~OZeO[eO]!YO~O]!^O~PnO]!`O~Ou!aO~PnOx!bO~PnO{!cO~PnO]!dO^!dO~PnO]!eO~PnO]!gO^!gO~PnOU!YaV!Ya~PVO]!hO~O]!jO~PnO]!kO^!kO~PnOi!`~",
|
||||
goto: "&V!bPPPPPPPPPPPPPPPPP!c!k!kP!}!kP#QPPPPPPPPPPPPPP!kPP!kPP!k!c!c#T#]#c!c#s!c#{$Z$}PPP%X%aP%s]WOSYim!VqaP^_`cfgny{}!Q!S!U!]!fRu[Rw]]SOSYim!VXiSjm![QlSQoUS!XjmQ!_pR!i![]UOSYim!VQYOQmSUsYm!VR!ViQcPQy^Q{_Q}``!Ocy{}!Q!S!]!fQ!QfQ!SgQ!]nR!f!UQjSS!Wj![R![m]XOSYim!VqbP^_`cfgny{}!Q!S!U!]!fQfQQgRQnTQrVQ!UhR!Zk",
|
||||
nodeNames: "⚠ Comment RawBody Text OpenTagStart RawTagStart MidTagStart EndTagStart StrayEndTagStart TagStart InterpolationStart DirectiveName MacroName TagEnd SelfCloseEnd InterpolationEnd Template Interpolation VariableName Member . PropertyName BuiltIn ? BuiltInName String Number Operator CompareOp as in using gt gte lt lte BooleanLiteral ) ( ParenGroup ] [ BracketGroup } { HashGroup Tag Element OpenTag MidTag EndTag RawElement RawTag StrayEndTag",
|
||||
maxTerm: 63,
|
||||
context: blocks,
|
||||
nodeProps: [
|
||||
["openedBy", 37,"(",40,"[",43,"{"],
|
||||
["closedBy", 38,")",41,"]",44,"}"]
|
||||
],
|
||||
skippedNodes: [0],
|
||||
repeatNodeCount: 3,
|
||||
tokenData: ",X~RvXY#iYZ#i]^#ipq#iqr#zrs$Xtu%yuv&nvw&{wx'Txy(pyz(uz{&n{|(z|}&v}!O)V!O!P)e!P!Q&n!Q![){![!]&v!]!^&v!^!_*f!_!`#z!`!a*f!a!b*n!c!}%y!}#O*v#P#Q*{#R#S%y#T#f%y#f#g+Q#g#o%y#o#p+u#p#q+z#q#r,S$g;'S%y;'S;=`&h<%lO%y~#nS!]~XY#iYZ#i]^#ipq#i~$PPk~!_!`$S~$XOl~~$^Vi~Or$Xrs$ss#O$X#O#P$x#P;'S$X;'S;=`%s<%lO$X~$xOi~~${RO;'S$X;'S;=`%U;=`O$X~%ZWi~Or$Xrs$ss#O$X#O#P$x#P;'S$X;'S;=`%s;=`<%l$X<%lO$X~%vP;=`<%l$X~&OW!`~tu%y!Q![%y!c!}%y#R#S%y#T#o%y$g;'S%y;'S;=`&h<%lO%y~&kP;=`<%l%y~&sPk~!_!`&v~&{Ok~~'QPk~vw&v~'YVi~Ow'Twx$sx#O'T#O#P'o#P;'S'T;'S;=`(j<%lO'T~'rRO;'S'T;'S;=`'{;=`O'T~(QWi~Ow'Twx$sx#O'T#O#P'o#P;'S'T;'S;=`(j;=`<%l'T<%lO'T~(mP;=`<%l'T~(uOv~~(zOu~~)PQk~{|&v!_!`&v~)[Rk~}!O&v!_!`&v!`!a&v~)jPd~!O!P)m~)rRk~qr&vz{&v!^!_&v~*QQj~!O!P*W!Q![){~*ZP!Q![*^~*cPj~!Q![*^~*kPl~!_!`$S~*sPg~!a!b&v~*{Oy~~+QOx~~+VY!`~rs$Xtu%ywx'T!Q![%y!c!}%y#R#S%y#T#o%y$g;'S%y;'S;=`&h<%lO%y~+zO|~~,PPk~#p#q&v~,XO{~",
|
||||
tokenizers: [comment, rawBody, text, tagStart, tagName, tagEnd, 0],
|
||||
topRules: {"Template":[0,16]},
|
||||
specialized: [{term: 62, get: (value: keyof typeof spec_identifier) => spec_identifier[value] || -1}],
|
||||
tokenPrec: 306
|
||||
})
|
||||
@@ -0,0 +1,350 @@
|
||||
/**
|
||||
* External tokens of `freemarker.grammar`: the text between template elements, the
|
||||
* comments, the raw content of `noparse`, the start of each tag, classified by its name
|
||||
* against the blocks open around it, the tag's name and the delimiters that end tags
|
||||
* and interpolations, which depend on the tag syntax.
|
||||
*/
|
||||
import { ContextTracker, ExternalTokenizer, type InputStream, type Stack } from "@lezer/lr";
|
||||
import {
|
||||
Comment,
|
||||
DirectiveName,
|
||||
Element,
|
||||
EndTagStart,
|
||||
InterpolationEnd,
|
||||
InterpolationStart,
|
||||
MacroName,
|
||||
MidTagStart,
|
||||
OpenTagStart,
|
||||
RawBody,
|
||||
RawElement,
|
||||
RawTagStart,
|
||||
SelfCloseEnd,
|
||||
StrayEndTagStart,
|
||||
TagEnd,
|
||||
TagStart,
|
||||
Text,
|
||||
} from "./parser.terms";
|
||||
|
||||
const LT = 60,
|
||||
GT = 62,
|
||||
SLASH = 47,
|
||||
HASH = 35,
|
||||
AT = 64,
|
||||
DOLLAR = 36,
|
||||
EQ = 61,
|
||||
BRACE_L = 123,
|
||||
BRACE_R = 125,
|
||||
BRACKET_L = 91,
|
||||
BRACKET_R = 93,
|
||||
PAREN_L = 40,
|
||||
PAREN_R = 41,
|
||||
DASH = 45,
|
||||
QUOTE = 34,
|
||||
APOS = 39,
|
||||
BACKSLASH = 92,
|
||||
BANG = 33;
|
||||
|
||||
/** Block directives, with the middle tags each one allows. */
|
||||
export const BLOCK_DIRECTIVES: ReadonlyMap<string, readonly string[]> = new Map([
|
||||
["attempt", ["recover"]],
|
||||
["autoesc", []],
|
||||
["compress", []],
|
||||
["escape", []],
|
||||
["function", []],
|
||||
["if", ["elseif", "else"]],
|
||||
["items", []],
|
||||
["list", ["else"]],
|
||||
["macro", []],
|
||||
["noautoesc", []],
|
||||
["noescape", []],
|
||||
["outputformat", []],
|
||||
["switch", ["case", "default", "on"]],
|
||||
]);
|
||||
|
||||
/** `<#assign x>…</#assign>`: these capture their content when they have no `=`. */
|
||||
export const CAPTURING: ReadonlySet<string> = new Set(["assign", "global", "local"]);
|
||||
|
||||
/** Directives whose content FreeMarker doesn't parse. */
|
||||
export const RAW_DIRECTIVES: ReadonlySet<string> = new Set(["noparse", "comment"]);
|
||||
|
||||
/** Every built-in directive, for completion. */
|
||||
export const DIRECTIVES = [
|
||||
"assign",
|
||||
"attempt",
|
||||
"autoesc",
|
||||
"break",
|
||||
"case",
|
||||
"compress",
|
||||
"continue",
|
||||
"default",
|
||||
"else",
|
||||
"elseif",
|
||||
"escape",
|
||||
"fallback",
|
||||
"flush",
|
||||
"ftl",
|
||||
"function",
|
||||
"global",
|
||||
"if",
|
||||
"import",
|
||||
"include",
|
||||
"items",
|
||||
"list",
|
||||
"local",
|
||||
"lt",
|
||||
"macro",
|
||||
"nested",
|
||||
"noautoesc",
|
||||
"noescape",
|
||||
"noparse",
|
||||
"nt",
|
||||
"on",
|
||||
"outputformat",
|
||||
"recover",
|
||||
"recurse",
|
||||
"return",
|
||||
"rt",
|
||||
"sep",
|
||||
"setting",
|
||||
"stop",
|
||||
"switch",
|
||||
"t",
|
||||
"visit",
|
||||
];
|
||||
|
||||
/** The blocks open around a position, innermost first, and the tag syntax (`null`: not fixed yet). */
|
||||
class Context {
|
||||
readonly hash: number;
|
||||
constructor(
|
||||
/** `#if`, `@badge`. */
|
||||
readonly name: string | null,
|
||||
readonly parent: Context | null,
|
||||
readonly square: boolean | null,
|
||||
) {
|
||||
let hash = parent ? parent.hash : square === null ? 1 : square ? 2 : 3;
|
||||
for (let i = 0; name && i < name.length; i++) hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
|
||||
this.hash = hash;
|
||||
}
|
||||
}
|
||||
|
||||
const TOP = new Context(null, null, null);
|
||||
|
||||
const isNameStart = (ch: number) => (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122) || ch == 95;
|
||||
const isName = (ch: number) => isNameStart(ch) || (ch >= 48 && ch <= 57);
|
||||
/** User-defined directive names may be qualified (`lib.badge`) or carry `:` and `-`. */
|
||||
const isMacroName = (ch: number) => isName(ch) || ch == 46 || ch == 58 || ch == DASH;
|
||||
|
||||
/** A tag opening `offset` code units ahead: its kind, sigil and name. */
|
||||
interface TagHead {
|
||||
/** Code units up to the name. */
|
||||
length: number;
|
||||
end: boolean;
|
||||
sigil: "#" | "@";
|
||||
name: string;
|
||||
square: boolean;
|
||||
}
|
||||
|
||||
function tagHead(input: InputStream, offset: number, square: boolean | null): TagHead | null {
|
||||
const open = input.peek(offset);
|
||||
if (open == LT ? square === true : open == BRACKET_L ? square === false : true) return null;
|
||||
let i = offset + 1;
|
||||
const end = input.peek(i) == SLASH;
|
||||
if (end) i++;
|
||||
const sigil = input.peek(i);
|
||||
if (sigil != HASH && sigil != AT) return null;
|
||||
i++;
|
||||
let name = "";
|
||||
const accept = sigil == HASH ? isName : isMacroName;
|
||||
for (let ch; accept((ch = input.peek(i))); i++) {
|
||||
if (!name && !isNameStart(ch)) break;
|
||||
name += String.fromCharCode(ch);
|
||||
}
|
||||
// `<#--` is a comment, `</@>` ends the innermost call; anything else needs a name.
|
||||
if (!name && !(end && sigil == AT)) return null;
|
||||
return { length: i - offset - name.length, end, sigil: sigil == HASH ? "#" : "@", name, square: open == BRACKET_L };
|
||||
}
|
||||
|
||||
const commentAt = (input: InputStream, offset: number, square: boolean | null) => {
|
||||
const open = input.peek(offset);
|
||||
return (
|
||||
(open == LT ? square !== true : open == BRACKET_L && square !== false) &&
|
||||
input.peek(offset + 1) == HASH &&
|
||||
input.peek(offset + 2) == DASH &&
|
||||
input.peek(offset + 3) == DASH
|
||||
);
|
||||
};
|
||||
|
||||
const interpolationAt = (input: InputStream, offset: number, square: boolean | null) => {
|
||||
const ch = input.peek(offset);
|
||||
return (
|
||||
(ch == DOLLAR && input.peek(offset + 1) == BRACE_L) ||
|
||||
(square === true && ch == BRACKET_L && input.peek(offset + 1) == EQ)
|
||||
);
|
||||
};
|
||||
|
||||
/** Whether a comment, a tag or an interpolation starts `offset` code units ahead. */
|
||||
function elementStart(input: InputStream, offset: number, square: boolean | null): boolean {
|
||||
const ch = input.peek(offset);
|
||||
if (ch != LT && ch != BRACKET_L && ch != DOLLAR) return false;
|
||||
return interpolationAt(input, offset, square) || commentAt(input, offset, square) || !!tagHead(input, offset, square);
|
||||
}
|
||||
|
||||
/** How far a tag scan looks for the tag's end. */
|
||||
const MAX_TAG = 4000;
|
||||
|
||||
/**
|
||||
* The rest of a tag after its name: whether it ends with `/>` (`/]`) and whether it has an
|
||||
* assignment `=` outside brackets, skipping strings and brackets.
|
||||
*/
|
||||
function tagTail(input: InputStream, offset: number, square: boolean): { selfClosing: boolean; assigns: boolean } {
|
||||
const close = square ? BRACKET_R : GT;
|
||||
let depth = 0;
|
||||
let assigns = false;
|
||||
for (let i = offset; i < offset + MAX_TAG; i++) {
|
||||
const ch = input.peek(i);
|
||||
if (ch < 0) break;
|
||||
if (ch == QUOTE || ch == APOS) {
|
||||
for (i++; ; i++) {
|
||||
const c = input.peek(i);
|
||||
if (c < 0 || c == ch) break;
|
||||
if (c == BACKSLASH) i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (ch == PAREN_L || ch == BRACE_L || ch == BRACKET_L) {
|
||||
depth++;
|
||||
continue;
|
||||
}
|
||||
if (depth > 0 && (ch == PAREN_R || ch == BRACE_R || ch == BRACKET_R)) {
|
||||
depth--;
|
||||
continue;
|
||||
}
|
||||
if (depth == 0 && ch == close) return { selfClosing: input.peek(i - 1) == SLASH, assigns };
|
||||
if (depth == 0 && ch == EQ) {
|
||||
const before = input.peek(i - 1);
|
||||
const after = input.peek(i + 1);
|
||||
if (after != EQ && before != EQ && before != BANG && before != LT && before != GT) assigns = true;
|
||||
}
|
||||
}
|
||||
return { selfClosing: false, assigns };
|
||||
}
|
||||
|
||||
export const blocks = new ContextTracker<Context>({
|
||||
start: TOP,
|
||||
shift(context, term, _stack, input) {
|
||||
const opens = term == OpenTagStart || term == RawTagStart;
|
||||
const tag = opens || term == MidTagStart || term == EndTagStart || term == StrayEndTagStart || term == TagStart;
|
||||
if (!tag) return context;
|
||||
const square = context.square ?? input.next == BRACKET_L;
|
||||
if (!opens) return square === context.square ? context : fixSyntax(context, square);
|
||||
const head = tagHead(input, 0, square);
|
||||
const base = square === context.square ? context : fixSyntax(context, square);
|
||||
return new Context(head ? head.sigil + head.name : null, base, square);
|
||||
},
|
||||
reduce(context, term) {
|
||||
return (term == Element || term == RawElement) && context.parent ? context.parent : context;
|
||||
},
|
||||
hash: (context) => context.hash,
|
||||
strict: false,
|
||||
});
|
||||
|
||||
/** `context` with the tag syntax fixed, for the blocks around it too. */
|
||||
function fixSyntax(context: Context, square: boolean): Context {
|
||||
return context.parent
|
||||
? new Context(context.name, fixSyntax(context.parent, square), square)
|
||||
: new Context(null, null, square);
|
||||
}
|
||||
|
||||
/** `<#-- … -->` (`[#-- … --]`), to the end of the document when unterminated. */
|
||||
export const comment = new ExternalTokenizer((input, stack: Stack) => {
|
||||
const context: Context = stack.context;
|
||||
if (!commentAt(input, 0, context.square)) return;
|
||||
const close = input.next == BRACKET_L ? BRACKET_R : GT;
|
||||
input.advance(4);
|
||||
for (let ch; (ch = input.next) >= 0;) {
|
||||
if (ch == DASH && input.peek(1) == DASH && input.peek(2) == close) {
|
||||
input.advance(3);
|
||||
break;
|
||||
}
|
||||
input.advance();
|
||||
}
|
||||
input.acceptToken(Comment);
|
||||
});
|
||||
|
||||
/** Template text: up to a tag, an interpolation or a comment. */
|
||||
export const text = new ExternalTokenizer((input, stack: Stack) => {
|
||||
const square = (stack.context as Context).square;
|
||||
const start = input.pos;
|
||||
while (input.next >= 0 && !elementStart(input, 0, square)) input.advance();
|
||||
if (input.pos > start) input.acceptToken(Text);
|
||||
});
|
||||
|
||||
/** The opening delimiter of a tag or an interpolation, a token telling what it is in the blocks open around it. */
|
||||
export const tagStart = new ExternalTokenizer((input, stack: Stack) => {
|
||||
const context: Context = stack.context;
|
||||
if (interpolationAt(input, 0, context.square)) {
|
||||
if (stack.canShift(InterpolationStart)) input.acceptToken(InterpolationStart, 2);
|
||||
return;
|
||||
}
|
||||
const head = tagHead(input, 0, context.square);
|
||||
if (!head) return;
|
||||
const open = context.name;
|
||||
const name = head.sigil + head.name;
|
||||
let term = TagStart;
|
||||
if (head.end) {
|
||||
term =
|
||||
open && (name == open || (head.sigil == "@" && !head.name && open.startsWith("@")))
|
||||
? EndTagStart
|
||||
: StrayEndTagStart;
|
||||
} else if (head.sigil == "#" && RAW_DIRECTIVES.has(head.name)) {
|
||||
term = RawTagStart;
|
||||
} else if (open?.startsWith("#") && BLOCK_DIRECTIVES.get(open.slice(1))?.includes(head.name)) {
|
||||
term = MidTagStart;
|
||||
} else if (head.sigil == "@" || BLOCK_DIRECTIVES.has(head.name) || CAPTURING.has(head.name)) {
|
||||
const tail = tagTail(input, head.length + head.name.length, head.square);
|
||||
const block = !tail.selfClosing && (!CAPTURING.has(head.name) || !tail.assigns);
|
||||
if (block) term = OpenTagStart;
|
||||
}
|
||||
if (!stack.canShift(term)) term = term == EndTagStart ? StrayEndTagStart : TagStart;
|
||||
if (stack.canShift(term)) input.acceptToken(term, head.length);
|
||||
});
|
||||
|
||||
/** A tag's name: a directive's (`if`) or a user-defined directive's (`lib.badge`). */
|
||||
export const tagName = new ExternalTokenizer((input) => {
|
||||
const sigil = input.peek(-1);
|
||||
if (sigil != HASH && sigil != AT) return;
|
||||
const accept = sigil == HASH ? isName : isMacroName;
|
||||
if (!isNameStart(input.next)) return;
|
||||
while (accept(input.next)) input.advance();
|
||||
input.acceptToken(sigil == HASH ? DirectiveName : MacroName);
|
||||
});
|
||||
|
||||
/** `>` / `/>` (`]` / `/]`) ending a tag, `}` (`]`) ending an interpolation. */
|
||||
export const tagEnd = new ExternalTokenizer((input, stack: Stack) => {
|
||||
const square = (stack.context as Context).square === true;
|
||||
const close = square ? BRACKET_R : GT;
|
||||
if (input.next == SLASH && input.peek(1) == close) {
|
||||
if (stack.canShift(SelfCloseEnd)) input.acceptToken(SelfCloseEnd, 2);
|
||||
return;
|
||||
}
|
||||
if (input.next == close && stack.canShift(TagEnd)) {
|
||||
input.acceptToken(TagEnd, 1);
|
||||
return;
|
||||
}
|
||||
if ((input.next == BRACE_R || (square && input.next == BRACKET_R)) && stack.canShift(InterpolationEnd)) {
|
||||
input.acceptToken(InterpolationEnd, 1);
|
||||
}
|
||||
});
|
||||
|
||||
/** The content of `noparse` or `comment`: up to the end tag closing it. */
|
||||
export const rawBody = new ExternalTokenizer((input, stack: Stack) => {
|
||||
const context: Context = stack.context;
|
||||
const name = context.name;
|
||||
if (!name) return;
|
||||
const start = input.pos;
|
||||
for (; input.next >= 0; input.advance()) {
|
||||
const head = (input.next == LT || input.next == BRACKET_L) && tagHead(input, 0, context.square);
|
||||
if (head && head.end && head.sigil + head.name == name) break;
|
||||
}
|
||||
if (input.pos > start) input.acceptToken(RawBody);
|
||||
});
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
useTextEditorWrappers,
|
||||
type EditorCloseSession,
|
||||
type EditorInput,
|
||||
type EditorKindContribution,
|
||||
type OpenOptions,
|
||||
type FileEditorResolution,
|
||||
type OpenEditorTab,
|
||||
@@ -310,6 +311,11 @@ function tabModified(tab: Tab): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether `input` opens in the preview tab when asked: always for kinds that reuse one, else per the setting. */
|
||||
function previewTabsFor(input: EditorInput, kinds: ReadonlyMap<string, EditorKindContribution>): boolean {
|
||||
return editorPrefs().tabs.previewTab || !!kinds.get(input.kind)?.reusesPreviewTab;
|
||||
}
|
||||
|
||||
export class EditorController implements SlotHost {
|
||||
manager: DocumentManager;
|
||||
readonly slots = new Map<string, EditorSlot>();
|
||||
@@ -1529,7 +1535,7 @@ export class EditorController implements SlotHost {
|
||||
const kinds = useContributions.getState().editorKinds;
|
||||
const lifecycle = documentLifecycle(input, kinds);
|
||||
const canPreview = !lifecycle || (lifecycle.allowPreview && !documentDirty({ input, lifecycle }));
|
||||
const preview = !!o.preview && editorPrefs().tabs.previewTab && canPreview;
|
||||
const preview = !!o.preview && previewTabsFor(input, kinds) && canPreview;
|
||||
if (!activate && preview) return;
|
||||
const kind = kinds.get(input.kind);
|
||||
let paneId = s.panes[generation.pane] ? generation.pane : activate ? s.activePane : null;
|
||||
@@ -2447,7 +2453,8 @@ export class EditorController implements SlotHost {
|
||||
|
||||
activeInput(options?: { previewOnly?: boolean }): EditorInput | null {
|
||||
const tab = this.activeTabOf();
|
||||
if (options?.previewOnly && (!tab?.preview || !editorPrefs().tabs.previewTab)) return null;
|
||||
const kinds = useContributions.getState().editorKinds;
|
||||
if (options?.previewOnly && (!tab?.preview || !previewTabsFor(tab.input, kinds))) return null;
|
||||
return tab?.input ?? null;
|
||||
}
|
||||
|
||||
|
||||
@@ -151,6 +151,36 @@ describe("file open order", () => {
|
||||
expect(activePath()).toBe("/p/b.ts");
|
||||
});
|
||||
|
||||
it("reuses one tab for kinds that ask for it while the preview tab is off", async () => {
|
||||
useProject.setState({ settings: { editor: { tabs: { previewTab: false } } } });
|
||||
dispose = registerEditorKind({
|
||||
kind: "test-diff",
|
||||
reusesPreviewTab: true,
|
||||
component: () => null,
|
||||
title: (input) => input.key,
|
||||
});
|
||||
const controller = setup();
|
||||
const diff = (key: string) => ({ kind: "test-diff", key });
|
||||
await controller.openInput(diff("one"), { preview: true, focus: false });
|
||||
await controller.openInput(diff("two"), { preview: true, focus: false });
|
||||
const tabs = () => Object.values(useTabs.getState().panes).flatMap((pane) => pane.tabs);
|
||||
expect(tabs().map((t) => [t.input.key, t.preview])).toEqual([["two", true]]);
|
||||
expect(controller.activeInput({ previewOnly: true })?.key).toBe("two");
|
||||
// Files still don't preview.
|
||||
await controller.openFile("/p/a.ts", { preview: true, focus: false });
|
||||
await controller.openFile("/p/b.ts", { preview: true, focus: false });
|
||||
expect(openFilePaths(useTabs.getState()).sort()).toEqual(["/p/a.ts", "/p/b.ts"]);
|
||||
// A kept diff tab stays.
|
||||
const pane = useTabs.getState().activePane;
|
||||
controller.keepTab(pane, tabs().find((t) => t.input.key == "two")!.id);
|
||||
await controller.openInput(diff("three"), { preview: true, focus: false });
|
||||
expect(
|
||||
tabs()
|
||||
.filter((t) => t.input.kind == "test-diff")
|
||||
.map((t) => t.input.key),
|
||||
).toEqual(["two", "three"]);
|
||||
});
|
||||
|
||||
it("keeps an earlier regular file without removing the newer preview", async () => {
|
||||
const { started, response } = delayProvider();
|
||||
const controller = setup();
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { CodeAction } from "@/bindings";
|
||||
import { unambiguousImport } from "./autoImport";
|
||||
|
||||
const action = (title: string, over: Partial<CodeAction> = {}): CodeAction => ({
|
||||
title,
|
||||
kind: "quickfix",
|
||||
isPreferred: false,
|
||||
disabledReason: null,
|
||||
edit: null,
|
||||
command: null,
|
||||
data: null,
|
||||
server: 1,
|
||||
...over,
|
||||
});
|
||||
|
||||
describe("unambiguousImport", () => {
|
||||
it("applies the one import fix among other quick fixes", () => {
|
||||
const fix = action("Import 'ArrayList' (java.util)");
|
||||
expect(unambiguousImport([action("Create class 'ArrayList'"), fix])).toBe(fix);
|
||||
});
|
||||
|
||||
it("recognizes C#'s add-using fix, titled with the directive", () => {
|
||||
// csharp-ls (Roslyn) for an unresolved `SceneManager`.
|
||||
const using = action("using UnityEngine.SceneManagement;", { isPreferred: true });
|
||||
const actions = [
|
||||
using,
|
||||
action("Generate field 'SceneManager' in 'Player'", { kind: null }),
|
||||
action("UnityEngine.SceneManagement.SceneManager", { kind: null }),
|
||||
action("Generate class 'SceneManager'", { kind: null }),
|
||||
];
|
||||
expect(unambiguousImport(actions)).toBe(using);
|
||||
expect(unambiguousImport([action("using static System.Math;")])?.title).toBe("using static System.Math;");
|
||||
});
|
||||
|
||||
it("leaves ambiguous, disabled and non-import fixes alone", () => {
|
||||
expect(unambiguousImport([action("using A.Scenes;"), action("using B.Scenes;")])).toBeNull();
|
||||
expect(
|
||||
unambiguousImport([action("using UnityEngine.SceneManagement;", { disabledReason: "unavailable" })]),
|
||||
).toBeNull();
|
||||
expect(unambiguousImport([action("using UnityEngine.SceneManagement;", { kind: "refactor" })])).toBeNull();
|
||||
expect(unambiguousImport([action("Remove unnecessary usings")])).toBeNull();
|
||||
expect(unambiguousImport([action("UnityEngine.SceneManagement.SceneManager")])).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -16,13 +16,21 @@ import { offsetsToRange, rangeToOffsets } from "./positions";
|
||||
import { featureBackoff } from "./availability";
|
||||
|
||||
const IDLE_MS = 1500;
|
||||
/**
|
||||
* C#'s add-import fix: Roslyn (csharp-ls) titles it with the directive itself,
|
||||
* `using UnityEngine.SceneManagement;`, never with the word "import".
|
||||
*/
|
||||
export const CSHARP_USING_FIX = /^using (?:static )?[\w.]+;$/;
|
||||
const IMPORT_TITLE = /\bimport\b/i;
|
||||
const importBackoff = featureBackoff();
|
||||
|
||||
/** The single import fix among `actions`, if exactly one exists. */
|
||||
export function unambiguousImport(actions: readonly CodeAction[]): CodeAction | null {
|
||||
const imports = actions.filter(
|
||||
(a) => !a.disabledReason && IMPORT_TITLE.test(a.title) && (!a.kind || a.kind.startsWith("quickfix")),
|
||||
(a) =>
|
||||
!a.disabledReason &&
|
||||
(IMPORT_TITLE.test(a.title) || CSHARP_USING_FIX.test(a.title)) &&
|
||||
(!a.kind || a.kind.startsWith("quickfix")),
|
||||
);
|
||||
return imports.length === 1 ? imports[0]! : null;
|
||||
}
|
||||
|
||||
@@ -151,6 +151,8 @@ describe("paste import selection", () => {
|
||||
"Import `std::collections::HashMap`",
|
||||
'Add import: "fmt"',
|
||||
"Add 'useState' to existing import declaration from 'react'",
|
||||
"using UnityEngine.SceneManagement;",
|
||||
"using static System.Math;",
|
||||
])("recognizes the import quick fix %s", (title) => {
|
||||
expect(pastedImport([action({ title }), action({ title: "Create class ArrayList" })])?.title).toBe(title);
|
||||
});
|
||||
@@ -165,6 +167,8 @@ describe("paste import selection", () => {
|
||||
{ title: "Remove unused import" },
|
||||
{ title: "Import all missing names" },
|
||||
{ title: "Optimize imports" },
|
||||
{ title: "UnityEngine.SceneManagement.SceneManager" },
|
||||
{ title: "Remove unnecessary usings" },
|
||||
])
|
||||
expect(pastedImport([action(over)])).toBeNull();
|
||||
expect(pastedImport([action({ isPreferred: true }), action({ title: "Import 'ArrayList' (other)" })])).toBeNull();
|
||||
|
||||
@@ -11,6 +11,7 @@ import { docOf, lspRequest } from "./lsp";
|
||||
import { comparePos, rangeToOffsets } from "./positions";
|
||||
import { closePopup, openPopup, useLspPopup, type LspPopup } from "./popupStore";
|
||||
import { actionsForDiagnostic } from "./intentions";
|
||||
import { CSHARP_USING_FIX } from "./autoImport";
|
||||
|
||||
const WAIT_MS = 8000;
|
||||
const SETTLE_MS = 200;
|
||||
@@ -47,7 +48,7 @@ export function pastedImport(actions: readonly CodeAction[]): CodeAction | null
|
||||
(a) =>
|
||||
a.disabledReason == null &&
|
||||
(!a.kind || a.kind === "quickfix" || a.kind.startsWith("quickfix.")) &&
|
||||
IMPORT_FIX.test(a.title) &&
|
||||
(IMPORT_FIX.test(a.title) || CSHARP_USING_FIX.test(a.title)) &&
|
||||
!/^import (?:all|missing)\b/i.test(a.title),
|
||||
);
|
||||
return imports.length === 1 ? imports[0]! : null;
|
||||
|
||||
@@ -16,6 +16,7 @@ export function activateDiffViewer(): () => void {
|
||||
const single = registerEditorKind({
|
||||
kind: DIFF_KIND,
|
||||
standalone: true,
|
||||
reusesPreviewTab: true,
|
||||
// Switching back shows the diff where it was left (scroll, caret, expanded lines),
|
||||
// without reloading the revisions.
|
||||
keepAlive: true,
|
||||
@@ -28,6 +29,7 @@ export function activateDiffViewer(): () => void {
|
||||
const combined = registerEditorKind({
|
||||
kind: COMBINED_DIFF_KIND,
|
||||
standalone: true,
|
||||
reusesPreviewTab: true,
|
||||
keepAlive: true,
|
||||
component: lazyComponent(() => import("./CombinedDiff").then((m) => m.CombinedDiffTab)),
|
||||
title: (input) => (input.data as CombinedDiffData).title ?? tx("Combined Changes Diff"),
|
||||
|
||||
@@ -426,6 +426,7 @@ export function activate(): () => void {
|
||||
registerEditorKind({
|
||||
kind: "git-merge-diff",
|
||||
standalone: true,
|
||||
reusesPreviewTab: true,
|
||||
component: lazyComponent(() => import("./GitMergeDiff").then((m) => m.GitMergeDiff)),
|
||||
title: (input) => (input.data as { path: string }).path,
|
||||
icon: () => "diff",
|
||||
|
||||
@@ -169,6 +169,11 @@ export interface EditorKindContribution {
|
||||
* `splitInput`, or moves the tab instead.
|
||||
*/
|
||||
singleton?: boolean;
|
||||
/**
|
||||
* A preview tab its opener asks for is granted even with Opening Policy › Enable preview tab
|
||||
* off, so stepping through a change set's diffs reuses one tab. Pinned or kept tabs stay.
|
||||
*/
|
||||
reusesPreviewTab?: boolean;
|
||||
/** Fresh input opened when splitting a `singleton` tab (e.g. a new shell in the same cwd). */
|
||||
splitInput?(input: EditorInput): EditorInput | Promise<EditorInput | null> | null;
|
||||
/** Last tab showing this input closed (including split tabs and tab-limit eviction). */
|
||||
|
||||
Reference in new issue
Заблокувати користувача