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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 49443fea13 fix(run): run a Flutter app's Dart files with flutter run
Current File (and Run on a Dart file) ran `dart run <file>` even inside a
Flutter app, which can't start a Flutter program. In a folder with a
detected Flutter configuration the file now runs and debugs as the app,
`flutter run -t <file>` from the app's folder, on the toolbar's device.
Dart files outside a Flutter app keep `dart run`.
2026-11-19 11:00:54 +08:00
l0ng-ai 0f652824b3 fix(database): don't leave the tree loading after a disconnect or rename (#4406)
Disconnecting a data source (Deactivate, or Auto-disconnect when idle)
forgets what it loaded, but its expanded tree nodes stayed expanded and
showed Loading until collapsed by hand, since only expanding a node loads
its children. A disconnect now also collapses the nodes of what it
forgot: the source with all its databases, or one database. Renaming a
source dropped its metadata the same way; it now saves like any edit,
which reloads what the tree had expanded.

Fixes #4388
2026-11-19 10:51:01 +08:00
l0ng-ai 10aa367df3 feat(vcs): add File › New › Project from Version Control (#4398)
The clone dialog was only reachable from the Git menu and the welcome
screen. File › New now lists it too, as its own action
(vcs.cloneProject) since a menu bar holds each action id once.

Closes #4100
2026-11-19 10:35:19 +08:00
LU XIANGRUIтаwildcatDownstairs 9622bff6bd feat(run): add a Flutter device selector (#4393)
Flutter projects get a device selector next to the run configuration. A new ide-flutter crate keeps one `flutter daemon` per project for the device list (restartable from the menu); on Unix a watchdog ends the daemon when the IDE exits. Detected Flutter apps get a `flutter run -t lib/main.dart` configuration and a Flutter run type, and Run/Debug pass `-d <id>` for the selected device, or for the device a configuration pins.

Refs #4096

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-19 10:29:15 +08:00
LU XIANGRUIтаwildcatDownstairs ad1621dee6 feat(debugger): hot reload Flutter apps on save (#4392)
While a Flutter debug session runs, saving a Dart file of its package (or a package it depends on, from .dart_tool/package_config.json) hot reloads the app, on by default and switchable under Settings › Build, Execution, Deployment › Debugger › Flutter. Flutter sessions are recognised by the flutter.appStarted event; saves are debounced (300 ms) so Save All reloads once; files with Dart errors skip the reload until fixed; saves during a pause reload on resume; failures go to the Debug console. hotReload now passes a reason (save / manual).

Refs #4096

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-19 10:18:57 +08:00
Vladislav Kuzmin 450c78b90d feat(database): support custom JDBC driver profiles (#4331)
A Custom JDBC driver connects any database that ships a JDBC driver. Driver profiles (driver and dependency JARs, driver class detected from the JARs, URL template with {host}/{port}/{database}/{file} fields) are stored locally and shared by all projects; project files can't start a driver until the user approves the source. Queries run through a bundled Java 17 bridge (java/jdbc-bridge, reproducible from source) found with the existing JDK discovery. Options › Read-only calls Connection.setReadOnly(true) and the IDE rejects table edits; Cancel calls Statement.cancel() and keeps the session, with a three-second fallback that reconnects. Transactions, Explain Plan and grid edits are off for JDBC sources.

Co-authored-by: principalwater <[email protected]>
2026-11-19 09:13:12 +08:00
Deng Liuтаdengliu 62058d5932 feat(mcp): support the built-in IDE MCP server in remote development (#4380)
In remote development (SSH, WSL, Dev Containers) the built-in IDE MCP server ran only in the desktop
shell: openidea-server never started it or answered --mcp-stdio, MCP status and confirmation commands
ran locally, and the Settings window showed the desktop's mcpServer settings for a remote window.

McpService and the MCP commands move into ide-host, so openidea-server runs its own MCP server per
host with a stable ~/.openidea/bin/openidea-server --mcp-stdio bridge. mcpServer.* settings of a
remote window apply to the remote host only. Remote MCP confirmation requests show only when this
machine trusts the remote project, and their answers route back to the server. Several servers sharing
one data directory (several remote windows on a host) each record a discovery entry; the stdio bridge
picks the one that has the project open by probing tools/list, and a server leaving promotes a live one.

Review follow-ups: the bridge no longer matches the initialize instructions text, a starting server
drops entries of servers that stopped listening, the stdio link is written only when the MCP server
starts, the MCP settings page reloads its status after Apply (a remote server's settings events reach
the project window only), and the unused process-wide MCP executable in ide-agent is gone.

Co-authored-by: dengliu <[email protected]>
2026-11-19 09:01:27 +08:00
Mansur Akhmadiтаmansur-akhmadi f0c383fc6d feat(go): add a Format with gofumpt setting for gopls (#4390)
Settings › Languages & Frameworks › Go gets a Formatting section with a Format with gofumpt checkbox (languages.go.gofumpt, off by default, global or per project). On sends gopls gofumpt: true; off sends an explicit false (gopls keeps omitted keys on reconfiguration) unless a value is already set for gopls in the language definition or in Settings › Language Servers. The explicit-default fill now also reads the Language Servers initializationOptions, so buildFlags / env given there are no longer shadowed either.

Closes #4389

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-19 09:01:01 +08:00
xiaohuiduanтаxiaohuiduan 4766a4bdef feat(tools): optional GitHub mirror prefix for tool downloads (#4038)
Adds Settings › Tools › Download Mirrors with a mirror prefix for GitHub downloads (empty by default, so nothing changes unless it is set). With a prefix such as https://gh-proxy.com/, tool and language server assets from github.com are fetched through it first and fall back to the official host on failure. Eclipse, Open VSX, Maven Central and authenticated hosts are never mirrored.

Checksums are always read from the official release data or .sha256 file, never through the mirror; a mirrored file that fails the check, or that has no published checksum at all, is discarded and the official host is used instead. The remote development server always downloads from its own release.

Closes #3295

Co-authored-by: xiaohuiduan <[email protected]>
2026-11-19 08:59:42 +08:00
l0ng-ai 44e7508af3 ci: add an always-reporting Rust checks job for the ruleset to require (#4391)
A skipped matrix job reports under its unexpanded name, so the per-OS Rust checks never appear on frontend-only PRs and requiring them blocked those PRs. The new job passes when the Rust matrix succeeded or was skipped.
2026-11-19 08:50:39 +08:00
Mansur Akhmadiтаmansur-akhmadi 42b99b9df7 feat(go): go from a go.mod dependency to its folder under External Libraries (#4379)
⌘-click / ⌘B on the module path of a require entry (single line or block, quoted or not) or the replaced module of a replace entry in go.mod selects that module's folder under External Libraries › Go Modules: the module cache folder (path@version) or vendor/<path>. Modules that aren't downloaded, versions, comments and other directives fall through to gopls as before.

Closes #4378

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-19 08:50:09 +08:00
l0ng-ai 72c84b9131 ci: run CI in the merge queue and let main's runs finish (#4387)
Adds the merge_group trigger so the merge queue's required Rust checks report, and cancels superseded runs only for pull requests: main's runs used to be cancelled by the next merge, so a broken main went unnoticed.
2026-11-19 08:45:30 +08:00
144 змінених файлів з 6871 додано та 647 видалено

No files matched your search

+21 -3
Переглянути файл
@@ -5,6 +5,7 @@ on:
pull_request:
branches: [main]
types: [opened, synchronize, reopened]
merge_group:
workflow_dispatch:
permissions:
@@ -12,8 +13,9 @@ permissions:
concurrency:
group: ci-${{ github.ref }}
# A newer push supersedes the run in progress, on main too.
cancel-in-progress: true
# A newer push supersedes a pull request's run in progress. Runs on main and in the merge
# queue finish, so a broken main shows up and the queue's required checks report.
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
CARGO_TERM_COLOR: always
@@ -23,7 +25,7 @@ env:
jobs:
# Which parts a pull request touches, so jobs it can't affect skip and leave the
# shared runners to others. Pushes and manual runs always run everything.
# shared runners to others. Pushes, the merge queue and manual runs always run everything.
changes:
name: Changes
runs-on: ubuntu-latest
@@ -140,6 +142,22 @@ jobs:
if: runner.os == 'Linux'
run: git diff --exit-code src/bindings.ts src-tauri/tests/commands.snap
# One check that always reports, for the ruleset to require: a skipped matrix job reports
# under its unexpanded name, so the per-OS checks never appear on frontend-only PRs.
rust-checks:
name: Rust checks
needs: [changes, rust]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- env:
CHANGES: ${{ needs.changes.result }}
RUST: ${{ needs.rust.result }}
run: |
echo "changes: $CHANGES, rust: $RUST"
[ "$CHANGES" = success ] && { [ "$RUST" = success ] || [ "$RUST" = skipped ]; }
# The remote development server ships as a static Linux binary (release-build.yml):
# keep that build working.
server:
Створено
+14
Переглянути файл
@@ -4319,6 +4319,7 @@ dependencies = [
"futures",
"ide-core",
"ide-http",
"ide-sdk",
"ide-ssh",
"notify",
"open",
@@ -4340,6 +4341,7 @@ dependencies = [
"tracing",
"uuid",
"zeroize",
"zip",
]
[[package]]
@@ -4376,6 +4378,17 @@ dependencies = [
"zip",
]
[[package]]
name = "ide-flutter"
version = "0.1.48"
dependencies = [
"ide-android",
"ide-core",
"parking_lot",
"serde_json",
"tempfile",
]
[[package]]
name = "ide-fonts"
version = "0.1.48"
@@ -4442,6 +4455,7 @@ dependencies = [
"ide-db",
"ide-docker",
"ide-extension",
"ide-flutter",
"ide-heap",
"ide-http",
"ide-index",
+21 -14
Переглянути файл
@@ -125,6 +125,9 @@ type Connector = Arc<
/// Returns the configured MCP servers (User and Workspace) for this project.
pub type McpServersFn = dyn Fn() -> Vec<McpServer> + Send + Sync;
/// Returns the executable of the running built-in MCP server, if any.
pub type McpExecutableFn = dyn Fn() -> Option<PathBuf> + Send + Sync;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct CopilotBinaryKey {
command: String,
@@ -148,6 +151,7 @@ struct Shared {
/// [`IDLE_RELEASE`], in milliseconds (shorter in tests).
idle_release_ms: AtomicU64,
mcp_servers_hook: RwLock<Option<Arc<McpServersFn>>>,
mcp_executable_hook: RwLock<Option<Arc<McpExecutableFn>>>,
/// Monotonic id for [`AgentEvent::Attention`] episodes.
attention_seq: AtomicU64,
}
@@ -220,8 +224,12 @@ impl Shared {
overrides: &BTreeMap<String, bool>,
) -> McpForSession {
let builtin_off = overrides.get(mcp::BUILTIN_MCP_NAME) == Some(&false);
let mut servers =
if builtin_off { Vec::new() } else { mcp_servers_for(init.mcp_stdio(), &self.paths.project_root) };
let mut servers = if builtin_off {
Vec::new()
} else {
let exe = self.mcp_executable_hook.read().as_ref().and_then(|hook| hook());
stdio_mcp_servers(exe.as_deref(), init.mcp_stdio(), &self.paths.project_root)
};
let configured = self.mcp_servers_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
servers.extend(mcp::acp_mcp_servers(&configured, provider, init, overrides));
let off = Self::mcp_off(&configured, provider, overrides);
@@ -516,6 +524,7 @@ impl AgentManager {
copilot_acp_fallback: Mutex::new(HashSet::new()),
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
mcp_servers_hook: RwLock::new(None),
mcp_executable_hook: RwLock::new(None),
attention_seq: AtomicU64::new(0),
});
shared.paths.catalogs.subscribe(&shared);
@@ -650,6 +659,11 @@ impl AgentManager {
*self.shared.mcp_servers_hook.write() = Some(Arc::from(hook));
}
/// Provides the executable of the running built-in MCP server for this host.
pub fn set_mcp_executable_hook(&self, hook: Box<McpExecutableFn>) {
*self.shared.mcp_executable_hook.write() = Some(Arc::from(hook));
}
/// The slash commands to complete for `provider`, in `task`'s directory or (without one)
/// in the project: what the agent offered last time there, unadvertised builtins,
/// and, for Claude Code, skills and custom commands on disk it has not listed.
@@ -3768,21 +3782,14 @@ mod tests;
/// The name agents know the built-in server by (its tools are `mcp__OpenIDEA__…` in Claude Code).
const BUILTIN_SERVER: &str = "OpenIDEA";
// The desktop advertises its relay only while the built-in server is listening.
static MCP_EXECUTABLE: parking_lot::RwLock<Option<std::path::PathBuf>> = parking_lot::RwLock::new(None);
pub fn set_mcp_executable(executable: Option<std::path::PathBuf>) {
*MCP_EXECUTABLE.write() = executable;
}
fn mcp_servers_for(supported: bool, root: &std::path::Path) -> Vec<Value> {
stdio_mcp_servers(MCP_EXECUTABLE.read().as_deref(), supported, root)
}
fn stdio_mcp_servers(executable: Option<&std::path::Path>, supported: bool, root: &std::path::Path) -> Vec<Value> {
let Some(executable) = executable.filter(|_| supported) else { return Vec::new() };
let command = ide_mcp::stdio_command(executable, root);
vec![json!({ "name": BUILTIN_SERVER, "command": command[0], "args": command[1..], "env": [] })]
let env: Vec<Value> = ["OPENIDEA_SERVER_HOME", "OPENIDEA_DATA_DIR"]
.into_iter()
.filter_map(|name| std::env::var(name).ok().map(|value| json!({ "name": name, "value": value })))
.collect();
vec![json!({ "name": BUILTIN_SERVER, "command": command[0], "args": command[1..], "env": env })]
}
/// What was sent of a streaming message: its first `bytes` (`utf16` UTF-16 units), which
+47
Переглянути файл
@@ -53,6 +53,10 @@ pub enum IdeEvent {
root: crate::IpcPath,
status: DirenvStatus,
},
/// The project's `flutter daemon` changed state, or a device came or went.
FlutterDevices {
list: FlutterDeviceList,
},
/// Files or directories changed on disk (after debouncing, ignore rules applied).
FsChanged {
created: Vec<crate::IpcPath>,
@@ -234,6 +238,46 @@ pub enum AskpassKind {
Confirm,
}
/// A target `flutter run -d <id>` can name, or an Android device adb sees but Flutter can't use yet.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FlutterDevice {
pub id: String,
pub name: String,
/// `android`, `ios`, `macos`, `web`, …
pub platform_type: Option<String>,
/// `mobile`, `desktop` or `web`.
pub category: Option<String>,
pub emulator: bool,
/// The adb state keeping it from being used (`unauthorized`, `offline`, …).
pub unavailable: Option<String>,
}
/// See [`FlutterDeviceList`].
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum FlutterDaemonStatus {
#[default]
Stopped,
/// Started; the first device discovery has not finished.
Starting,
Ready,
/// No `flutter` executable on the search path.
NotInstalled,
/// The daemon could not start or exited: what it printed last. It is not restarted on its own.
Failed {
message: String,
},
}
/// The project's Flutter devices, best default first.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FlutterDeviceList {
pub status: FlutterDaemonStatus,
pub devices: Vec<FlutterDevice>,
}
/// See [`IdeEvent::Direnv`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
@@ -323,6 +367,9 @@ pub enum DebugEvent {
change_type: String,
message: String,
},
/// `flutter debug_adapter`'s `flutter.appStarted` event (launch and attach): the session is
/// a Flutter app that can take a hot reload now. The plain Dart adapter never sends it.
FlutterAppStarted,
/// The session's capabilities changed after it started: fetch them again.
Capabilities,
/// The adapter's `invalidated` event: what it shows for `areas` (`all`, `stacks`, `threads`,
+21
Переглянути файл
@@ -50,6 +50,8 @@ pub struct Settings {
/// Per language server, by name (`rust-analyzer`): launch and protocol
/// options on top of the language definition, or a server defined here.
pub language_servers: BTreeMap<String, LanguageServerSettings>,
/// Tools › Download sources: a mirror prefix for the release archives the installer fetches.
pub tool_downloads: ToolDownloadSettings,
/// Editor › Inspections profiles.
pub inspections: InspectionSettings,
/// Editor › Natural Languages › Spelling.
@@ -361,6 +363,22 @@ impl Default for McpServerSettings {
}
}
/// Tools › Download sources: a mirror the installer tries when `github.com` is slow or
/// unreachable.
///
/// The mirror is a proxy prefix: the official URL is appended to it unchanged
/// (`https://mirror.example/https://github.com/o/r/releases/download/…`), which is what the
/// public GitHub proxies speak. Only `github.com` downloads are affected — those proxies
/// hard-code that host, so Eclipse JDT LS and Open VSX keep their official addresses. Empty by
/// default, so every download stays on its official host until the user opts in.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ToolDownloadSettings {
/// Proxy prefix prepended to `https://github.com/…` archive addresses only; empty keeps
/// every download on its official host.
pub github_mirror: String,
}
/// Absent profiles retain automatic discovery for existing projects.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -499,6 +517,7 @@ impl Default for Settings {
external_tools: Vec::new(),
tools: BTreeMap::new(),
language_servers: BTreeMap::new(),
tool_downloads: ToolDownloadSettings::default(),
inspections: InspectionSettings::default(),
spelling: SpellingSettings::default(),
ssh: SshSettings::default(),
@@ -1384,6 +1403,8 @@ pub struct GoSettings {
pub goroot: String,
/// Empty = `go env GOPATH`.
pub gopath: String,
/// Format with gofumpt, a stricter gofmt (gopls `gofumpt`).
pub gofumpt: bool,
pub build_tags: GoBuildTags,
pub modules: GoModules,
}
+3
Переглянути файл
@@ -367,6 +367,8 @@ pub struct DebuggerSettings {
pub skip_library_code: bool,
/// JavaScript: debugging a dev server (`vite`, `next dev`) also opens its page in a browser session.
pub debug_server_page: bool,
/// Flutter: saving a Dart file of a running debug session hot reloads the app.
pub flutter_hot_reload_on_save: bool,
pub python: PythonDebuggerSettings,
}
@@ -387,6 +389,7 @@ impl Default for DebuggerSettings {
value_tooltip_delay: 700,
skip_library_code: true,
debug_server_page: false,
flutter_hot_reload_on_save: true,
python: PythonDebuggerSettings::default(),
}
}
+27 -4
Переглянути файл
@@ -280,6 +280,14 @@ pub struct SessionExceptionFilters {
pub filters: Vec<ExceptionFilter>,
}
/// What triggered a hot reload; `flutter debug_adapter` takes it as `reason`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum HotReloadReason {
Manual,
Save,
}
/// A live session, as listed by [`DebugManager::sessions`].
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -404,6 +412,14 @@ fn is_flutter_project(dir: &Path, program: Option<&Path>) -> bool {
.any(|s| s.contains("sdk: flutter"))
}
/// `flutter debug_adapter` passes `toolArgs` on to `flutter run` / `flutter attach`.
fn add_flutter_device(arguments: &mut Value, device: Value) {
let args = arguments.as_object_mut().map(|o| o.entry("toolArgs").or_insert_with(|| json!([])));
if let Some(args) = args.and_then(Value::as_array_mut) {
args.extend([json!("-d"), device]);
}
}
fn no_session(s: DebugSessionId) -> IdeError {
IdeError::not_found(format!("no debug session {}", s.0))
}
@@ -768,6 +784,8 @@ impl DebugManager {
// one regardless of what the working directory holds.
let force_flutter =
arguments.as_object_mut().and_then(|o| o.remove("__flutter")).and_then(|v| v.as_bool()).unwrap_or(false);
// Also IDE-side: the device to run on, should this turn out to be a Flutter session.
let flutter_device = arguments.as_object_mut().and_then(|o| o.remove("__flutterDevice"));
let cwd = config
.cwd
.clone()
@@ -812,10 +830,15 @@ impl DebugManager {
// Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter`
// (the Dart adapter cannot start a program importing `dart:ui`, and hot reload
// is Flutter-only). Plain Dart projects keep the configured `dart`.
if config.adapter == "dart" && spec.command == "dart" {
if config.adapter == "dart" {
let program = arguments.get("program").and_then(Value::as_str).map(Path::new);
if force_flutter || is_flutter_project(&cwd, program) {
spec.command = "flutter".into();
if spec.command == "dart" {
spec.command = "flutter".into();
}
if let Some(device) = flutter_device {
add_flutter_device(&mut arguments, device);
}
}
}
let id = DebugSessionId::next();
@@ -1646,8 +1669,8 @@ impl DebugManager {
/// Flutter's DAP adapter: injects the changed sources into the running app.
/// Not part of the DAP standard; adapters that do not know the request reject it.
pub async fn hot_reload(&self, s: DebugSessionId) -> IdeResult<()> {
self.session(s)?.conn.request_timeout("hotReload", json!({ "reason": "manual" }), REQUEST_TIMEOUT).await?;
pub async fn hot_reload(&self, s: DebugSessionId, reason: HotReloadReason) -> IdeResult<()> {
self.session(s)?.conn.request_timeout("hotReload", json!({ "reason": reason }), REQUEST_TIMEOUT).await?;
Ok(())
}
+1
Переглянути файл
@@ -866,6 +866,7 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
change_type: crate::hot_code_replace_type(body.get("changeType")),
message: str_("message").unwrap_or_default(),
}),
"flutter.appStarted" => s.emit(DebugEvent::FlutterAppStarted),
// Sent only by adapters told `supportsInvalidatedEvent` (kotlin-lsp).
"invalidated" => s.emit(DebugEvent::Invalidated {
areas: body
+25
Переглянути файл
@@ -559,6 +559,10 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
}
}
"stepIn" | "stepOut" | "pause" => ok!(msg, Value::Null),
"hotReload" => {
ok!(msg, Value::Null);
send!(json!({"type": "event", "event": "flutter.appStarted", "body": {}}));
}
"redefineClasses" => {
send!(
json!({"type": "event", "event": "hotcodereplace", "body": {"changeType": "STARTING", "message": "Start hot code replacement procedure..."}})
@@ -1891,6 +1895,17 @@ async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled()
);
}
#[tokio::test]
async fn hot_reload_sends_its_reason_and_reports_the_flutter_app() {
let h = harness(Script::default());
let id = h.start(config()).await.unwrap();
h.manager.hot_reload(id, HotReloadReason::Manual).await.unwrap();
h.manager.hot_reload(id, HotReloadReason::Save).await.unwrap();
let reasons: Vec<_> = requests(&h, "hotReload").iter().map(|args| args["reason"].clone()).collect();
assert_eq!(reasons, [json!("manual"), json!("save")]);
h.wait_event(|e| matches!(e, DebugEvent::FlutterAppStarted)).await;
}
#[tokio::test]
async fn hot_swap_only_for_java_debug() {
let h = harness(Script::default());
@@ -2280,6 +2295,16 @@ fn flutter_projects_are_found_from_the_program_or_the_working_directory() {
std::fs::remove_dir_all(&root).unwrap();
}
#[test]
fn the_flutter_device_follows_the_tool_arguments() {
let mut arguments = json!({ "toolArgs": ["--flavor", "dev"] });
add_flutter_device(&mut arguments, json!("macos"));
assert_eq!(arguments["toolArgs"], json!(["--flavor", "dev", "-d", "macos"]));
let mut arguments = json!({});
add_flutter_device(&mut arguments, json!("chrome"));
assert_eq!(arguments["toolArgs"], json!(["-d", "chrome"]));
}
#[test]
fn rdbg_runs_the_debuggee_after_its_options_with_the_configuration_environment() {
let dir = tempfile::tempdir().unwrap();
+3 -1
Переглянути файл
@@ -7,6 +7,9 @@ license.workspace = true
[dependencies]
ide-core.workspace = true
ide-sdk.workspace = true
tempfile.workspace = true
zip.workspace = true
dunce.workspace = true
serde.workspace = true
serde_json = { workspace = true, features = ["raw_value"] }
@@ -38,5 +41,4 @@ open = "5"
[dev-dependencies]
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "net"] }
tempfile.workspace = true
ide-ssh = { workspace = true, features = ["testing"] }
+14 -1
Переглянути файл
@@ -237,6 +237,7 @@ pub enum Pool {
Mysql(ServerPool<MysqlManager>),
SqlServer(Bb8Pool<MssqlConnectionManager>),
Clickhouse(crate::clickhouse::ClickhousePool),
Jdbc(Box<crate::jdbc::JdbcPool>),
Oracle(crate::oracle::OraclePool),
Snowflake(crate::snowflake::SnowflakePool),
}
@@ -729,6 +730,7 @@ impl Pool {
Pool::Mysql(_) => DbDriver::Mysql,
Pool::SqlServer(_) => DbDriver::SqlServer,
Pool::Clickhouse(_) => DbDriver::Clickhouse,
Pool::Jdbc(_) => DbDriver::Jdbc,
Pool::Oracle(_) => DbDriver::Oracle,
Pool::Snowflake(_) => DbDriver::Snowflake,
}
@@ -919,6 +921,7 @@ impl Pool {
conn.query("SELECT 1", &[]).await.map_err(mssql_err)?.into_results().await.map_err(mssql_err)?;
Ok(Pool::SqlServer(pool))
}
DbDriver::Jdbc => Err(IdeError::invalid("An installed JDBC driver profile is required")),
DbDriver::Clickhouse => unreachable!(),
DbDriver::Oracle | DbDriver::Snowflake => unreachable!(),
}
@@ -928,6 +931,7 @@ impl Pool {
match self {
Pool::SqlServer(_) | Pool::Oracle(_) => {}
Pool::Clickhouse(p) => p.close(),
Pool::Jdbc(p) => p.close().await,
Pool::Snowflake(p) => p.close().await,
Pool::Sqlite(p) => p.close().await,
Pool::Postgres(p) => p.closed.store(true, Ordering::Relaxed),
@@ -940,6 +944,7 @@ impl Pool {
Pool::SqlServer(_) => false,
Pool::Oracle(p) => p.is_closed(),
Pool::Clickhouse(p) => p.is_closed(),
Pool::Jdbc(p) => p.is_closed(),
Pool::Snowflake(p) => p.is_closed(),
Pool::Sqlite(p) => p.is_closed(),
Pool::Postgres(p) => p.closed.load(Ordering::Relaxed),
@@ -949,6 +954,9 @@ impl Pool {
/// Runs `sql` (no row limit beyond `max`), for introspection: cells are text (see [`Cells::Text`]).
pub async fn rows(&self, sql: &str, max: usize) -> IdeResult<Vec<Vec<Option<String>>>> {
if let Pool::Jdbc(p) = self {
return Ok(p.query(sql, 0, max, &CancellationToken::new()).await?.rows);
}
if let Pool::Clickhouse(p) = self {
return Ok(p.execute(sql, max, &CancellationToken::new()).await?.rows);
}
@@ -976,6 +984,9 @@ impl Pool {
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
if let Pool::Jdbc(p) = self {
return p.query(sql, skip, max_rows, cancel).await;
}
if let Pool::Clickhouse(p) = self {
return p.execute_from(sql, skip, max_rows, cancel).await;
}
@@ -998,6 +1009,7 @@ impl Pool {
/// row when flagged (table editor submits).
pub async fn transaction(&self, statements: &[(String, bool)]) -> IdeResult<u64> {
match self {
Pool::Jdbc(_) => Err(IdeError::invalid("Custom JDBC table editing is unsupported")),
Pool::Clickhouse(_) => Err(crate::clickhouse::transaction_error()),
Pool::Snowflake(p) => p.transaction(statements).await,
Pool::SqlServer(_) => {
@@ -1088,6 +1100,7 @@ pub enum Held {
impl Held {
pub async fn acquire(pool: &Pool) -> IdeResult<Self> {
Ok(match pool {
Pool::Jdbc(_) => return Err(IdeError::invalid("Custom JDBC manual transactions are unsupported")),
Pool::Sqlite(p) => Held::Sqlite(p.acquire().await.map_err(db_err)?),
Pool::Postgres(p) => Held::Postgres(Box::new(p.get().await?)),
Pool::Mysql(p) => Held::Mysql(Box::new(p.get().await?)),
@@ -1377,7 +1390,7 @@ pub fn begin_statement(driver: DbDriver) -> &'static str {
DbDriver::Mysql => "START TRANSACTION",
DbDriver::SqlServer => "BEGIN TRAN",
DbDriver::Oracle => "", // opens implicitly with autocommit off
DbDriver::Sqlite | DbDriver::Postgres | DbDriver::Clickhouse | DbDriver::Snowflake => "BEGIN",
DbDriver::Sqlite | DbDriver::Postgres | DbDriver::Clickhouse | DbDriver::Snowflake | DbDriver::Jdbc => "BEGIN",
}
}
+678
Переглянути файл
@@ -0,0 +1,678 @@
//! A trusted local driver profile is shared by data sources. JDBC URLs and properties
//! can run driver-specific initialization. A project source may connect only with the
//! settings its user last accepted in the dialog; the approval lives outside the project.
use crate::{DataSource, DbManager, QueryResult, ResultColumn};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::io::{Cursor, Read};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::{Duration, Instant};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::process::{ChildStdin, ChildStdout, Command};
use tokio::sync::Mutex;
use tokio::time::{Instant as Deadline, timeout_at};
const LIMIT: usize = 16 * 1024 * 1024;
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DbJdbcDriver {
pub id: String,
pub name: String,
pub jars: Vec<String>,
pub class_name: String,
pub url_template: String,
}
fn persist_local(path: &Path, data: &[u8]) -> IdeResult<()> {
let dir = path.parent().expect("registry paths have a parent");
std::fs::create_dir_all(dir)?;
let mut tmp = tempfile::NamedTempFile::new_in(dir)?;
std::io::Write::write_all(&mut tmp, data)?;
tmp.persist(path).map_err(|e| IdeError::from(e.error))?;
Ok(())
}
fn local_jar(jar: &str) -> IdeResult<&Path> {
if jar.contains(if cfg!(windows) { ';' } else { ':' }) {
return Err(IdeError::invalid("A JDBC JAR path contains the system classpath separator"));
}
let path = Path::new(jar);
if !path.is_absolute() || !path.is_file() || !path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("jar")) {
return Err(IdeError::invalid("Choose an existing local .jar file for each JDBC driver file"));
}
Ok(path)
}
/// Read the standard JDBC service descriptors without executing any driver code.
pub fn jdbc_driver_classes(jars: &[String]) -> IdeResult<Vec<String>> {
let mut classes = Vec::new();
if jars.len() > 128 {
return Err(IdeError::invalid("Choose at most 128 JDBC driver files"));
}
for jar in jars {
let file = std::fs::File::open(local_jar(jar)?)?;
let mut archive = zip::ZipArchive::new(file).map_err(|_| IdeError::invalid("Invalid JDBC JAR archive"))?;
let descriptor = match archive.by_name("META-INF/services/java.sql.Driver") {
Ok(entry) => entry,
Err(zip::result::ZipError::FileNotFound) => continue,
Err(_) => return Err(IdeError::invalid("Cannot read the JDBC driver descriptor")),
};
let mut text = String::new();
descriptor.take(65537).read_to_string(&mut text)?;
if text.len() > 65536 {
return Err(IdeError::invalid("JDBC driver descriptor is too large"));
}
for line in text.lines() {
let name = line.split('#').next().unwrap_or_default().trim();
if !name.is_empty()
&& name.split('.').all(|part| {
let mut chars = part.chars();
chars.next().is_some_and(|c| c.is_alphabetic() || matches!(c, '_' | '$'))
&& chars.all(|c| c.is_alphanumeric() || matches!(c, '_' | '$'))
})
&& !classes.iter().any(|s| s == name)
{
classes.push(name.to_owned());
}
}
}
Ok(classes)
}
impl DbJdbcDriver {
fn validate(&self) -> IdeResult<()> {
if self.id.is_empty()
|| self.name.trim().is_empty()
|| self.jars.is_empty()
|| self.class_name.trim().is_empty()
{
return Err(IdeError::invalid("A JDBC driver needs a name, a driver class and at least one JAR"));
}
if !self.url_template.is_empty() && !self.url_template.starts_with("jdbc:") {
return Err(IdeError::invalid("The JDBC URL template must start with jdbc:"));
}
for jar in &self.jars {
local_jar(jar)?;
}
Ok(())
}
}
impl DbManager {
fn jdbc_registry(&self) -> IdeResult<PathBuf> {
self.global
.as_ref()
.map(|(dir, _)| dir.join("jdbc-drivers.json"))
.ok_or_else(|| IdeError::invalid("Global JDBC driver profiles are unavailable here"))
}
pub fn jdbc_drivers(&self) -> IdeResult<Vec<DbJdbcDriver>> {
let path = self.jdbc_registry()?;
match std::fs::File::open(path) {
Ok(file) => {
serde_json::from_reader(file).map_err(|e| IdeError::invalid(format!("JDBC driver profiles: {e}")))
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(vec![]),
Err(e) => Err(e.into()),
}
}
fn update_jdbc_driver(&self, id: &str, driver: Option<DbJdbcDriver>) -> IdeResult<()> {
let _guard = crate::plugin::EDIT.lock();
let path = self.jdbc_registry()?;
let mut list = self.jdbc_drivers()?;
list.retain(|d| d.id != id);
list.extend(driver);
let data = serde_json::to_vec_pretty(&list).map_err(|e| IdeError::internal(e.to_string()))?;
persist_local(&path, &data)
}
pub fn save_jdbc_driver(&self, driver: DbJdbcDriver) -> IdeResult<()> {
driver.validate()?;
self.update_jdbc_driver(&driver.id.clone(), Some(driver))
}
pub fn remove_jdbc_driver(&self, id: &str) -> IdeResult<()> {
if self.global_sources().iter().any(|s| s.driver == crate::DbDriver::Jdbc && s.jdbc_driver == id) {
return Err(IdeError::invalid("This JDBC driver is in use by a data source"));
}
self.update_jdbc_driver(id, None)
}
fn jdbc_approval(&self, source: &DataSource) -> IdeResult<(PathBuf, String)> {
let registry = self.jdbc_registry()?;
let key = serde_json::to_vec(&(&self.root, &source.id)).map_err(|e| IdeError::internal(e.to_string()))?;
let settings = serde_json::to_vec(&(
&source.jdbc_driver,
&source.url,
&source.user,
source.read_only,
&source.properties,
&source.options,
))
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok((
registry.with_file_name("jdbc-approvals").join(blake3::hash(&key).to_hex().as_str()),
blake3::hash(&settings).to_hex().to_string(),
))
}
/// Called only for the source the user explicitly saved in the connection dialog.
pub fn approve_jdbc_source(&self, source: &DataSource) -> IdeResult<()> {
if source.driver != crate::DbDriver::Jdbc || source.plugin_owner.is_some() {
return Err(IdeError::invalid("Expected a user-managed JDBC data source"));
}
let (path, fingerprint) = self.jdbc_approval(source)?;
persist_local(&path, fingerprint.as_bytes())
}
pub(crate) async fn open_pool(
&self,
source: &DataSource,
password: Option<&str>,
testing: bool,
) -> IdeResult<crate::Pool> {
if source.driver != crate::DbDriver::Jdbc {
return crate::Pool::connect(source, password, Some(&self.root)).await;
}
if source.plugin_owner.is_some() {
return Err(IdeError::invalid("Plugins cannot start custom JDBC drivers"));
}
if !testing && !source.global {
let (path, expected) = self.jdbc_approval(source)?;
if std::fs::read_to_string(path).ok().as_deref() != Some(&expected) {
return Err(IdeError::invalid(
"Review this project's JDBC URL and properties, then save the data source before connecting",
));
}
}
let driver = self
.jdbc_drivers()?
.into_iter()
.find(|d| d.id == source.jdbc_driver)
.ok_or_else(|| IdeError::invalid("Select an installed JDBC driver profile"))?;
JdbcPool::connect(source, password, driver, self.jdbc_registry()?.with_file_name("jdbc"))
.await
.map(Box::new)
.map(crate::Pool::Jdbc)
}
}
struct Bridge {
stop: tokio::sync::oneshot::Sender<()>,
exited: tokio::task::JoinHandle<()>,
sequence: u64,
input: ChildStdin,
output: ChildStdout,
}
pub struct JdbcPool {
bridge: Mutex<Option<Bridge>>,
closed: CancellationToken,
pub(crate) version: String,
pub(crate) identifier_quote: String,
}
impl Bridge {
fn start(cache: &Path, jars: &[String]) -> IdeResult<Self> {
let jdks = ide_sdk::java::installed_jdks();
let java = ide_sdk::java::java_runtime(&jdks, 17)
.ok_or_else(|| IdeError::invalid("Install a Java 17 or newer runtime to use custom JDBC drivers"))?;
let jar = ide_sdk::java::jdbc_bridge_jar(cache)
.ok_or_else(|| IdeError::invalid("Cannot install the JDBC bridge in the application data directory"))?;
let classpath = std::env::join_paths(std::iter::once(jar.as_path()).chain(jars.iter().map(Path::new)))
.map_err(|_| IdeError::invalid("A JDBC JAR path contains the system classpath separator"))?;
// Embedded databases can resolve file URLs against the JVM's working directory.
let files = cache.join("files");
std::fs::create_dir_all(&files)?;
let mut command = Command::new(ide_sdk::java::java_executable(&java.home));
command.current_dir(files);
ide_core::process::prepare(command.as_std_mut());
let mut child = command
.args(["-Xms8m", "-Xmx192m", "--enable-native-access=ALL-UNNAMED", "-cp"])
.arg(classpath)
.arg("ai.openidea.jdbc.OpenIdeaJdbc")
.env_remove("CLASSPATH")
.env_remove("JDK_JAVA_OPTIONS")
.env_remove("JAVA_TOOL_OPTIONS")
.env_remove("_JAVA_OPTIONS")
.kill_on_drop(true)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()?;
let input = child.stdin.take().expect("piped");
let output = child.stdout.take().expect("piped");
let (stop, stopped) = tokio::sync::oneshot::channel();
let exited = tokio::spawn(async move {
tokio::select! {
stop = stopped => {
// Disconnect closes stdin so a file-backed driver can flush. A dropped
// request or an unresponsive driver must be reaped without waiting.
if stop.is_err() || tokio::time::timeout(Duration::from_secs(2), child.wait()).await.is_err() {
let _ = child.kill().await;
}
}
_ = child.wait() => {}
}
});
Ok(Self { input, output, stop, exited, sequence: 0 })
}
async fn close(self) {
drop(self.input);
let _ = self.stop.send(());
let _ = self.exited.await;
}
}
// Request: u64 request id, u32 field count, then length-prefixed UTF-8 fields.
// Zero fields cancels that id. Replies have a u32 length; zero acknowledges Cancel.
fn encode(id: u64, fields: &[&str]) -> IdeResult<Vec<u8>> {
if fields.is_empty() || fields.len() > 8192 {
return Err(IdeError::invalid("Invalid JDBC field count"));
}
let size = fields
.iter()
.try_fold(12usize, |n, s| n.checked_add(4)?.checked_add(s.len()).filter(|n| *n <= LIMIT))
.ok_or_else(|| IdeError::invalid("JDBC request exceeds 16 MiB"))?;
let mut data = Vec::with_capacity(size);
data.extend_from_slice(&id.to_be_bytes());
data.extend_from_slice(&(fields.len() as u32).to_be_bytes());
for field in fields {
data.extend_from_slice(&(field.len() as u32).to_be_bytes());
data.extend_from_slice(field.as_bytes());
}
Ok(data)
}
async fn read_frame(output: &mut (impl AsyncRead + Unpin)) -> IdeResult<Vec<u8>> {
let n = output.read_u32().await? as usize;
if n > LIMIT {
return Err(IdeError::invalid("JDBC response exceeds 16 MiB"));
}
let mut data = vec![0; n];
output.read_exact(&mut data).await?;
Ok(data)
}
const CANCEL_GRACE: Duration = Duration::from_secs(3);
fn cancel_timeout() -> IdeError {
IdeError::invalid("The JDBC driver did not stop in time. The session was closed. Reconnect to continue.")
}
async fn exchange(
input: &mut (impl AsyncWrite + Unpin),
output: &mut (impl AsyncRead + Unpin),
frame: Vec<u8>,
cancel: &CancellationToken,
) -> IdeResult<Option<Vec<u8>>> {
let mut stop = [0; 12];
stop[..8].copy_from_slice(&frame[..8]);
let early_deadline = {
let send = input.write_all(&frame);
tokio::pin!(send);
tokio::select! {
result = &mut send => { result?; None },
() = cancel.cancelled() => {
let end = Deadline::now() + CANCEL_GRACE;
timeout_at(end, send).await.map_err(|_| cancel_timeout())??;
Some(end)
}
}
};
drop(frame);
let (first, deadline) = {
let reply = read_frame(output);
tokio::pin!(reply);
let end = tokio::select! {
biased;
() = cancel.cancelled() => early_deadline.unwrap_or_else(|| Deadline::now() + CANCEL_GRACE),
data = &mut reply => {
let data = data?;
if data.is_empty() { return Err(IdeError::invalid("Unexpected JDBC cancellation acknowledgement")); }
return Ok(Some(data));
}
};
let first = timeout_at(end, async {
input.write_all(&stop).await?;
reply.await
})
.await
.map_err(|_| cancel_timeout())??;
(first, end)
};
// Drain both frames before the next statement can use this session. The driver
// may complete the statement before or after the control thread acknowledges it.
let data = if first.is_empty() {
timeout_at(deadline, read_frame(output)).await.map_err(|_| cancel_timeout())??
} else {
if timeout_at(deadline, output.read_u32()).await.map_err(|_| cancel_timeout())?? != 0 {
return Err(IdeError::invalid("Invalid JDBC cancellation acknowledgement"));
}
first
};
match data.first() {
// A committed statement may have finished before the control thread received Cancel.
Some(1) => Ok(Some(data)),
Some(0) => Ok(None),
_ => Err(IdeError::invalid("Invalid JDBC cancellation response")),
}
}
impl JdbcPool {
async fn connect(
source: &DataSource,
password: Option<&str>,
driver: DbJdbcDriver,
cache: PathBuf,
) -> IdeResult<Self> {
driver.validate()?;
let mut fields = vec![
"open".to_string(),
driver.class_name,
source.url.clone(),
source.user.clone(),
password.unwrap_or_default().to_owned(),
source.read_only.to_string(),
];
for p in &source.properties {
if p.name.eq_ignore_ascii_case("password") {
return Err(IdeError::invalid("Enter the JDBC password in the password field"));
}
fields.extend([p.name.clone(), p.value.clone()]);
}
let bridge = tokio::task::spawn_blocking(move || Bridge::start(&cache, &driver.jars))
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
let mut pool = Self {
bridge: Mutex::new(Some(bridge)),
closed: CancellationToken::new(),
version: String::new(),
identifier_quote: String::new(),
};
let args: Vec<_> = fields.iter().map(String::as_str).collect();
let cancel = CancellationToken::new();
let result = tokio::time::timeout(Duration::from_secs(30), pool.request(&args, "", &cancel))
.await
.map_err(|_| IdeError::new(ide_core::error::ErrorKind::TimedOut, "JDBC connection timed out"))??;
let mut metadata = result.rows.into_iter().next().unwrap_or_default().into_iter();
pool.version = metadata.next().flatten().unwrap_or_else(|| "Connected".into());
pool.identifier_quote = metadata.next().flatten().unwrap_or_default().trim().into();
Ok(pool)
}
pub(crate) async fn close(&self) {
self.closed.cancel();
if let Some(bridge) = self.bridge.lock().await.take() {
bridge.close().await;
}
}
pub(crate) fn is_closed(&self) -> bool {
self.closed.is_cancelled()
}
pub(crate) async fn query(
&self,
sql: &str,
skip: usize,
max: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
self.query_in_schema(sql, skip, max, cancel, None).await
}
pub(crate) async fn query_in_schema(
&self,
sql: &str,
skip: usize,
max: usize,
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
self.request(
&["query", sql, &skip.to_string(), &max.min(i32::MAX as usize).to_string(), schema.unwrap_or_default()],
sql,
cancel,
)
.await
}
pub(crate) async fn page(
&self,
sql: &str,
offset: u64,
limit: u64,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
self.request(&["page", sql, &offset.to_string(), &limit.min(i32::MAX as u64).to_string()], sql, cancel).await
}
pub(crate) async fn metadata(&self, fields: &[&str]) -> IdeResult<Vec<Vec<Option<String>>>> {
Ok(self.request(fields, "", &CancellationToken::new()).await?.rows)
}
async fn request(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult<QueryResult> {
let mut slot = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
() = self.closed.cancelled() => return Err(IdeError::invalid("JDBC connection is closed")),
slot = self.bridge.lock() => slot,
};
let bridge = slot
.as_mut()
.ok_or_else(|| IdeError::invalid("JDBC connection is closed; reconnect to start a new session"))?;
bridge.sequence = bridge.sequence.wrapping_add(1);
let frame = encode(bridge.sequence, fields)?;
let mut bridge = slot.take().expect("checked above");
// Dropping an in-flight request must discard its process and partially consumed frame.
let interrupted = self.closed.clone().drop_guard();
let start = Instant::now();
let response = tokio::select! {
biased;
() = self.closed.cancelled() => Err(IdeError::cancelled()),
response = exchange(&mut bridge.input, &mut bridge.output, frame, cancel) => response,
};
let data = match response {
Ok(data) => {
*slot = Some(bridge);
interrupted.disarm();
data
}
Err(e) => {
drop(bridge.stop);
let _ = bridge.exited.await;
return Err(e);
}
};
decode(&data.ok_or_else(IdeError::cancelled)?, sql, start.elapsed().as_secs_f64() * 1000.0)
}
}
fn decode(data: &[u8], sql: &str, elapsed_ms: f64) -> IdeResult<QueryResult> {
let mut input = Cursor::new(data);
fn bytes<const N: usize>(input: &mut Cursor<&[u8]>) -> IdeResult<[u8; N]> {
let mut buf = [0; N];
Read::read_exact(input, &mut buf)?;
Ok(buf)
}
fn flag(input: &mut Cursor<&[u8]>) -> IdeResult<bool> {
match bytes::<1>(input)? {
[0] => Ok(false),
[1] => Ok(true),
_ => Err(IdeError::invalid("Invalid JDBC flag")),
}
}
fn field(input: &mut Cursor<&[u8]>) -> IdeResult<Option<String>> {
let n = i32::from_be_bytes(bytes(input)?);
if n == -1 {
return Ok(None);
}
let start = input.position() as usize;
let end = start
.checked_add(n as usize)
.filter(|end| *end <= input.get_ref().len())
.ok_or_else(|| IdeError::invalid("Invalid JDBC field length"))?;
let value = String::from_utf8_lossy(&input.get_ref()[start..end]).into_owned();
input.set_position(end as u64);
Ok(Some(value))
}
if !flag(&mut input)? {
return Err(IdeError::invalid(field(&mut input)?.unwrap_or_else(|| "JDBC request failed".into())));
}
let count = u32::from_be_bytes(bytes(&mut input)?) as usize;
if count > data.len() / 8 {
return Err(IdeError::invalid("Invalid JDBC column count"));
}
let mut columns = Vec::new();
for _ in 0..count {
columns.push(ResultColumn {
name: field(&mut input)?.unwrap_or_default(),
type_name: field(&mut input)?.unwrap_or_default(),
});
}
let mut rows = vec![];
while flag(&mut input)? {
if count == 0 {
return Err(IdeError::invalid("JDBC returned a row with no columns"));
}
rows.push((0..count).map(|_| field(&mut input)).collect::<IdeResult<_>>()?);
}
let has_more = flag(&mut input)?;
let affected = i64::from_be_bytes(bytes(&mut input)?);
if input.position() != data.len() as u64 {
return Err(IdeError::invalid("Invalid trailing JDBC response data"));
}
Ok(QueryResult {
statement: sql.into(),
columns,
rows,
has_more,
affected: (affected >= 0).then_some(affected as f64),
elapsed_ms,
execution_ms: elapsed_ms,
})
}
impl DbManager {
pub(crate) async fn jdbc_completion(&self, id: &str, pool: &JdbcPool) -> IdeResult<crate::CompletionModel> {
let mut tables = vec![];
let schemas = self.schemas(id).await?;
for schema in &schemas {
for table in self.tables(id, schema).await? {
tables.push(crate::CompletionTable {
schema: schema.clone(),
name: table.name,
kind: table.kind,
columns: vec![],
});
if tables.len() >= crate::MAX_META_ROWS {
break;
}
}
if tables.len() >= crate::MAX_META_ROWS {
break;
}
}
Ok(crate::CompletionModel {
default_schema: pool
.metadata(&["namespace"])
.await?
.into_iter()
.flatten()
.flatten()
.next()
.unwrap_or_default(),
tables,
foreign_keys: vec![],
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn frame_codec_checks_both_16_mib_boundaries() {
assert_eq!(encode(7, &["a"]).unwrap(), [0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 1, b'a']);
let mut field = "x".repeat(LIMIT - 16);
assert_eq!(encode(1, &[&field]).unwrap().len(), LIMIT);
field.push('x');
assert!(encode(1, &[&field]).is_err());
let mut framed = vec![0u8; LIMIT + 4];
framed[..4].copy_from_slice(&(LIMIT as u32).to_be_bytes());
assert_eq!(read_frame(&mut framed.as_slice()).await.unwrap().len(), LIMIT);
assert!(read_frame(&mut &((LIMIT + 1) as u32).to_be_bytes()[..]).await.is_err());
assert!(read_frame(&mut &[0, 0, 0, 2, 1u8][..]).await.is_err());
}
#[tokio::test]
async fn cancel_drains_partial_replies_in_either_order() {
for ack_first in [true, false] {
let (mut input, mut peer_input) = tokio::io::duplex(1);
let (mut output, mut peer_output) = tokio::io::duplex(1);
let cancel = CancellationToken::new();
let frame = encode(42, &["query"]).unwrap();
let peer = async {
let mut request = vec![0; frame.len()];
peer_input.read_exact(&mut request).await.unwrap();
assert_eq!(request, frame);
// The one-byte pipe forces the reader to consume part of the header before Cancel.
peer_output.write_all(&[0, 0]).await.unwrap();
cancel.cancel();
let mut stop = [0; 12];
peer_input.read_exact(&mut stop).await.unwrap();
assert_eq!(&stop[..8], &42u64.to_be_bytes());
assert_eq!(&stop[8..], &[0; 4]);
let frames = if ack_first { [0, 0, 0, 0, 0, 1, 0] } else { [0, 1, 1, 0, 0, 0, 0] };
peer_output.write_all(&frames).await.unwrap();
};
let (result, ()) = tokio::join!(exchange(&mut input, &mut output, frame.clone(), &cancel), peer);
assert_eq!(result.unwrap(), (!ack_first).then(|| vec![1]));
}
}
#[tokio::test]
async fn exchange_rejects_unexpected_acknowledgements() {
let cancel = CancellationToken::new();
let mut sink = tokio::io::sink();
let mut reply = &[0, 0, 0, 1, 1u8][..];
assert_eq!(
exchange(&mut sink, &mut reply, encode(1, &["query"]).unwrap(), &cancel).await.unwrap(),
Some(vec![1])
);
for cancelled in [false, true] {
if cancelled {
cancel.cancel();
}
let mut duplicate_ack = &[0u8; 8][..];
assert!(exchange(&mut sink, &mut duplicate_ack, encode(1, &["query"]).unwrap(), &cancel).await.is_err());
}
let (mut peer, mut output) = tokio::io::duplex(4);
peer.write_u32(0).await.unwrap();
let error = exchange(&mut sink, &mut output, encode(1, &["query"]).unwrap(), &cancel).await.unwrap_err();
assert_eq!(error.message, cancel_timeout().message);
}
#[test]
fn result_codec_preserves_null_and_rejects_incomplete_frames() {
let mut frame =
vec![1, 0, 0, 0, 1, 0, 0, 0, 1, b'n', 0, 0, 0, 3, b'i', b'n', b't', 1, 255, 255, 255, 255, 0, 0];
frame.extend_from_slice(&(-1i64).to_be_bytes());
let result = decode(&frame, "select", 0.).unwrap();
assert_eq!(result.columns[0].name, "n");
assert_eq!(result.rows, [vec![None]]);
for end in 0..frame.len() {
assert!(decode(&frame[..end], "", 0.).is_err());
}
frame.push(0);
assert!(decode(&frame, "", 0.).is_err());
assert!(decode(&[2], "", 0.).is_err());
}
}
+62 -11
Переглянути файл
@@ -4,6 +4,8 @@
pub mod catalog;
mod clickhouse;
mod jdbc;
pub use jdbc::{DbJdbcDriver, jdbc_driver_classes};
pub mod conn;
pub mod history;
mod oracle;
@@ -339,7 +341,7 @@ fn group_foreign_keys(rows: Vec<Vec<Option<String>>>, tables: &[CompletionTable]
/// never contain `:`.
/// Snowflake is HTTPS to a named host: a tunnel's local end cannot pass its certificate check.
fn tunneled(driver: DbDriver) -> bool {
!matches!(driver, DbDriver::Sqlite | DbDriver::Snowflake)
!matches!(driver, DbDriver::Sqlite | DbDriver::Snowflake | DbDriver::Jdbc)
}
/// The database host and port the SSH host forwards to.
@@ -759,7 +761,7 @@ impl DbManager {
};
let (target, tunnel) = self.endpoint(source, ssh_secret, false).await?;
self.restore_sso(source).await;
let connected = Pool::connect(&target, password.as_deref(), Some(&self.root)).await;
let connected = self.open_pool(&target, password.as_deref(), true).await;
self.keep_sso(source).await;
let pool = connected.map_err(|e| {
through_tunnel(
@@ -768,7 +770,13 @@ impl DbManager {
tunnel.is_some().then(|| self.ssh_label(source.ssh.as_ref().expect("tunneled"))).as_deref(),
)
})?;
if let Pool::Jdbc(p) = &pool {
let version = p.version.clone();
pool.close().await;
return Ok(version);
}
let version = match source.driver {
DbDriver::Jdbc => unreachable!("JDBC uses driver metadata"),
DbDriver::Sqlite => "SELECT 'SQLite ' || sqlite_version()",
DbDriver::Postgres | DbDriver::Clickhouse => "SELECT version()",
DbDriver::Mysql => "SELECT CONCAT(@@version_comment, ' ', VERSION())",
@@ -861,7 +869,7 @@ impl DbManager {
let password = self.password(&source).await;
let (target, tunnel) = self.endpoint(&source, None, true).await?;
self.restore_sso(&source).await;
let connected = Pool::connect(&target, password.as_deref(), Some(&self.root)).await;
let connected = self.open_pool(&target, password.as_deref(), false).await;
self.keep_sso(&source).await;
let pool = match connected {
Ok(p) => Arc::new(p),
@@ -1071,7 +1079,10 @@ impl DbManager {
if let Pool::Snowflake(p) = &*pool {
return snowflake::meta::schemas(p, system).await;
}
let rows = pool.rows(sql::schemas(pool.driver(), system), MAX_META_ROWS).await?;
let rows = match &*pool {
Pool::Jdbc(p) => p.metadata(&["schemas"]).await?,
_ => pool.rows(sql::schemas(pool.driver(), system), MAX_META_ROWS).await?,
};
Ok(rows.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect())
}
@@ -1080,7 +1091,10 @@ impl DbManager {
if let Pool::Snowflake(p) = &*pool {
return snowflake::meta::tables(p, schema).await;
}
let rows = pool.rows(&sql::tables(pool.driver(), schema), MAX_META_ROWS).await?;
let rows = match &*pool {
Pool::Jdbc(p) => p.metadata(&["tables", schema]).await?,
_ => pool.rows(&sql::tables(pool.driver(), schema), MAX_META_ROWS).await?,
};
Ok(rows
.into_iter()
.filter_map(|r| {
@@ -1097,9 +1111,11 @@ impl DbManager {
return snowflake::meta::table_details(p, schema, table).await;
}
let driver = pool.driver();
let columns = pool
.rows(&sql::columns(driver, schema, table), MAX_META_ROWS)
.await?
let rows = match &*pool {
Pool::Jdbc(p) => p.metadata(&["columns", schema, table]).await?,
_ => pool.rows(&sql::columns(driver, schema, table), MAX_META_ROWS).await?,
};
let columns = rows
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
@@ -1111,6 +1127,9 @@ impl DbManager {
Some(ColumnInfo { name, data_type, nullable, default, primary_key })
})
.collect();
if driver == DbDriver::Jdbc {
return Ok(TableDetails { columns, indexes: vec![], foreign_keys: vec![], triggers: vec![] });
}
let mut indexes: Vec<IndexInfo> = Vec::new();
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
let mut it = r.into_iter();
@@ -1271,6 +1290,7 @@ impl DbManager {
rows.into_iter().filter_map(|r| r.into_iter().nth(i).flatten()).collect()
};
match driver {
DbDriver::Jdbc => Err(IdeError::invalid("Custom JDBC sources do not provide vendor-specific DDL")),
DbDriver::Sqlite => {
let stmts = cells(pool.rows(&sql::sqlite_ddl(schema, name), MAX_META_ROWS).await?, 0);
if stmts.is_empty() {
@@ -1395,6 +1415,7 @@ impl DbManager {
let driver = pool.driver();
let mut tables: Vec<CompletionTable> = Vec::new();
let rows = match &*pool {
Pool::Jdbc(p) => return self.jdbc_completion(id, p).await,
Pool::Snowflake(p) => {
tables = snowflake::meta::completion(p).await?;
Vec::new()
@@ -1515,6 +1536,9 @@ impl DbManager {
schema: Option<&str>,
) -> IdeResult<Vec<PlanNode>> {
let driver = self.pool(id).await?.driver();
if driver == DbDriver::Jdbc {
return Err(IdeError::invalid("Custom JDBC execution plans are unsupported"));
}
if driver == DbDriver::Oracle {
// EXPLAIN PLAN writes PLAN_TABLE; the plan is read (and cleaned up) separately.
let plan_id = format!(
@@ -1554,6 +1578,9 @@ impl DbManager {
schema: Option<&str>,
) -> IdeResult<QueryResult> {
let pool = self.pool(id).await?;
if let Pool::Jdbc(p) = &*pool {
return p.query_in_schema(statement, skip, max_rows, cancel, schema).await;
}
let session = self.sessions.lock().get(id).cloned();
let Some(session) = session else {
if schema.is_none() {
@@ -1595,6 +1622,9 @@ impl DbManager {
/// Switches `id` between auto-commit and manual commit. Leaving manual
/// mode rolls back what was not committed.
pub async fn set_manual_commit(&self, id: &str, manual: bool) -> IdeResult<()> {
if manual && self.source(id)?.driver == DbDriver::Jdbc {
return Err(IdeError::invalid("Custom JDBC manual transactions are unsupported"));
}
if manual {
if self.source(id)?.driver == DbDriver::Clickhouse {
return Err(IdeError::invalid("ClickHouse manual transactions are unsupported"));
@@ -1614,6 +1644,9 @@ impl DbManager {
if self.source(id).is_ok_and(|s| s.driver == DbDriver::Clickhouse) {
return Err(IdeError::invalid("ClickHouse manual transactions are unsupported"));
}
if self.source(id).is_ok_and(|s| s.driver == DbDriver::Jdbc) {
return Err(IdeError::invalid("Custom JDBC manual transactions are unsupported"));
}
let session = self.sessions.lock().get(id).cloned();
let Some(session) = session else { return Ok(()) };
let mut held = session.lock().await;
@@ -1649,8 +1682,22 @@ impl DbManager {
) -> IdeResult<TablePage> {
let details = self.table_details(id, schema, table).await?;
let pool = self.pool(id).await?;
let sql = sql::table_page(pool.driver(), schema, table, filter, sort, offset, limit);
let mut result = pool.execute(&sql, limit as usize, cancel).await?;
let mut result = if let Pool::Jdbc(p) = &*pool {
let q = &p.identifier_quote;
let names = [schema, table].into_iter().chain(sort.iter().map(|k| k.column.as_str()));
if q.is_empty()
&& names.into_iter().any(|name| !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
{
return Err(IdeError::invalid("This JDBC driver cannot quote the selected identifier"));
}
let quote = |s: &str| format!("{q}{}{q}", s.replace(q, &format!("{q}{q}")));
let name = if schema.is_empty() { quote(table) } else { format!("{}.{}", quote(schema), quote(table)) };
let sql = sql::table_select(&name, filter, sort, quote);
p.page(&sql, offset, limit, cancel).await?
} else {
let sql = sql::table_page(pool.driver(), schema, table, filter, sort, offset, limit);
pool.execute(&sql, limit as usize, cancel).await?
};
if result.columns.is_empty() {
result.columns = details
.columns
@@ -1663,7 +1710,11 @@ impl DbManager {
/// Applies the table editor's pending changes in one transaction.
pub async fn apply_edits(&self, id: &str, schema: &str, table: &str, edits: &[DbRowEdit]) -> IdeResult<u64> {
if self.source(id)?.driver == DbDriver::Clickhouse {
let source = self.source(id)?;
if source.read_only {
return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only"));
}
if source.driver == DbDriver::Clickhouse {
return Err(IdeError::invalid("ClickHouse table editing is unsupported"));
}
let pool = self.pool(id).await?;
+2 -1
Переглянути файл
@@ -36,7 +36,7 @@ pub fn explain_statement(driver: DbDriver, statement: &str) -> String {
DbDriver::Sqlite => format!("EXPLAIN QUERY PLAN {s}"),
DbDriver::Postgres => format!("EXPLAIN (FORMAT JSON) {s}"),
DbDriver::Clickhouse => format!("EXPLAIN json = 1 {s}"),
DbDriver::Mysql => format!("EXPLAIN {s}"),
DbDriver::Mysql | DbDriver::Jdbc => format!("EXPLAIN {s}"),
DbDriver::SqlServer => format!("SET SHOWPLAN_TEXT ON; {s}"),
DbDriver::Oracle => format!("EXPLAIN PLAN FOR {s}"),
DbDriver::Snowflake => format!("EXPLAIN USING TABULAR {s}"),
@@ -77,6 +77,7 @@ pub fn parse(driver: DbDriver, result: &QueryResult) -> IdeResult<Vec<PlanNode>>
let names: Vec<&str> = result.columns.iter().map(|c| c.name.as_str()).collect();
Ok(mysql(&names, &result.rows))
}
DbDriver::Jdbc => Err(IdeError::invalid("Custom JDBC execution plans are unsupported")),
DbDriver::SqlServer => Ok(Vec::new()),
DbDriver::Snowflake => {
let names: Vec<&str> = result.columns.iter().map(|c| c.name.as_str()).collect();
+18 -3
Переглянути файл
@@ -23,12 +23,13 @@ pub enum DbDriver {
/// Oracle Database (pure-Rust thin driver, no client library).
Oracle,
Snowflake,
Jdbc,
}
impl DbDriver {
pub fn default_port(self) -> Option<u16> {
match self {
DbDriver::Sqlite => None,
DbDriver::Sqlite | DbDriver::Jdbc => None,
DbDriver::Postgres => Some(5432),
DbDriver::Mysql => Some(3306),
DbDriver::SqlServer => Some(1433),
@@ -191,6 +192,9 @@ pub struct DataSource {
pub id: String,
pub name: String,
pub driver: DbDriver,
/// An app-wide driver profile id; classpaths never come from a project.
#[serde(skip_serializing_if = "String::is_empty")]
pub jdbc_driver: String,
pub host: String,
pub port: Option<u16>,
pub database: String,
@@ -237,6 +241,7 @@ impl Default for DataSource {
id: String::new(),
name: String::new(),
driver: DbDriver::Sqlite,
jdbc_driver: String::new(),
host: "localhost".into(),
port: None,
database: String::new(),
@@ -390,6 +395,12 @@ impl DataSource {
/// database, user, SSL and driver properties come from the URL (properties
/// of the Advanced tab still apply after the URL's).
pub fn resolved(&self) -> IdeResult<DataSource> {
if self.driver == DbDriver::Jdbc {
if !self.url.starts_with("jdbc:") {
return Err(IdeError::invalid("Enter a JDBC URL starting with jdbc:"));
}
return Ok(self.clone());
}
if !self.url_only {
return Ok(self.clone());
}
@@ -476,7 +487,7 @@ impl DataSource {
/// The password written in the URL of a [`DataSource::url_only`] data source.
pub fn url_password(&self) -> Option<String> {
if !self.url_only {
if self.driver == DbDriver::Jdbc || !self.url_only {
return None;
}
parse_url(&self.url).ok()?.password
@@ -491,7 +502,11 @@ struct SourcesFile {
/// The project's data sources.
pub fn load(root: &Path) -> IdeResult<Vec<DataSource>> {
read(&project_dir::path(root, FILE))
let mut sources = read(&project_dir::path(root, FILE))?;
for source in &mut sources {
source.global = false;
}
Ok(sources)
}
/// Saves the project's data sources.
+34 -15
Переглянути файл
@@ -70,6 +70,7 @@ pub fn sqlserver_databases() -> &'static str {
pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
match driver {
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
DbDriver::Sqlite => "SELECT name FROM pragma_database_list WHERE name <> 'temp' ORDER BY seq",
DbDriver::Clickhouse if system => "SELECT name FROM system.databases ORDER BY name",
DbDriver::Clickhouse => {
@@ -114,6 +115,7 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
/// Rows: `name, kind` where kind is `table`, `view` or `materialized view`.
pub fn tables(driver: DbDriver, schema: &str) -> String {
match driver {
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
DbDriver::Clickhouse => format!(
"SELECT name, CASE engine WHEN 'View' THEN 'view' WHEN 'MaterializedView' THEN 'materialized view' \
WHEN 'WindowView' THEN 'view' ELSE 'table' END FROM system.tables \
@@ -164,6 +166,7 @@ const SNOWFLAKE_TYPE: &str = "CASE WHEN data_type = 'NUMBER' THEN 'NUMBER(' || n
pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
match driver {
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
DbDriver::Clickhouse => format!(
"SELECT name, type, CASE WHEN startsWith(type, 'Nullable(') \
OR startsWith(type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, \
@@ -225,6 +228,7 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
match driver {
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
DbDriver::Clickhouse => format!(
"SELECT * FROM (SELECT 'PRIMARY KEY' AS index_name, 0 AS is_unique, primary_key AS expression \
FROM system.tables WHERE database = {s} AND name = {t} AND primary_key != '' \
@@ -269,6 +273,7 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
/// for SQL completion, grouped by table in column order.
pub fn completion_columns(driver: DbDriver) -> &'static str {
match driver {
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
DbDriver::Clickhouse => {
"SELECT c.database, c.table, CASE t.engine WHEN 'View' THEN 'view' \
WHEN 'MaterializedView' THEN 'materialized view' WHEN 'WindowView' THEN 'view' ELSE 'table' END, \
@@ -357,6 +362,7 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
/// when the key references the primary key implicitly.
pub fn foreign_keys(driver: DbDriver) -> &'static str {
match driver {
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
DbDriver::Clickhouse => "SELECT '', '', '', '', '', '', '' WHERE 0",
DbDriver::Snowflake => "SELECT '', '', '', '', '', '', '' WHERE 1 = 0",
DbDriver::Sqlite => {
@@ -409,6 +415,7 @@ pub fn foreign_keys(driver: DbDriver) -> &'static str {
pub fn table_foreign_keys(driver: DbDriver, schema: &str, table: &str) -> String {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
match driver {
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
DbDriver::Clickhouse | DbDriver::Snowflake => foreign_keys(driver).to_owned(),
DbDriver::Sqlite => format!(
"SELECT {s}, {t}, f.id, f.\"from\", {s}, f.\"table\", f.\"to\" FROM pragma_foreign_key_list({t}, {s}) f ORDER BY f.id, f.seq"
@@ -432,7 +439,7 @@ pub fn table_foreign_keys(driver: DbDriver, schema: &str, table: &str) -> String
pub fn current_schema(driver: DbDriver) -> Option<&'static str> {
match driver {
DbDriver::Clickhouse => Some("SELECT currentDatabase()"),
DbDriver::Sqlite => None,
DbDriver::Sqlite | DbDriver::Jdbc => None,
DbDriver::Postgres => Some("SELECT current_schema()"),
DbDriver::Mysql => Some("SELECT DATABASE()"),
DbDriver::SqlServer => Some("SELECT DB_NAME()"),
@@ -446,7 +453,7 @@ pub fn current_schema(driver: DbDriver) -> Option<&'static str> {
/// has no schema to switch — SQLite's `main`, ClickHouse's `USE` differs).
pub fn use_schema(driver: DbDriver, schema: &str) -> Option<String> {
match driver {
DbDriver::Sqlite | DbDriver::Clickhouse => None,
DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc => None,
DbDriver::Postgres => Some(format!("SET search_path TO {}", quote_ident(driver, schema))),
DbDriver::Mysql | DbDriver::SqlServer => Some(format!("USE {}", quote_ident(driver, schema))),
DbDriver::Oracle => Some(format!("ALTER SESSION SET CURRENT_SCHEMA = {}", quote_ident(driver, schema))),
@@ -462,17 +469,13 @@ pub struct SortKey {
pub descending: bool,
}
/// One page of a table: `limit + 1` rows so the caller knows whether more exist.
pub fn table_page(
driver: DbDriver,
schema: &str,
table: &str,
pub(crate) fn table_select(
qualified_name: &str,
filter: Option<&str>,
sort: &[SortKey],
offset: u64,
limit: u64,
quote: impl Fn(&str) -> String,
) -> String {
let mut sql = format!("SELECT * FROM {}", qualified(driver, schema, table));
let mut sql = format!("SELECT * FROM {}", qualified_name);
if let Some(f) = filter.map(str::trim).filter(|f| !f.is_empty()) {
let mut f = f.strip_prefix("WHERE ").or_else(|| f.strip_prefix("where ")).unwrap_or(f);
if let Some(i) = f.find(';') {
@@ -484,12 +487,24 @@ pub fn table_page(
}
}
if !sort.is_empty() {
let keys: Vec<String> = sort
.iter()
.map(|k| format!("{}{}", quote_ident(driver, &k.column), if k.descending { " DESC" } else { "" }))
.collect();
let keys: Vec<String> =
sort.iter().map(|k| format!("{}{}", quote(&k.column), if k.descending { " DESC" } else { "" })).collect();
sql.push_str(&format!(" ORDER BY {}", keys.join(", ")));
}
sql
}
/// One page of a table: `limit + 1` rows so the caller knows whether more exist.
pub fn table_page(
driver: DbDriver,
schema: &str,
table: &str,
filter: Option<&str>,
sort: &[SortKey],
offset: u64,
limit: u64,
) -> String {
let mut sql = table_select(&qualified(driver, schema, table), filter, sort, |name| quote_ident(driver, name));
if driver == DbDriver::SqlServer {
if sort.is_empty() {
sql.push_str(" ORDER BY (SELECT 1)");
@@ -535,6 +550,9 @@ fn where_key(driver: DbDriver, key: &[CellValue]) -> String {
/// The DML statement for `edit`. Values are written as quoted literals, which
/// every supported database coerces to the column type.
pub fn edit_statement(driver: DbDriver, schema: &str, table: &str, edit: &DbRowEdit) -> Result<String, String> {
if driver == DbDriver::Jdbc {
return Err("Custom JDBC table editing is unsupported".into());
}
if driver == DbDriver::Clickhouse {
return Err("ClickHouse table editing is unsupported: primary keys do not uniquely identify rows and edits require transactions".into());
}
@@ -631,6 +649,7 @@ pub fn postgres_ddl_indexes(oid: u32) -> String {
pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
match driver {
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
DbDriver::Clickhouse => "SELECT '', '', '' WHERE 0".to_owned(),
DbDriver::Snowflake => "SELECT '', '', '' WHERE 1 = 0".to_owned(),
DbDriver::Sqlite => format!(
@@ -691,7 +710,7 @@ pub fn postgres_legacy(sql: &str) -> Option<String> {
pub fn routines(driver: DbDriver, schema: &str) -> Option<String> {
let s = quote_literal(driver, schema);
match driver {
DbDriver::Sqlite | DbDriver::Clickhouse => None,
DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc => None,
// Functions of extensions are left out, as in IDEA.
DbDriver::Postgres => Some(format!(
"SELECT p.proname, CASE WHEN p.prokind = 'p' THEN 'procedure' ELSE 'function' END, \
+215
Переглянути файл
@@ -0,0 +1,215 @@
use ide_core::{CancellationToken, IdeResult};
use ide_db::{DataSource, DbDriver, DbJdbcDriver, DbManager, SortKey};
use std::{path::Path, sync::Arc};
fn manager(dir: &Path) -> DbManager {
let ssh = Arc::new(ide_ssh::SshManager::new(dir.join("ssh.json")));
DbManager::new(dir.join("project"), dir.join("passwords.json"), dir.join("history.json"), ssh)
.with_global_sources(dir.join("global"))
}
#[tokio::test]
async fn jdbc_profiles_persist_and_project_files_cannot_start_drivers() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let jar = tmp.path().join("fixture.jar");
std::fs::write(&jar, [])?;
let db = manager(tmp.path());
db.save_jdbc_driver(DbJdbcDriver {
id: "fixture".into(),
name: "Test".into(),
jars: vec![jar.display().to_string()],
class_name: "test.Driver".into(),
url_template: "jdbc:test:".into(),
})?;
let reopened = manager(tmp.path());
assert_eq!(reopened.jdbc_drivers()?[0].class_name, "test.Driver");
let source = DataSource {
id: "local".into(),
name: "local".into(),
driver: DbDriver::Jdbc,
jdbc_driver: "fixture".into(),
url: "jdbc:test:".into(),
..Default::default()
};
reopened.save_sources(vec![source.clone()]).await?;
let denied = reopened.pool("local").await.err().expect("project JDBC requires explicit approval");
assert!(denied.message.contains("Review this project"));
let readonly = DataSource { read_only: true, ..source.clone() };
reopened.save_sources(vec![readonly]).await?;
let err = reopened.apply_edits("local", "main", "sample", &[]).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::PermissionDenied);
reopened.approve_jdbc_source(&source)?;
let mut changed = source.clone();
changed.url.push_str("changed");
reopened.save_sources(vec![changed]).await?;
assert!(reopened.pool("local").await.err().unwrap().message.contains("Review this project"));
let mut global = source;
global.global = true;
reopened.save_sources(vec![global]).await?;
assert!(reopened.remove_jdbc_driver("fixture").is_err());
reopened.save_sources(vec![]).await?;
reopened.remove_jdbc_driver("fixture")?;
assert!(manager(tmp.path()).jdbc_drivers()?.is_empty());
Ok(())
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
let jar = std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR");
assert_eq!(ide_db::jdbc_driver_classes(std::slice::from_ref(&jar))?, ["org.duckdb.DuckDBDriver"]);
db.save_jdbc_driver(DbJdbcDriver {
id: "duck".into(),
name: "DuckDB".into(),
jars: vec![jar],
class_name: "org.duckdb.DuckDBDriver".into(),
url_template: "jdbc:duckdb:".into(),
})?;
let source = DataSource {
id: "test".into(),
name: "DuckDB".into(),
driver: DbDriver::Jdbc,
global: true,
jdbc_driver: "duck".into(),
url: "jdbc:duckdb:local.duckdb".into(),
..Default::default()
};
assert!(db.test(&source, None, None).await?.to_lowercase().contains("duckdb"));
db.save_sources(vec![source]).await?;
let db = manager(tmp.path());
let c = CancellationToken::new();
db.execute("test", "create table items(id int primary key, label varchar)", 1, &c).await?;
db.execute("test", "insert into items values (1, NULL), (2, 'row')", 1, &c).await?;
assert!(db.schemas("test").await?.iter().any(|v| v == "main"));
assert!(db.tables("test", "main").await?.iter().any(|v| v.name == "items"));
let details = db.table_details("test", "main", "items").await?;
assert_eq!(details.columns.len(), 2);
let result = db.execute("test", "select id, label from items order by id", 1, &c).await?;
assert!(result.has_more);
assert_eq!(result.rows, vec![vec![Some("1".into()), None]]);
assert_eq!(result.columns[1].name, "label");
assert_eq!(db.completion("test").await?.default_schema, "main");
db.execute("test", "create temporary table session_marker as select 42 as id", 1, &c).await?;
let stop = CancellationToken::new();
let (cancelled, ()) =
tokio::join!(db.execute("test", "select sum(sin(i)) from range(1000000000) t(i)", 1, &stop), async {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
stop.cancel();
},);
assert_eq!(cancelled.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
let marker = db.execute("test", "select id from session_marker", 1, &c).await?;
assert_eq!(marker.rows, [vec![Some("42".into())]]);
let sort = [SortKey { column: "id".into(), descending: false }];
let first = db.table_page("test", "main", "items", None, &sort, 0, 1, &c).await?.result;
assert_eq!(first.rows, result.rows);
assert!(first.has_more);
let last = db.table_page("test", "main", "items", None, &sort, 1, 1, &c).await?.result;
assert_eq!(last.rows, vec![vec![Some("2".into()), Some("row".into())]]);
assert!(!last.has_more);
let past = db.table_page("test", "main", "items", None, &sort, 2, 1, &c).await?.result;
assert!(past.rows.is_empty() && !past.has_more);
db.disconnect("test").await;
let reopened = manager(tmp.path());
assert_eq!(reopened.execute("test", "select count(*) from items", 1, &c).await?.rows, [vec![Some("2".into())]]);
reopened.disconnect("test").await;
Ok(())
}
#[tokio::test]
#[ignore = "requires CLICKHOUSE_JDBC_CLASSPATH and a loopback ClickHouse fixture on CLICKHOUSE_JDBC_TEST_PORT"]
async fn clickhouse_vendor_driver_reads_catalog_and_results() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
let jars: Vec<String> =
std::env::split_paths(&std::env::var_os("CLICKHOUSE_JDBC_CLASSPATH").expect("CLICKHOUSE_JDBC_CLASSPATH"))
.map(|p| p.display().to_string())
.collect();
let classes = ide_db::jdbc_driver_classes(&jars)?;
assert_eq!(classes.first().map(String::as_str), Some("com.clickhouse.jdbc.ClickHouseDriver"));
let port: u16 = std::env::var("CLICKHOUSE_JDBC_TEST_PORT").unwrap().parse().unwrap();
db.save_jdbc_driver(DbJdbcDriver {
id: "clickhouse".into(),
name: "ClickHouse JDBC".into(),
jars,
class_name: "com.clickhouse.jdbc.ClickHouseDriver".into(),
url_template: "jdbc:clickhouse://".into(),
})?;
let source = DataSource {
id: "test".into(),
name: "ClickHouse JDBC".into(),
driver: DbDriver::Jdbc,
jdbc_driver: "clickhouse".into(),
url: format!("jdbc:clickhouse://127.0.0.1:{port}/default"),
user: "fixture".into(),
read_only: true,
..Default::default()
};
let password = "local-fixture";
assert!(db.test(&source, Some(password.into()), None).await?.contains("ClickHouse"));
db.approve_jdbc_source(&source)?;
db.save_sources(vec![source]).await?;
db.set_password("test", Some(password.into()), false).await?;
assert!(db.schemas("test").await?.iter().any(|v| v == "system"));
assert!(db.tables("test", "system").await?.iter().any(|v| v.name == "one"));
let cols = db.table_details("test", "system", "one").await?.columns;
assert!(cols.iter().any(|col| col.name == "dummy"));
let r = db.execute("test", "SELECT number FROM numbers(3) ORDER BY number", 2, &CancellationToken::new()).await?;
assert_eq!(r.rows.len(), 2);
assert!(r.has_more);
let c = CancellationToken::new();
let page = db.table_page("test", "system", "one", None, &[], 0, 1, &c).await?.result;
assert_eq!(page.rows.len(), 1);
assert!(!page.has_more);
let past = db.table_page("test", "system", "one", None, &[], 1, 1, &c).await?.result;
assert!(past.rows.is_empty() && !past.has_more);
db.disconnect("test").await;
Ok(())
}
#[tokio::test]
#[ignore = "requires JDBC_FIXTURE_JAR (java/jdbc-bridge/build.py --test --out fixture.jar) and Java 17+"]
async fn unresponsive_driver_closes_before_reconnect() -> IdeResult<()> {
use std::time::Duration;
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
let started = tmp.path().join("started");
db.save_jdbc_driver(DbJdbcDriver {
id: "fixture".into(),
name: "Fixture".into(),
jars: vec![std::env::var("JDBC_FIXTURE_JAR").unwrap()],
class_name: "ai.openidea.jdbc.SelfTest$Fixture".into(),
url_template: String::new(),
})?;
let source = DataSource {
id: "test".into(),
name: "Fixture".into(),
driver: DbDriver::Jdbc,
global: true,
read_only: true,
jdbc_driver: "fixture".into(),
url: format!("jdbc:fixture:{}", started.display()),
..Default::default()
};
db.test(&source, None, None).await?;
db.save_sources(vec![source]).await?;
let normal = CancellationToken::new();
assert!(db.execute("test", "write", 1, &normal).await.unwrap_err().message.contains("read-only"));
let stop = CancellationToken::new();
let (result, ()) = tokio::time::timeout(Duration::from_secs(12), async {
tokio::join!(db.execute("test", "ignore cancel", 1, &stop), async {
while !started.is_file() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
stop.cancel();
})
})
.await
.expect("driver cancellation must be bounded");
assert!(result.unwrap_err().message.contains("Reconnect"));
db.disconnect("test").await;
assert_eq!(db.execute("test", "after reconnect", 1, &normal).await?.affected, Some(1.0));
db.disconnect("test").await;
Ok(())
}
+15
Переглянути файл
@@ -0,0 +1,15 @@
[package]
name = "ide-flutter"
description = "Flutter devices, kept current by the `flutter daemon` protocol"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
ide-android = { path = "../ide-android" }
ide-core.workspace = true
parking_lot.workspace = true
serde_json.workspace = true
[dev-dependencies]
tempfile.workspace = true
+563
Переглянути файл
@@ -0,0 +1,563 @@
//! The devices a Flutter project can run on, from one `flutter daemon` per project window.
//!
//! The daemon speaks JSON-RPC over stdio, one bracketed message per line. After
//! `daemon.connected` it is asked for `device.enable`, which makes it report `device.added` /
//! `device.removed`, and once for `device.getDevices`, whose answer ends the "discovering" state.
//!
//! The daemon keeps running after its stdin closes, so closing the pipe does not end it: on Unix
//! a watcher in its process group ends the group once the IDE is gone, even after a crash. A
//! daemon that fails stays failed until the user restarts it.
use ide_android::AndroidDevice;
use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList};
use ide_core::process::{kill_tree, own_group, prepare, terminate_tree};
use ide_core::tool_path::{find_command, search_path_in};
use ide_core::{IdeEvent, SharedSink};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::{BTreeMap, VecDeque};
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::Arc;
use std::time::Duration;
const ENABLE: u64 = 1;
const GET_DEVICES: u64 = 2;
/// How long the daemon gets to exit on `SIGTERM`.
const KILL_GRACE: Duration = Duration::from_millis(200);
/// Lines of unrecognised output kept to explain a failure.
const OUTPUT_TAIL: usize = 8;
#[derive(Debug, PartialEq, Eq)]
enum Message {
Connected,
Added(FlutterDevice),
Removed(String),
Devices(Vec<FlutterDevice>),
Other,
}
fn device(value: &Value) -> Option<FlutterDevice> {
let text = |key| value.get(key).and_then(Value::as_str).map(str::to_owned);
Some(FlutterDevice {
id: text("id")?,
name: text("name")?,
platform_type: text("platformType"),
category: text("category"),
emulator: value.get("emulator").and_then(Value::as_bool).unwrap_or(false),
unavailable: None,
})
}
/// The messages of one stdout line; `None` for anything outside the protocol (the tool's own
/// chatter, such as waiting for the startup lock).
fn parse_line(line: &str) -> Option<Vec<Message>> {
let line = line.trim();
if !line.starts_with('[') {
return None;
}
let messages: Vec<Value> = serde_json::from_str(line).ok()?;
Some(messages.iter().map(parse_message).collect())
}
fn parse_message(message: &Value) -> Message {
let params = message.get("params").unwrap_or(&Value::Null);
match message.get("event").and_then(Value::as_str) {
Some("daemon.connected") => Message::Connected,
Some("device.added") => device(params).map_or(Message::Other, Message::Added),
Some("device.removed") => {
params.get("id").and_then(Value::as_str).map_or(Message::Other, |id| Message::Removed(id.to_owned()))
}
Some(_) => Message::Other,
None if message.get("id").and_then(Value::as_u64) == Some(GET_DEVICES) => {
let result = message.get("result").and_then(Value::as_array);
Message::Devices(result.into_iter().flatten().filter_map(device).collect())
}
None => Message::Other,
}
}
fn request(id: u64, method: &str) -> String {
format!("{}\n", json!([{ "id": id, "method": method }]))
}
/// The daemon's devices, plus the Android devices adb sees that Flutter leaves out until they
/// are usable. A daemon Android device's id is its adb serial.
fn merged(daemon: &BTreeMap<String, FlutterDevice>, adb: &[AndroidDevice]) -> Vec<FlutterDevice> {
let mut devices: Vec<FlutterDevice> = daemon.values().cloned().collect();
devices.extend(adb.iter().filter(|d| !d.is_online() && !daemon.contains_key(&d.serial)).map(|d| FlutterDevice {
id: d.serial.clone(),
name: d.label().replace('_', " "),
platform_type: Some("android".into()),
category: Some("mobile".into()),
emulator: d.serial.starts_with("emulator-"),
unavailable: Some(d.state.clone()),
}));
let rank = |d: &FlutterDevice| match d.category.as_deref() {
Some("mobile") => 0,
Some("desktop") => 1,
Some("web") => 2,
_ => 3,
};
devices.sort_by_cached_key(|d| (d.unavailable.is_some(), rank(d), d.emulator, d.name.to_lowercase(), d.id.clone()));
devices
}
struct Running {
child: Child,
stdin: Option<ChildStdin>,
}
#[derive(Default)]
struct State {
/// Bumped by every start and stop: a reader of an older process no longer has a say.
generation: u64,
running: Option<Running>,
status: FlutterDaemonStatus,
devices: BTreeMap<String, FlutterDevice>,
adb: Vec<AndroidDevice>,
}
impl State {
fn list(&self) -> FlutterDeviceList {
FlutterDeviceList { status: self.status.clone(), devices: merged(&self.devices, &self.adb) }
}
fn shut_down(&mut self) {
self.generation += 1;
if let Some(Running { mut child, stdin }) = self.running.take() {
drop(stdin);
// Off the caller's thread: closing a window must not wait for the grace period.
std::thread::spawn(move || terminate_tree(&mut child, KILL_GRACE));
}
}
}
struct Shared {
root: PathBuf,
sink: SharedSink,
/// Replaces the lookup on the search path (tests).
executable: Option<PathBuf>,
state: Mutex<State>,
}
impl Shared {
fn emit(&self, list: FlutterDeviceList) {
self.sink.emit(IdeEvent::FlutterDevices { list });
}
}
/// One project window's `flutter daemon`, started on first use.
pub struct FlutterDaemon(Arc<Shared>);
impl FlutterDaemon {
pub fn new(root: PathBuf, sink: SharedSink) -> Self {
Self::with_executable(root, sink, None)
}
fn with_executable(root: PathBuf, sink: SharedSink, executable: Option<PathBuf>) -> Self {
Self(Arc::new(Shared { root, sink, executable, state: Mutex::default() }))
}
/// The current list; starts the daemon unless it already ran. Never blocks on the process.
pub fn devices(&self) -> FlutterDeviceList {
let mut state = self.0.state.lock();
if state.status == FlutterDaemonStatus::Stopped {
start(&self.0, &mut state);
}
state.list()
}
/// Replaces the daemon with a new one (the user's way out of a failure).
pub fn restart(&self) -> FlutterDeviceList {
let mut state = self.0.state.lock();
state.shut_down();
start(&self.0, &mut state);
state.list()
}
/// Reads adb again: a device awaiting authorization changes no daemon event.
pub fn refresh(&self) {
let generation = self.0.state.lock().generation;
refresh_adb(&self.0, generation);
}
/// Ends the daemon (project closed, or no longer trusted).
pub fn stop(&self) {
let mut state = self.0.state.lock();
state.shut_down();
state.status = FlutterDaemonStatus::Stopped;
state.devices.clear();
state.adb.clear();
}
/// Ends the daemon before returning, for a process about to exit.
pub fn kill(&self) {
let mut state = self.0.state.lock();
state.generation += 1;
if let Some(mut running) = state.running.take() {
kill_tree(&mut running.child);
}
}
}
fn start(shared: &Arc<Shared>, state: &mut State) {
state.generation += 1;
state.status = FlutterDaemonStatus::Starting;
state.devices.clear();
state.adb.clear();
let (shared, generation) = (shared.clone(), state.generation);
std::thread::spawn(move || run(&shared, generation));
}
fn refresh_adb(shared: &Arc<Shared>, generation: u64) {
let shared = shared.clone();
std::thread::spawn(move || {
// Without adb there is simply nothing to add.
let adb = ide_android::devices().unwrap_or_default();
let mut state = shared.state.lock();
if state.generation != generation || state.adb == adb {
return;
}
state.adb = adb;
let list = state.list();
drop(state);
shared.emit(list);
});
}
/// `flutter daemon`, ended with its whole process group when process `parent` is gone.
#[cfg(unix)]
fn daemon_command(executable: &Path, parent: u32) -> Command {
const WATCHED: &str = r#"(while kill -0 "$1" 2>/dev/null; do sleep 5; done; kill -KILL 0) </dev/null >/dev/null 2>&1 &
exec "$2" daemon"#;
let mut cmd = Command::new("/bin/sh");
cmd.args(["-c", WATCHED, "sh"]).arg(parent.to_string()).arg(executable);
cmd
}
// No watcher on Windows, so a crashed IDE leaves the daemon; a Job Object would cover it.
#[cfg(not(unix))]
fn daemon_command(executable: &Path, _parent: u32) -> Command {
let mut cmd = Command::new(executable);
cmd.arg("daemon");
cmd
}
fn spawn_daemon(executable: &Path, root: &Path) -> std::io::Result<Child> {
let mut cmd = daemon_command(executable, std::process::id());
cmd.current_dir(root).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
prepare(own_group(&mut cmd));
cmd.spawn()
}
/// Sets the final status of a daemon that is gone, unless it was replaced or stopped meanwhile.
fn finish(shared: &Shared, generation: u64, status: FlutterDaemonStatus) {
let mut state = shared.state.lock();
if state.generation != generation {
return;
}
let running = state.running.take();
state.status = status;
let list = state.list();
drop(state);
if let Some(Running { mut child, .. }) = running {
std::thread::spawn(move || terminate_tree(&mut child, Duration::ZERO));
}
shared.emit(list);
}
fn keep_output(tail: &Mutex<VecDeque<String>>, line: &str) {
if line.trim().is_empty() {
return;
}
let mut tail = tail.lock();
if tail.len() == OUTPUT_TAIL {
tail.pop_front();
}
tail.push_back(line.trim_end().to_owned());
}
fn read_lines(pipe: impl Read, mut on_line: impl FnMut(&str) -> bool) {
let mut reader = BufReader::new(pipe);
let mut bytes = Vec::new();
loop {
bytes.clear();
match reader.read_until(b'\n', &mut bytes) {
Ok(0) | Err(_) => return,
Ok(_) if !on_line(&String::from_utf8_lossy(&bytes)) => return,
Ok(_) => {}
}
}
}
/// One daemon's whole life, on its own thread.
fn run(shared: &Arc<Shared>, generation: u64) {
let executable =
shared.executable.clone().or_else(|| find_command("flutter", &search_path_in(&shared.root), &shared.root));
let Some(executable) = executable else {
return finish(shared, generation, FlutterDaemonStatus::NotInstalled);
};
let mut child = match spawn_daemon(&executable, &shared.root) {
Ok(child) => child,
Err(e) => {
let message = format!("could not run {}: {e}", executable.display());
return finish(shared, generation, FlutterDaemonStatus::Failed { message });
}
};
let (Some(stdout), Some(stderr)) = (child.stdout.take(), child.stderr.take()) else {
return finish(shared, generation, FlutterDaemonStatus::Failed { message: "no output pipe".into() });
};
let stdin = child.stdin.take();
{
let mut state = shared.state.lock();
if state.generation != generation {
drop(state);
drop(stdin);
terminate_tree(&mut child, KILL_GRACE);
return;
}
state.running = Some(Running { child, stdin });
}
let tail = Arc::new(Mutex::new(VecDeque::new()));
let errors = {
let tail = tail.clone();
std::thread::spawn(move || {
read_lines(stderr, |line| {
keep_output(&tail, line);
true
});
})
};
read_lines(stdout, |line| match parse_line(line) {
Some(messages) => messages.into_iter().all(|message| handle(shared, generation, message)),
None => {
keep_output(&tail, line);
true
}
});
let _ = errors.join();
let message = Vec::from(std::mem::take(&mut *tail.lock())).join("\n");
let message = if message.is_empty() { "flutter daemon exited".to_owned() } else { message };
finish(shared, generation, FlutterDaemonStatus::Failed { message });
}
/// Applies one message; false once this daemon has been replaced or stopped.
fn handle(shared: &Arc<Shared>, generation: u64, message: Message) -> bool {
let mut state = shared.state.lock();
if state.generation != generation {
return false;
}
match message {
Message::Other => return true,
Message::Connected => {
if let Some(stdin) = state.running.as_mut().and_then(|r| r.stdin.as_mut()) {
let requests = request(ENABLE, "device.enable") + &request(GET_DEVICES, "device.getDevices");
let _ = stdin.write_all(requests.as_bytes()).and_then(|()| stdin.flush());
}
return true;
}
Message::Added(device) => {
state.devices.insert(device.id.clone(), device);
}
Message::Removed(id) => {
state.devices.remove(&id);
}
// Merged, not replaced: events may have overtaken this answer.
Message::Devices(devices) => {
state.devices.extend(devices.into_iter().map(|d| (d.id.clone(), d)));
state.status = FlutterDaemonStatus::Ready;
}
}
let list = state.list();
drop(state);
shared.emit(list);
refresh_adb(shared, generation);
true
}
#[cfg(test)]
mod tests {
use super::*;
fn dev(id: &str, name: &str, category: &str, emulator: bool) -> FlutterDevice {
FlutterDevice {
id: id.into(),
name: name.into(),
platform_type: None,
category: Some(category.into()),
emulator,
unavailable: None,
}
}
fn adb(serial: &str, state: &str) -> AndroidDevice {
AndroidDevice {
serial: serial.into(),
state: state.into(),
model: None,
product: None,
device: None,
transport_id: None,
}
}
#[test]
fn reads_the_daemon_protocol() {
assert_eq!(
parse_line(r#"[{"event":"daemon.connected","params":{"version":"0.6.1","pid":7}}]"#),
Some(vec![Message::Connected])
);
let added = parse_line(
r#"[{"event":"device.added","params":{"id":"emulator-5554","name":"Pixel","platform":"android-arm64",
"emulator":true,"category":"mobile","platformType":"android","ephemeral":true}}]"#
.replace('\n', " ")
.as_str(),
);
let Some([Message::Added(device)]) = added.as_deref() else { panic!("{added:?}") };
assert_eq!(device.id, "emulator-5554");
assert_eq!(device.platform_type.as_deref(), Some("android"));
assert!(device.emulator);
assert_eq!(
parse_line(r#"[{"event":"device.removed","params":{"id":"macos","name":"macOS"}}]"#),
Some(vec![Message::Removed("macos".into())])
);
let answer = parse_line(r#"[{"id":2,"result":[{"id":"chrome","name":"Chrome","category":null}]}]"#);
let Some([Message::Devices(devices)]) = answer.as_deref() else { panic!("{answer:?}") };
assert_eq!((devices[0].id.as_str(), devices[0].category.as_deref()), ("chrome", None));
assert_eq!(parse_line(r#"[{"id":1,"result":null}]"#), Some(vec![Message::Other]));
}
#[test]
fn output_outside_the_protocol_is_not_a_message() {
assert_eq!(parse_line("Waiting for another flutter command to release the startup lock..."), None);
assert_eq!(parse_line("[not json"), None);
}
#[test]
fn lists_usable_devices_first_and_adds_what_only_adb_sees() {
let daemon: BTreeMap<_, _> = [
dev("chrome", "Chrome", "web", false),
dev("macos", "macOS", "desktop", false),
dev("emulator-5554", "Pixel", "mobile", true),
dev("R5C", "Galaxy", "mobile", false),
]
.into_iter()
.map(|d| (d.id.clone(), d))
.collect();
let adb = [adb("R5C", "device"), adb("emulator-5554", "offline"), adb("X1", "unauthorized")];
let list = merged(&daemon, &adb);
let ids: Vec<_> = list.iter().map(|d| d.id.as_str()).collect();
assert_eq!(ids, ["R5C", "emulator-5554", "macos", "chrome", "X1"]);
assert_eq!(list[4].unavailable.as_deref(), Some("unauthorized"));
assert_eq!(list[1].unavailable, None, "what the daemon lists is usable");
}
#[cfg(unix)]
mod process {
use super::super::*;
use ide_core::EventSink;
use std::os::unix::fs::PermissionsExt;
use std::time::Instant;
#[derive(Default)]
struct Lists(Mutex<Vec<FlutterDeviceList>>);
impl EventSink for Lists {
fn emit(&self, event: IdeEvent) {
if let IdeEvent::FlutterDevices { list } = event {
self.0.lock().push(list);
}
}
}
fn daemon(dir: &Path, script: &str) -> (FlutterDaemon, Arc<Lists>) {
let path = dir.join("flutter");
std::fs::write(&path, format!("#!/bin/sh\n{script}")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
let lists = Arc::new(Lists::default());
(FlutterDaemon::with_executable(dir.to_owned(), lists.clone(), Some(path)), lists)
}
fn wait_for(what: &str, done: impl Fn() -> bool) {
let deadline = Instant::now() + Duration::from_secs(10);
while !done() {
assert!(Instant::now() < deadline, "timed out waiting for {what}");
std::thread::sleep(Duration::from_millis(10));
}
}
const SESSION: &str = r#"
echo $$ > pid
echo 'Waiting for another flutter command to release the startup lock...'
echo '[{"event":"daemon.connected","params":{"version":"0.6.1","pid":1}}]'
read enable; read get; echo "$enable$get" > requests
echo '[{"id":1,"result":null}]'
echo '[{"id":2,"result":[{"id":"macos","name":"macOS","category":"desktop","emulator":false}]}]'
echo '[{"event":"device.added","params":{"id":"chrome","name":"Chrome","category":"web","emulator":false}}]'
echo '[{"event":"device.removed","params":{"id":"macos","name":"macOS"}}]'
cat > /dev/null
"#;
#[test]
fn follows_devices_and_ends_with_the_project() {
let dir = tempfile::tempdir().unwrap();
let (daemon, lists) = daemon(dir.path(), SESSION);
assert_eq!(daemon.devices().status, FlutterDaemonStatus::Starting);
wait_for("the removal", || {
let list = daemon.devices();
list.status == FlutterDaemonStatus::Ready
&& list.devices.iter().map(|d| d.id.as_str()).collect::<Vec<_>>() == ["chrome"]
});
let requests = std::fs::read_to_string(dir.path().join("requests")).unwrap();
assert!(requests.contains("device.enable") && requests.contains("device.getDevices"), "{requests}");
assert!(lists.0.lock().iter().any(|l| l.devices.iter().any(|d| d.id == "macos")));
let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap();
let alive =
|| Command::new("kill").args(["-0", pid.trim()]).stderr(Stdio::null()).status().unwrap().success();
assert!(alive());
daemon.stop();
wait_for("the process to end", || !alive());
assert_eq!(daemon.0.state.lock().status, FlutterDaemonStatus::Stopped);
}
#[test]
fn the_daemon_does_not_outlive_the_ide() {
let dir = tempfile::tempdir().unwrap();
let flutter = dir.path().join("flutter");
std::fs::write(&flutter, "#!/bin/sh\necho $$ > pid\nexec sleep 60\n").unwrap();
std::fs::set_permissions(&flutter, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut ide = Command::new("sleep").arg("60").spawn().unwrap();
let mut cmd = daemon_command(&flutter, ide.id());
cmd.current_dir(dir.path()).stdin(Stdio::piped());
let mut daemon = own_group(&mut cmd).spawn().unwrap();
wait_for("the daemon", || dir.path().join("pid").is_file());
assert_eq!(daemon.try_wait().unwrap(), None);
ide.kill().unwrap();
ide.wait().unwrap();
let deadline = Instant::now() + Duration::from_secs(10);
while daemon.try_wait().unwrap().is_none() {
assert!(Instant::now() < deadline, "the daemon outlived its parent");
std::thread::sleep(Duration::from_millis(50));
}
}
#[test]
fn a_crash_is_reported_and_not_restarted_until_asked() {
let dir = tempfile::tempdir().unwrap();
let (daemon, _lists) = daemon(dir.path(), "echo run >> runs\necho 'SDK is broken' >&2\nexit 3\n");
daemon.devices();
let failed = || matches!(daemon.0.state.lock().status, FlutterDaemonStatus::Failed { .. });
wait_for("the failure", failed);
let FlutterDaemonStatus::Failed { message } = daemon.devices().status else { panic!("still failed") };
assert_eq!(message, "SDK is broken");
std::thread::sleep(Duration::from_millis(100));
let runs = || std::fs::read_to_string(dir.path().join("runs")).unwrap().lines().count();
assert_eq!(runs(), 1);
daemon.restart();
wait_for("the second run", || runs() == 2);
}
}
}
+1
Переглянути файл
@@ -58,6 +58,7 @@ ide-plugin.workspace = true
ide-tools = { path = "../ide-tools" }
ide-scaffold.workspace = true
ide-docker = { path = "../ide-docker" }
ide-flutter = { path = "../ide-flutter" }
semver = "1"
serde.workspace = true
jsonschema = { version = "0.33", default-features = false }
+19 -4
Переглянути файл
@@ -11,7 +11,12 @@ use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let raw_args: Vec<String> = std::env::args().collect();
if let Some(project) = ide_mcp::stdio_request(&raw_args) {
let base = server_home();
std::process::exit(ide_mcp::stdio::run(&ide_mcp::discovery_path(&base.join("data")), project));
}
let args: Vec<String> = raw_args.into_iter().skip(1).collect();
if args.iter().any(|a| a == "--version") {
println!("openidea-server {} (protocol {})", env!("CARGO_PKG_VERSION"), rpc::PROTOCOL_VERSION);
return;
@@ -31,7 +36,9 @@ fn main() {
std::process::exit(code);
}
if !args.iter().any(|a| a == "--stdio") {
eprintln!("usage: openidea-server --stdio | --connect <host> <port> | --version");
eprintln!(
"usage: openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <port> | --version"
);
std::process::exit(2);
}
// stdout carries the protocol: logs go to stderr.
@@ -39,8 +46,7 @@ fn main() {
.with_writer(std::io::stderr)
.with_env_filter(tracing_subscriber::EnvFilter::try_from_env("OPENIDEA_LOG").unwrap_or_else(|_| "info".into()))
.init();
let home = dirs::home_dir().unwrap_or_default();
let base = std::env::var_os("OPENIDEA_SERVER_HOME").map(PathBuf::from).unwrap_or_else(|| home.join(".openidea"));
let base = server_home();
// An SSH exec channel gets a minimal environment: take the login shell's, read
// afresh on every start, plus the IDE-managed tools. Before any other thread starts.
ide_host::shell_env::inherit_login_shell_env("openidea-server");
@@ -53,6 +59,11 @@ fn main() {
std::process::exit(code);
}
fn server_home() -> PathBuf {
let home = dirs::home_dir().unwrap_or_default();
std::env::var_os("OPENIDEA_SERVER_HOME").map(PathBuf::from).unwrap_or_else(|| home.join(".openidea"))
}
async fn run(base: PathBuf) -> i32 {
let (config_dir, data_dir) = (base.join("config"), base.join("data"));
for dir in [&config_dir, &data_dir] {
@@ -85,6 +96,9 @@ async fn run(base: PathBuf) -> i32 {
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
// A stable path for `--mcp-stdio` client configurations across server upgrades.
host.mcp.set_stdio_link(base.join("bin").join("openidea-server"));
host.mcp.apply(&host);
// The desktop's code plugins run here, next to the project (`plugin_sync_packages`).
let plugins = match RemotePlugins::start(&plugins_data, &host, peer.clone()) {
Ok(p) => Some(p),
@@ -112,6 +126,7 @@ async fn run(base: PathBuf) -> i32 {
}
});
rpc::serve(host.clone(), dispatcher, peer, tokio::io::stdin(), tokio::io::stdout()).await;
host.mcp.stop(&host);
if let Some(plugins) = &plugins {
plugins.host().shutdown();
}
+11 -4
Переглянути файл
@@ -59,7 +59,8 @@ pub struct HostConfig {
}
pub struct Host {
pub(crate) mcp_executable: RwLock<Option<PathBuf>>,
pub(crate) mcp_executable: Arc<RwLock<Option<PathBuf>>>,
pub mcp: mcp::McpService,
plugin_host: RwLock<std::sync::Weak<plugins::PluginHost>>,
/// Every `Diagnostics` event the host ever emitted, per file and producer:
/// the snapshot plugins read (`problems`), independent of windows and reports.
@@ -152,7 +153,8 @@ impl Host {
ssh.set_configs(global_settings.effective().ssh.configs);
let host = Self {
plugin_host: RwLock::default(),
mcp_executable: RwLock::default(),
mcp_executable: Arc::default(),
mcp: Default::default(),
diagnostics,
mcp_reports: Default::default(),
mcp_requests: Default::default(),
@@ -222,12 +224,12 @@ impl Host {
}
}
/// Associates the plugin runtime that executes this host's project operations.
/// Publishes only the executable of the running built-in MCP service.
/// Publishes the executable of the running built-in MCP service (`None` while it is off).
pub fn set_mcp_executable(&self, executable: Option<PathBuf>) {
*self.mcp_executable.write() = executable;
}
/// Associates the plugin runtime that executes this host's project operations.
pub fn set_plugin_host(&self, plugins: &Arc<plugins::PluginHost>) {
*self.plugin_host.write() = Arc::downgrade(plugins);
}
@@ -341,6 +343,7 @@ impl Host {
}
project.documents.clear_workspace_edit_history();
project.agents.shutdown();
project.flutter.stop();
project.notebooks.stop_admission();
// What the closing window started goes with it — the builds and searches it
// asked for, its runs, its shells and its debug sessions — and its language
@@ -459,6 +462,9 @@ impl Host {
pub fn stop_processes_on_exit(&self) {
self.processes.kill_all();
self.terminals.kill_all();
for project in self.projects() {
project.flutter.kill();
}
}
/// Called before desktop exit, which may bypass document destructors.
@@ -480,6 +486,7 @@ impl Host {
let projects: Vec<_> = self.projects.write().drain().map(|(_, p)| p).collect();
for project in &projects {
project.files_events_active.store(false, std::sync::atomic::Ordering::Release);
project.flutter.kill();
}
for project in &projects {
project.plugin_diagnostics.close();
+3 -1
Переглянути файл
@@ -11,6 +11,7 @@ mod http;
mod page;
pub mod reports;
mod search;
pub mod service;
mod symbols;
mod tool;
mod util;
@@ -22,6 +23,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};
pub use service::{McpServerStatus, McpService};
use std::path::{Path, PathBuf};
use std::sync::Arc;
@@ -55,7 +57,7 @@ fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
impl Registry {
fn target(&self, root: &Path) -> Result<(String, Arc<crate::Project>), String> {
if self.0.mcp_reports.remote_roots().iter().any(|p| p == root) {
return Err("not supported for remote projects yet".into());
return Err("project is on a remote host; connect to the MCP server on that host".into());
}
let projects = self.0.projects.read();
let open = || projects.iter().filter(|(_, p)| !p.light);
+296
Переглянути файл
@@ -0,0 +1,296 @@
//! Agents › IDE MCP Server: runs `ide_mcp::McpServer` over built-in host tools
//! while `mcpServer.enabled` is on, and reports where it listens.
use crate::Host;
use ide_command::command;
use ide_core::{IdeResult, IpcPath};
use parking_lot::{Mutex, RwLock};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::net::IpAddr;
use std::path::PathBuf;
use std::sync::Arc;
/// The server while it runs, or why it doesn't.
#[derive(Default)]
pub struct McpService {
server: Mutex<Option<ide_mcp::McpServer>>,
/// The address, port and token settings the running server was started with.
running_with: Mutex<Option<Listen>>,
error: Mutex<Option<String>>,
/// A link to this executable advertised for `--mcp-stdio` instead of `current_exe()`.
stdio_link: RwLock<Option<PathBuf>>,
}
/// What the address, port and token settings ask the server for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Listen {
/// `mcpServer.address`.
address: IpAddr,
/// `mcpServer.port` with `mcpServer.fixedPort`; otherwise a free port.
port: Option<u16>,
fixed_token: bool,
}
impl McpService {
/// Advertises `link` in `--mcp-stdio` client configs and agent sessions, pointed at this
/// executable whenever the server starts. Without one (or where it can't be written),
/// `current_exe()` is advertised.
pub fn set_stdio_link(&self, link: PathBuf) {
*self.stdio_link.write() = Some(link);
}
pub(crate) fn stdio_executable(&self) -> PathBuf {
self.stdio_link.read().clone().or_else(|| std::env::current_exe().ok()).unwrap_or_default()
}
fn update_stdio_link(&self) {
let mut link = self.stdio_link.write();
if let Some(path) = link.as_deref()
&& let Err(e) = point_at_current_exe(path)
{
tracing::warn!("MCP server: cannot link {} ({e}); advertising this executable", path.display());
*link = None;
}
}
/// Starts, stops or restarts the server to match the global `mcpServer` settings:
/// `enabled`, and the address, port and token it listens with.
pub fn apply(&self, host: &Arc<Host>) {
let settings = host.global_settings.effective().mcp_server;
let mut server = self.server.lock();
if !settings.enabled {
let was_running = server.take();
let stopped = was_running.is_some();
if let Some(running) = was_running {
running.stop();
}
*self.running_with.lock() = None;
host.set_mcp_executable(None);
*self.error.lock() = None;
drop(server);
if stopped {
for project in host.projects() {
project.agents.notify_mcp_servers_changed();
}
}
return;
}
let Ok(address) = settings.address.trim().parse::<IpAddr>() else {
let stopped = server.take().map(|running| running.stop()).is_some();
*self.running_with.lock() = None;
host.set_mcp_executable(None);
*self.error.lock() = Some(format!("the listen address `{}` is not an IP address", settings.address.trim()));
drop(server);
if stopped {
for project in host.projects() {
project.agents.notify_mcp_servers_changed();
}
}
return;
};
let wanted = Listen {
address,
port: settings.fixed_port.then_some(settings.port).filter(|p| *p != 0),
fixed_token: settings.fixed_token,
};
if server.is_some() && *self.running_with.lock() == Some(wanted) {
return;
}
// Another address, port or token: clients connect anew.
if let Some(running) = server.take() {
let held = (running.address(), running.port());
running.stop();
if let Some(port) = port_to_wait_for(held, wanted.port) {
wait_until_free(address, port);
}
}
let token = if wanted.fixed_token {
match ide_mcp::kept_token(&ide_mcp::token_path(&host.data_dir)) {
Ok(token) => Some(token),
Err(e) => {
tracing::warn!("MCP server: cannot keep the token ({e}); using a new one for this run");
None
}
}
} else {
None
};
let discovery = ide_mcp::discovery_path(&host.data_dir);
match ide_mcp::McpServer::start_with(
Arc::new(crate::mcp::Registry::new(host.clone())),
Some(discovery),
&host.runtime,
ide_mcp::ServerOptions { address: Some(address), port: wanted.port, token },
) {
Ok(started) => {
self.update_stdio_link();
host.set_mcp_executable(Some(self.stdio_executable()));
*server = Some(started);
*self.running_with.lock() = Some(wanted);
*self.error.lock() = None;
drop(server);
for project in host.projects() {
project.agents.notify_mcp_servers_changed();
}
}
Err(e) => {
tracing::warn!("MCP server: {e}");
host.set_mcp_executable(None);
*self.running_with.lock() = None;
*self.error.lock() = Some(e.to_string());
}
}
}
/// Stops the server on exit (its discovery file goes with it).
pub fn stop(&self, host: &Host) {
host.set_mcp_executable(None);
if let Some(server) = self.server.lock().take() {
server.stop();
}
*self.running_with.lock() = None;
}
}
/// Replaces the symlink `link` with one to this executable.
fn point_at_current_exe(link: &std::path::Path) -> std::io::Result<()> {
#[cfg(unix)]
{
let exe = std::env::current_exe()?;
let dir = link.parent().ok_or_else(|| std::io::Error::other("no parent directory"))?;
std::fs::create_dir_all(dir)?;
let tmp = dir.join(format!(".openidea-server.{}", std::process::id()));
let _ = std::fs::remove_file(&tmp);
std::os::unix::fs::symlink(&exe, &tmp)?;
std::fs::rename(&tmp, link).inspect_err(|_| {
let _ = std::fs::remove_file(&tmp);
})
}
#[cfg(not(unix))]
{
let _ = link;
Err(std::io::ErrorKind::Unsupported.into())
}
}
/// The port a restart listening on `wanted` waits for after stopping the server that listened
/// on `held`: only its own, at any address (`127.0.0.1` and `0.0.0.0` overlap). A port another
/// program holds (the run fell back to a free one) stays taken, and waiting for it would block
/// the window.
fn port_to_wait_for(held: (IpAddr, u16), wanted: Option<u16>) -> Option<u16> {
wanted.filter(|port| held.1 == *port)
}
/// Waits briefly for a stopped server's port to close, so the restart gets it again.
fn wait_until_free(address: IpAddr, port: u16) {
for _ in 0..100 {
if std::net::TcpListener::bind((address, port)).is_ok() {
return;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
/// What Settings › Agents › IDE MCP Server shows.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct McpServerStatus {
pub running: bool,
/// Why it isn't running though turned on.
pub error: Option<String>,
/// The address listened on (`0.0.0.0` / `::`: every address).
pub address: Option<String>,
pub port: Option<u16>,
/// Why the fixed port (`mcpServer.port`) isn't the one listened on: it was in use or
/// reserved, so a free port was taken for this run.
pub port_unavailable: Option<String>,
/// The window's project, which the URL and command below are for.
pub project: Option<IpcPath>,
/// `http://<address>:<port>/mcp?project=<root>`, with loopback for every address.
pub url: Option<String>,
/// Bearer token of `url` (changes with every run unless `mcpServer.fixedToken` is on).
pub token: Option<String>,
/// The stdio bridge: this host's executable and its arguments.
pub stdio_command: Vec<String>,
}
#[command(trust = outside_restricted)]
pub fn mcp_server_status(host: &Host, window: &str) -> IdeResult<McpServerStatus> {
let root: Option<PathBuf> = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let server = host.mcp.server.lock();
let exe = host.mcp.stdio_executable();
Ok(McpServerStatus {
running: server.is_some(),
error: host.mcp.error.lock().clone(),
address: server.as_ref().map(|s| s.address().to_string()),
port: server.as_ref().map(|s| s.port()),
port_unavailable: server.as_ref().and_then(|s| s.port_unavailable().map(str::to_owned)),
url: server.as_ref().zip(root.as_ref()).map(|(s, r)| s.url(r)),
token: server.as_ref().map(|s| s.token().to_owned()),
stdio_command: root.as_ref().map(|r| ide_mcp::stdio_command(&exe, r)).unwrap_or_default(),
project: root.map(IpcPath::from),
})
}
/// Settings › Agents › IDE MCP Server › Regenerate Token: forgets the kept token, and restarts the
/// server with a new one. Clients configured with the old token stop working.
#[command(trust = outside_restricted)]
pub fn mcp_regenerate_token(host: &Arc<Host>) -> IdeResult<()> {
match std::fs::remove_file(ide_mcp::token_path(&host.data_dir)) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
*host.mcp.running_with.lock() = None;
host.mcp.apply(host);
Ok(())
}
#[command(trust = trusted)]
pub fn mcp_ui_ready(host: &Host, window: &str, ready: bool) -> IdeResult<()> {
let window = host.owner_window(window);
host.project(window)?;
host.mcp_requests.set_ready(window, ready);
Ok(())
}
/// The user closed the Run tool window tab of an agent command (`run_command`).
#[command(trust = trusted)]
pub fn mcp_agent_run_closed(host: &Host, window: &str, name: String) -> IdeResult<()> {
let project = host.project(window)?;
host.mcp_agent_runs.closed(&project.root, &name);
Ok(())
}
#[command(trust = trusted)]
pub fn mcp_respond(host: &Host, window: &str, id: u32, allow: bool, error: Option<String>) -> IdeResult<()> {
host.mcp_requests.answer(host.owner_window(window), id, allow, error)
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::Ipv4Addr;
#[test]
fn a_restart_waits_only_for_the_port_the_stopped_server_held() {
let local = IpAddr::V4(Ipv4Addr::LOCALHOST);
let any = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
assert_eq!(port_to_wait_for((local, 64342), Some(64342)), Some(64342));
// Another address on the same port overlaps the old listener: wait for it too.
assert_eq!(port_to_wait_for((any, 64342), Some(64342)), Some(64342));
// The fixed port was taken by another program: the server ran on a free one.
assert_eq!(port_to_wait_for((local, 51234), Some(64342)), None);
assert_eq!(port_to_wait_for((local, 64342), None), None);
}
}
ide_command::domain!(
mcp:
mcp_agent_run_closed,
mcp_regenerate_token,
mcp_respond,
mcp_server_status,
mcp_ui_ready,
);
+33
Переглянути файл
@@ -24,6 +24,34 @@ pub struct StatementOutcome {
pub error: Option<String>,
}
#[command(trust = trusted)]
pub fn db_approve_jdbc_source(host: &Host, window: &str, source: DataSource) -> IdeResult<()> {
host.project(window)?.db.approve_jdbc_source(&source)
}
#[command(trust = trusted)]
pub async fn db_jdbc_driver_classes(host: &Host, window: &str, jars: Vec<String>) -> IdeResult<Vec<String>> {
host.project(window)?;
tokio::task::spawn_blocking(move || ide_db::jdbc_driver_classes(&jars))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
#[command(trust = trusted)]
pub fn db_jdbc_drivers(host: &Host, window: &str) -> IdeResult<Vec<ide_db::DbJdbcDriver>> {
host.project(window)?.db.jdbc_drivers()
}
#[command(trust = trusted)]
pub fn db_save_jdbc_driver(host: &Host, window: &str, driver: ide_db::DbJdbcDriver) -> IdeResult<()> {
host.project(window)?.db.save_jdbc_driver(driver)
}
#[command(trust = trusted)]
pub fn db_remove_jdbc_driver(host: &Host, window: &str, id: String) -> IdeResult<()> {
host.project(window)?.db.remove_jdbc_driver(&id)
}
#[command(trust = trusted)]
pub fn db_sources(host: &Host, window: &str) -> IdeResult<Vec<DataSource>> {
// The data sources configured for the project (the tree's roots).
@@ -514,6 +542,11 @@ ide_command::domain!(
db_explain,
db_finish_transaction,
db_history,
db_jdbc_driver_classes,
db_jdbc_drivers,
db_approve_jdbc_source,
db_save_jdbc_driver,
db_remove_jdbc_driver,
db_object_ddl,
db_remove_history,
db_retain_catalog,
+2 -2
Переглянути файл
@@ -357,8 +357,8 @@ pub async fn debug_send_input(host: &Host, session: DebugSessionId, text: String
host.debugger.send_input(session, &text)
}
pub async fn debug_hot_reload(host: &Host, session: DebugSessionId) -> IdeResult<()> {
host.debugger.hot_reload(session).await
pub async fn debug_hot_reload(host: &Host, session: DebugSessionId, reason: HotReloadReason) -> IdeResult<()> {
host.debugger.hot_reload(session, reason).await
}
pub async fn debug_hot_restart(host: &Host, session: DebugSessionId) -> IdeResult<()> {
+28
Переглянути файл
@@ -0,0 +1,28 @@
//! Flutter's devices. The daemon runs on the project host, where `flutter run` and the debug
//! adapter run too, so a remote project lists the devices of its remote machine.
use crate::Host;
use ide_command::command;
use ide_core::IdeResult;
use ide_core::event::FlutterDeviceList;
/// The project's Flutter devices, starting its `flutter daemon` on first use. Changes arrive as
/// `IdeEvent::FlutterDevices`.
#[command(trust = trusted)]
pub fn flutter_devices(host: &Host, window: &str) -> IdeResult<FlutterDeviceList> {
Ok(host.project(window)?.flutter.devices())
}
/// Looks at adb again, for Android devices Flutter doesn't report (awaiting authorization, offline).
#[command(trust = trusted)]
pub fn flutter_devices_refresh(host: &Host, window: &str) -> IdeResult<()> {
host.project(window)?.flutter.refresh();
Ok(())
}
/// Replaces the project's `flutter daemon`, after a failure or an SDK change.
#[command(trust = trusted)]
pub fn flutter_daemon_restart(host: &Host, window: &str) -> IdeResult<FlutterDeviceList> {
Ok(host.project(window)?.flutter.restart())
}
ide_command::domain!(flutter: flutter_devices, flutter_devices_refresh, flutter_daemon_restart);
+3
Переглянути файл
@@ -15,6 +15,7 @@ pub mod deploy;
pub mod doc;
pub mod docker;
pub mod env;
pub mod flutter;
pub mod fs;
pub mod heap;
pub mod history;
@@ -85,12 +86,14 @@ ide_command::domains!(
doc_commands: crate::ops::doc::commands,
docker: crate::ops::docker,
env: crate::ops::env,
flutter: crate::ops::flutter,
fs: crate::ops::fs,
heap: crate::ops::heap,
history: crate::ops::history,
java: crate::ops::java,
jvm_icons: crate::ops::jvm_icons,
lsp: crate::ops::lsp,
mcp: crate::mcp::service,
mcp_reports: crate::mcp::reports,
nav: crate::ops::nav,
notebook: crate::ops::notebook,
+12 -1
Переглянути файл
@@ -80,6 +80,13 @@ pub fn settings_get(host: &Host, window: &str) -> Settings {
})
}
/// Defaults plus the global layer, without any project's values: what new
/// projects (and projects without their own value) get.
#[command(trust = always)]
pub fn settings_get_global(host: &Host) -> Settings {
host.with_proxy_password(host.global_settings.effective())
}
/// The removed built-in theme id a settings file of this window still names, if any:
/// `settings_get` reports the built-in that stands in for it, so the notice about
/// a theme that moved to a plugin can address the installs it concerns.
@@ -96,13 +103,16 @@ pub fn settings_removed_theme(host: &Host, window: &str) -> Option<String> {
/// re-reads its effective settings.
#[command(trust = always, desktop_body = sync)]
pub fn settings_set(
host: &Host,
host: &Arc<Host>,
window: &str,
scope: SettingsScope,
key: String,
value: String,
) -> IdeResult<Settings> {
let applied = set_settings(host, window, scope, &key, &value)?;
if key == "mcpServer" || key.starts_with("mcpServer.") {
host.mcp.apply(host);
}
let sink = host.window_sink(window);
sink.emit(IdeEvent::SettingsChanged { key });
if let Some(root) = applied.roots_changed {
@@ -386,6 +396,7 @@ ide_command::domain!(
project_trust_set,
project_trust_status,
settings_get,
settings_get_global,
settings_removed_theme,
settings_set,
);
+1
Переглянути файл
@@ -27,6 +27,7 @@ fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
let runtime = ide_sdk::apply::tool_install_environment(&root, &settings);
let work_dir = (!root.as_os_str().is_empty()).then_some(root);
Ok(Tools::new(&data)
.with_downloads(settings.tool_downloads.clone())
.with_runtime(runtime.commands, runtime.env)
.with_custom_paths(custom)
.with_found_paths(found.into_iter().collect())
+8
Переглянути файл
@@ -61,6 +61,8 @@ pub struct Project {
pub agents: Arc<ide_agent::AgentManager>,
/// Native notebooks and owned kernels, scoped to this project incarnation.
pub notebooks: Arc<crate::notebook::NotebookService>,
/// Flutter's devices; its daemon starts when the UI first asks for them.
pub(crate) flutter: ide_flutter::FlutterDaemon,
pub(crate) kotlin_bridge: Option<Arc<crate::kotlin_bridge::KotlinBridge>>,
pub(crate) phpstan: Option<Arc<crate::phpstan::Phpstan>>,
pub(crate) watcher: Arc<Watcher>,
@@ -601,6 +603,7 @@ impl Host {
let project = Arc::new(Project {
plugin_diagnostics,
trusted,
flutter: ide_flutter::FlutterDaemon::new(root.clone(), sink.clone()),
root,
sink,
languages,
@@ -731,6 +734,10 @@ impl Host {
agents.set_mcp_servers_hook(Box::new(move || {
crate::ops::agent::session_mcp_servers(&settings, &approvals, &secrets, &root)
}));
{
let mcp_executable = self.mcp_executable.clone();
agents.set_mcp_executable_hook(Box::new(move || mcp_executable.read().clone()));
}
(db, http_history, agents)
}
}
@@ -809,6 +816,7 @@ impl Host {
let project = Arc::new(Project {
plugin_diagnostics,
trusted: Arc::new(AtomicBool::new(false)),
flutter: ide_flutter::FlutterDaemon::new(dir.clone(), sink.clone()),
sink,
languages,
settings,
+24 -9
Переглянути файл
@@ -171,20 +171,21 @@ pub fn event_sink(peer: Arc<OnceLock<Peer>>, window: Option<String>) -> ide_core
}
/// Whether a desktop shows an `event` notification of its server in the window. A server reports
/// on its project; what this machine answers or owns itself (MCP approvals, app updates, window
/// groups, its own connection to the server) never comes from it.
pub fn client_accepts(event: &IdeEvent) -> bool {
/// on its project; what this machine owns itself (app updates, window groups, its own connection
/// to the server) never comes from it, and MCP UI requests are accepted only when this machine
/// trusts the remote project (their answers route back to the server, never locally).
pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
match event {
IdeEvent::McpRequest { .. }
| IdeEvent::McpRequestClosed { .. }
| IdeEvent::WindowGroupsChanged
IdeEvent::WindowGroupsChanged
| IdeEvent::WindowFullscreenChanged
| IdeEvent::RemoteConnectionLost { .. }
| IdeEvent::UpdateStatusChanged { .. }
| IdeEvent::UpdateAvailable { .. } => false,
IdeEvent::McpRequest { .. } | IdeEvent::McpRequestClosed { .. } => trusted,
IdeEvent::DbSourcesChanged
| IdeEvent::ProjectTrustChanged { .. }
| IdeEvent::Direnv { .. }
| IdeEvent::FlutterDevices { .. }
| IdeEvent::FsChanged { .. }
| IdeEvent::ExcludedDirsChanged { .. }
| IdeEvent::DocPatched { .. }
@@ -301,8 +302,21 @@ mod tests {
date: None,
};
for event in [
IdeEvent::McpRequest { id: 1, request: confirm },
IdeEvent::McpRequest { id: 1, request: confirm.clone() },
IdeEvent::McpRequestClosed { id: 1 },
IdeEvent::UpdateAvailable { update: update.clone() },
IdeEvent::UpdateStatusChanged {
status: ide_core::updates::UpdateStatus { last_checked: None, checking: true },
},
IdeEvent::WindowGroupsChanged,
IdeEvent::WindowFullscreenChanged,
] {
assert!(!client_accepts(&event, false), "{event:?}");
}
// Even for a trusted remote project, desktop-owned events stay blocked while remote MCP prompts pass.
assert!(client_accepts(&IdeEvent::McpRequest { id: 1, request: confirm }, true));
assert!(client_accepts(&IdeEvent::McpRequestClosed { id: 1 }, true));
for event in [
IdeEvent::UpdateAvailable { update },
IdeEvent::UpdateStatusChanged {
status: ide_core::updates::UpdateStatus { last_checked: None, checking: true },
@@ -310,7 +324,7 @@ mod tests {
IdeEvent::WindowGroupsChanged,
IdeEvent::WindowFullscreenChanged,
] {
assert!(!client_accepts(&event), "{event:?}");
assert!(!client_accepts(&event, true), "{event:?}");
}
}
@@ -328,7 +342,8 @@ mod tests {
IdeEvent::Askpass { id: 1, prompt: "Password".into(), kind: AskpassKind::Secret, remember: false },
IdeEvent::ProjectTrustChanged { root: "/srv/app".into(), trusted: true },
] {
assert!(client_accepts(&event), "{event:?}");
assert!(client_accepts(&event, false), "{event:?}");
assert!(client_accepts(&event, true), "{event:?}");
}
}
}
+1
Переглянути файл
@@ -282,6 +282,7 @@ impl crate::Host {
self.environment.project_closed();
self.environment.direnv_closed(&project.root);
project.agents.shutdown();
project.flutter.stop();
self.processes.kill_project(&project.root);
project.notebooks.restrict().await;
let windows: Vec<_> = self
+4 -1
Переглянути файл
@@ -185,7 +185,10 @@ async fn restricted_projects_have_only_read_tools_and_remote_projects_explain_th
assert!(registry.tools(&h.root).unwrap().iter().all(|t| t.read_only && !t.destructive));
assert!(!h.host.global_settings.effective().mcp_server.enabled);
h.host.mcp_reports.set_remote("remote", PathBuf::from("/remote/project"));
assert_eq!(registry.tools(Path::new("/remote/project")).unwrap_err(), "not supported for remote projects yet");
assert_eq!(
registry.tools(Path::new("/remote/project")).unwrap_err(),
"project is on a remote host; connect to the MCP server on that host"
);
h.host.close_project_detached("remote");
assert!(!registry.projects().contains(&PathBuf::from("/remote/project")));
}
+128
Переглянути файл
@@ -522,3 +522,131 @@ async fn renames_a_branch_with_the_clients_argument_names() {
invoke(&peer, "close_project", json!({})).await.unwrap();
peer.kill();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn serves_builtin_mcp_over_remote_dispatch_and_routes_ui_requests() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("remote-mcp");
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(root.join("src/hello.txt"), "from remote mcp\n").unwrap();
let root = dunce::canonicalize(root).unwrap();
let base = tmp.path().join("server");
let data_dir = base.join("data");
let peer_slot = Arc::new(OnceLock::new());
let sink_peer = peer_slot.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: data_dir.clone(),
local_data_dir: data_dir.clone(),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(move |w| rpc::event_sink(sink_peer.clone(), Some(w.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
let server_exe = base.join("bin/openidea-server");
host.mcp.set_stdio_link(server_exe.clone());
host.mcp.apply(&host);
let (client_io, server_io) = tokio::io::duplex(1 << 20);
let (sr, sw) = tokio::io::split(server_io);
let serve_host = host.clone();
tokio::spawn(rpc::serve(serve_host, Dispatcher::standard(), peer_slot, sr, sw));
let (cr, cw) = tokio::io::split(client_io);
let client = Arc::new(Client::default());
let peer = Peer::connect(cr, cw, client.clone());
invoke(&peer, "open_project", json!({ "path": root })).await.unwrap();
for cmd in ["mcp_server_status", "mcp_regenerate_token", "mcp_ui_ready", "mcp_respond", "mcp_agent_run_closed"] {
let err = invoke(&peer, cmd, json!({})).await.unwrap_err();
assert!(err.message.contains("Restricted Mode"), "{cmd}: {err:?}");
}
invoke(&peer, "project_trust_set", json!({ "path": root, "trusted": true, "folder": false })).await.unwrap();
let initial = invoke(&peer, "mcp_server_status", json!({})).await.unwrap();
assert_eq!(initial["running"], false);
assert!(!server_exe.exists(), "the stdio link is written only once the server runs");
invoke(&peer, "settings_set", json!({ "scope": "global", "key": "mcpServer.fixedPort", "value": "false" }))
.await
.unwrap();
invoke(&peer, "settings_set", json!({ "scope": "global", "key": "mcpServer.fixedToken", "value": "true" }))
.await
.unwrap();
invoke(&peer, "settings_set", json!({ "scope": "global", "key": "mcpServer.enabled", "value": "true" }))
.await
.unwrap();
let global = invoke(&peer, "settings_get_global", json!({})).await.unwrap();
assert_eq!(global["mcpServer"]["enabled"], true);
let status = invoke(&peer, "mcp_server_status", json!({})).await.unwrap();
assert_eq!(status["running"], true);
assert_eq!(status["project"], json!(ide_core::IpcPath::from(&root)));
#[cfg(unix)]
{
assert_eq!(status["stdioCommand"][0], server_exe.to_string_lossy().as_ref());
assert_eq!(std::fs::read_link(&server_exe).unwrap(), std::env::current_exe().unwrap());
}
let first_token = status["token"].as_str().unwrap().to_owned();
assert!(status["url"].as_str().unwrap().starts_with("http://127.0.0.1:"));
invoke(&peer, "mcp_ui_ready", json!({ "ready": true })).await.unwrap();
let discovery = ide_mcp::discovery_path(&data_dir);
let read_call = json!({
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": { "name": "read_file", "arguments": { "file_path": "src/hello.txt" } }
});
let mut out = Vec::new();
ide_mcp::stdio::bridge(&discovery, &root, format!("{read_call}\n").as_bytes(), &mut out).await.unwrap();
let reply: Value = serde_json::from_slice(&out).unwrap();
assert_eq!(reply["result"]["content"][0]["text"], "L1: from remote mcp\nL2: ");
// UI-bound MCP requests stream over RPC events and are answered via routed `mcp_respond`.
let open_call = json!({
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": { "name": "open_file_in_editor", "arguments": { "filePath": "src/hello.txt", "line": 1, "column": 1 } }
});
let (disc2, root2) = (discovery.clone(), root.clone());
let call_task = tokio::spawn(async move {
let mut out = Vec::new();
ide_mcp::stdio::bridge(&disc2, &root2, format!("{open_call}\n").as_bytes(), &mut out).await.unwrap();
serde_json::from_slice::<Value>(&out).unwrap()
});
until("remote MCP UI request", || {
client.events.lock().iter().any(|m| matches!(m.event, ide_core::IdeEvent::McpRequest { .. }))
})
.await;
let req_id = client
.events
.lock()
.iter()
.find_map(|m| match &m.event {
event @ ide_core::IdeEvent::McpRequest { id, .. } => {
assert!(!rpc::client_accepts(event, false));
assert!(rpc::client_accepts(event, true));
Some(*id)
}
_ => None,
})
.unwrap();
invoke(&peer, "mcp_respond", json!({ "id": req_id, "allow": true, "error": null })).await.unwrap();
let opened = call_task.await.unwrap();
assert_eq!(opened["result"]["isError"], false, "{opened}");
invoke(&peer, "mcp_regenerate_token", json!({})).await.unwrap();
let rotated = invoke(&peer, "mcp_server_status", json!({})).await.unwrap();
assert_eq!(rotated["running"], true);
assert_ne!(rotated["token"].as_str().unwrap(), first_token);
host.mcp.stop(&host);
invoke(&peer, "close_project", json!({})).await.unwrap();
peer.kill();
}
+81 -3
Переглянути файл
@@ -61,18 +61,96 @@ impl Discovery {
serde_json::from_slice(&bytes).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}
/// Writes the file atomically, readable only by the user.
/// Writes the file atomically, readable only by the user, and records a per-server
/// entry alongside it so multiple `openidea-server` processes sharing one data
/// directory remain discoverable by project.
pub fn write(&self, path: &Path) -> io::Result<()> {
let bytes = serde_json::to_vec_pretty(self).map_err(io::Error::other)?;
write_atomic(path, &bytes)
write_atomic(path, &bytes)?;
if let Some(entry) = server_entry_path(path, self.pid, self.port) {
let _ = write_atomic(&entry, &bytes);
}
// Entries of servers that ended without removing theirs (a crash) go now, so bridges
// stop trying them.
for (file, other) in sibling_entry_files(path) {
if (other.pid, other.port) != (self.pid, self.port) && !other.listening() {
let _ = std::fs::remove_file(file);
}
}
Ok(())
}
fn listening(&self) -> bool {
let addr = std::net::SocketAddr::new(self.address, self.port);
std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(50)).is_ok()
}
/// Removes the file at `path` if it still describes this process's server.
pub fn remove_if_ours(path: &Path) {
if Self::read(path).is_ok_and(|d| d.pid == std::process::id()) {
if let Ok(d) = Self::read(path)
&& d.pid == std::process::id()
{
Self::remove_server(path, d.port);
}
}
/// Removes this server's entry and updates `path` to another live entry when one exists.
pub fn remove_server(path: &Path, port: u16) {
let pid = std::process::id();
if let Some(entry) = server_entry_path(path, pid, port) {
let _ = std::fs::remove_file(entry);
}
if Self::read(path).is_ok_and(|d| d.pid == pid && d.port == port) {
for (file, other) in sibling_entry_files(path) {
if other.pid == pid && other.port == port {
continue;
}
if other.listening() {
if let Ok(bytes) = serde_json::to_vec_pretty(&other)
&& write_atomic(path, &bytes).is_ok()
{
return;
}
} else {
let _ = std::fs::remove_file(file);
}
}
let _ = std::fs::remove_file(path);
}
}
/// Running server entries recorded for `path`, starting with `path` itself.
pub fn candidates(path: &Path) -> Vec<Self> {
let mut out = Vec::new();
if let Ok(primary) = Self::read(path) {
out.push(primary);
}
for (_, item) in sibling_entry_files(path) {
if !out.iter().any(|d| d.address == item.address && d.port == item.port) {
out.push(item);
}
}
out
}
}
fn servers_dir(path: &Path) -> Option<PathBuf> {
path.parent().map(|dir| dir.join("servers"))
}
fn server_entry_path(path: &Path, pid: u32, port: u16) -> Option<PathBuf> {
servers_dir(path).map(|dir| dir.join(format!("{pid}-{port}.json")))
}
fn sibling_entry_files(path: &Path) -> Vec<(PathBuf, Discovery)> {
let Some(dir) = servers_dir(path) else { return Vec::new() };
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
let mut files: Vec<PathBuf> = entries
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().is_some_and(|ext| ext == "json"))
.collect();
files.sort();
files.into_iter().filter_map(|p| Discovery::read(&p).ok().map(|d| (p, d))).collect()
}
/// Writes `bytes` to `path` atomically, readable only by the user.
+1 -1
Переглянути файл
@@ -185,7 +185,7 @@ impl Drop for McpServer {
self.cancel.cancel();
let _ = self.shutdown.send(true);
if let Some(path) = &self.discovery {
Discovery::remove_if_ours(path);
Discovery::remove_server(path, self.port);
}
}
}
+113 -8
Переглянути файл
@@ -9,9 +9,19 @@ use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::{Request, StatusCode, header};
use serde_json::Value;
use std::collections::HashSet;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt};
#[derive(Default)]
struct BridgeState {
preferred: Option<SocketAddr>,
init_message: Option<Value>,
initialized_on: HashSet<SocketAddr>,
}
/// Runs the bridge on this process's stdin and stdout until stdin closes.
/// `project` defaults to the current directory. Returns the exit code.
pub fn run(discovery: &Path, project: Option<PathBuf>) -> i32 {
@@ -43,6 +53,7 @@ where
W: AsyncWrite + Unpin,
{
let scope = crate::server::new_token()?;
let state = Arc::new(Mutex::new(BridgeState::default()));
let mut lines = input.lines();
let mut pending = tokio::task::JoinSet::new();
let (sent, mut received) = tokio::sync::mpsc::unbounded_channel::<Value>();
@@ -57,10 +68,13 @@ where
if line.trim().is_empty() { continue; }
match serde_json::from_str::<Value>(&line) {
Ok(message) => {
let (discovery, project, scope, sent) =
(discovery.to_owned(), project.to_owned(), scope.clone(), sent.clone());
if is_initialize(&message) {
state.lock().unwrap().init_message = Some(message.clone());
}
let (discovery, project, scope, sent, state) =
(discovery.to_owned(), project.to_owned(), scope.clone(), sent.clone(), state.clone());
pending.spawn(async move {
if let Some(reply) = relay(&discovery, &project, &message, &scope, &sent).await {
if let Some(reply) = relay(&discovery, &project, &message, &scope, &sent, &state).await {
let _ = sent.send(reply);
}
});
@@ -86,6 +100,10 @@ where
Ok(())
}
fn is_initialize(message: &Value) -> bool {
message.get("method").and_then(Value::as_str) == Some("initialize")
}
/// The IDE's answer to `message`, or an error response for each request in
/// it when the IDE can't be reached. An answer on an event stream goes to `sent`
/// with the messages before it.
@@ -95,8 +113,9 @@ async fn relay(
message: &Value,
scope: &str,
sent: &tokio::sync::mpsc::UnboundedSender<Value>,
state: &Mutex<BridgeState>,
) -> Option<Value> {
let failure = match post(discovery, project, message, scope, sent).await {
let failure = match post(discovery, project, message, scope, sent, state).await {
Ok(Answer::Streamed { answered: true }) => return None,
Ok(Answer::Streamed { answered: false }) => "OpenIDEA's answer ended early".to_owned(),
Ok(Answer::Body(StatusCode::ACCEPTED, _)) => return None,
@@ -132,14 +151,101 @@ enum Answer {
},
}
/// POSTs `message` to the server in the discovery file; a message for the
/// user when that fails.
/// POSTs `message` to the server in the discovery file; when several servers share a data
/// directory (multiple remote windows on one host), picks the one where `project` is open.
async fn post(
discovery: &Path,
project: &Path,
message: &Value,
scope: &str,
sent: &tokio::sync::mpsc::UnboundedSender<Value>,
state: &Mutex<BridgeState>,
) -> Result<Answer, String> {
let not_running = || {
format!(
"OpenIDEA's MCP server is not running. Start OpenIDEA, open {} in it, and turn on Settings › Agents › MCP Server",
project.display()
)
};
let mut candidates = Discovery::candidates(discovery);
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)
{
let chosen = candidates.remove(pos);
candidates.insert(0, chosen);
}
let initializing = is_initialize(message);
let mut fallback: Option<(SocketAddr, 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);
if !initializing {
let init = {
let guard = state.lock().unwrap();
(!guard.initialized_on.contains(&at)).then(|| guard.init_message.clone()).flatten()
};
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}__")));
}
if post_one(&info, project, &init_msg, scope, sent).await.is_ok() {
state.lock().unwrap().initialized_on.insert(at);
}
}
}
match post_one(&info, project, message, scope, sent).await {
Ok(answer) => {
if initializing {
state.lock().unwrap().initialized_on.insert(at);
if total > 1 && !serves_project(&info, project, scope).await {
fallback.get_or_insert((at, answer));
continue;
}
} else if idx + 1 < total && is_not_open_reply(&answer) {
fallback = Some((at, answer));
continue;
}
state.lock().unwrap().preferred = Some(at);
return Ok(answer);
}
Err(err) => last_error = Some(err),
}
}
if let Some((at, answer)) = fallback {
state.lock().unwrap().preferred = Some(at);
return Ok(answer);
}
Err(last_error.unwrap_or_else(not_running))
}
/// 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 is_not_open_reply(answer: &Answer) -> bool {
let Answer::Body(StatusCode::OK, body) = answer else { return false };
serde_json::from_slice::<Value>(body)
.ok()
.and_then(|v| v.pointer("/error/code").and_then(Value::as_i64))
.is_some_and(|code| code == NOT_OPEN)
}
async fn post_one(
info: &Discovery,
project: &Path,
message: &Value,
scope: &str,
sent: &tokio::sync::mpsc::UnboundedSender<Value>,
) -> Result<Answer, String> {
let not_running = || {
format!(
@@ -147,8 +253,7 @@ async fn post(
project.display()
)
};
let info = Discovery::read(discovery).map_err(|_| not_running())?;
let at = std::net::SocketAddr::new(info.address, info.port);
let at = SocketAddr::new(info.address, info.port);
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
+49
Переглянути файл
@@ -424,3 +424,52 @@ async fn another_listen_address_is_used_and_one_not_on_this_computer_fails() {
let error = McpServer::start_with(registry, None, &runtime, elsewhere).err().expect("no such address here");
assert!(error.to_string().contains("192.0.2.1"), "{error}");
}
#[tokio::test(flavor = "multi_thread")]
async fn multiple_servers_sharing_app_data_route_by_project_and_survive_one_closing() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let (proj_a, proj_b) = (base.join("proj-a"), base.join("proj-b"));
std::fs::create_dir_all(&proj_a).unwrap();
std::fs::create_dir_all(&proj_b).unwrap();
let discovery = discovery_path(&base.join("app-data"));
let runtime = tokio::runtime::Handle::current();
let server_a =
McpServer::start(Arc::new(Registry { project: proj_a.clone() }), Some(discovery.clone()), &runtime).unwrap();
let server_b =
McpServer::start(Arc::new(Registry { project: proj_b.clone() }), Some(discovery.clone()), &runtime).unwrap();
let session = |text: &str| {
[
json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-06-18", "clientInfo": { "name": "agent", "version": "1" } } }),
json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "echo", "arguments": { "text": text } } }),
]
.iter()
.map(|m| format!("{m}\n"))
.collect::<String>()
};
for (proj, tag) in [(&proj_a, "alpha"), (&proj_b, "beta")] {
let mut out = Vec::new();
stdio::bridge(&discovery, proj, session(tag).as_bytes(), &mut out).await.unwrap();
let mut replies: Vec<Value> =
String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
replies.sort_by_key(|r| r["id"].as_i64());
assert!(replies[0]["result"]["instructions"].as_str().unwrap().contains(&proj.display().to_string()));
assert_eq!(replies[1]["result"]["content"][0]["text"], format!("{tag} in {}", proj.display()));
}
// Closing the newer server promotes the remaining server back to server.json.
server_b.stop();
assert_eq!(Discovery::read(&discovery).unwrap().port, server_a.port());
let mut out = Vec::new();
stdio::bridge(&discovery, &proj_a, session("still-here").as_bytes(), &mut out).await.unwrap();
let mut replies: Vec<Value> =
String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
replies.sort_by_key(|r| r["id"].as_i64());
assert_eq!(replies[1]["result"]["content"][0]["text"], format!("still-here in {}", proj_a.display()));
server_a.stop();
assert!(!discovery.exists());
}
+12
Переглянути файл
@@ -88,6 +88,7 @@ pub(crate) fn detect_with_profiles(
detect_projects(root, &["Makefile", "makefile", "GNUmakefile"], detect_make, &mut out);
detect_projects(root, &["justfile", "Justfile", ".justfile"], detect_just, &mut out);
detect_godot(root, &mut out);
detect_projects(root, &["pubspec.yaml"], detect_flutter, &mut out);
crate::external::detect(root, &mut out);
let mut seen = HashSet::new();
@@ -1545,6 +1546,17 @@ fn detect_godot(root: &Path, out: &mut Vec<RunConfig>) {
}
}
/// A Flutter app: depends on the SDK and has the conventional entry point (packages have none).
fn detect_flutter(root: &Path, out: &mut Vec<RunConfig>) {
if root.join("lib/main.dart").is_file()
&& read(&root.join("pubspec.yaml")).is_some_and(|pubspec| pubspec.contains("sdk: flutter"))
{
out.push(
config("flutter:run", "flutter run", "flutter", "flutter", &["run", "-t", "lib/main.dart"]).debug("dart"),
);
}
}
fn detect_just(root: &Path, out: &mut Vec<RunConfig>) {
let Some(path) = first_existing(root, &["justfile", "Justfile", ".justfile"]) else { return };
let Some(src) = read(&path) else { return };
+14
Переглянути файл
@@ -627,6 +627,20 @@ fn godot_projects_run_their_main_scene() {
assert!(detect(project(&[("main.gd", "extends Node\n")]).path()).is_empty());
}
#[test]
fn flutter_apps_run_their_entry_point() {
let pubspec = "name: app\ndependencies:\n flutter:\n sdk: flutter\n";
let dir = project(&[("pubspec.yaml", pubspec), ("lib/main.dart", "void main() {}\n")]);
let c = detect(dir.path());
let app = find(&c, "flutter:run");
assert_eq!(app.kind, "flutter");
assert_eq!(cmdline(app), "flutter run -t lib/main.dart");
assert_eq!(app.debug_adapter.as_deref(), Some("dart"));
// A Flutter package has no app to start, and a Dart package no Flutter.
assert!(detect(project(&[("pubspec.yaml", pubspec), ("lib/widgets.dart", "")]).path()).is_empty());
assert!(detect(project(&[("pubspec.yaml", "name: tool\n"), ("lib/main.dart", "")]).path()).is_empty());
}
#[test]
fn just_recipes() {
let justfile = "\
+8 -2
Переглянути файл
@@ -1187,13 +1187,19 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
for (key, value) in module_env {
build["env"][key] = json!(value);
}
if s.languages.go.gofumpt {
build["gofumpt"] = json!(true);
}
let mut settings = cfg.settings.take().unwrap_or_else(|| json!({}));
// gopls retains omitted keys on reconfiguration. Explicit empty values
// restore defaults when the last project constraint is cleared.
// Settings › Language Servers options are merged later, so look at them too.
let init = cfg.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok());
for (key, default) in [("buildFlags", json!([])), ("env", json!({}))] {
let user_init = s.language_servers.get(&cfg.name).and_then(|ls| ls.initialization_options.as_ref());
for (key, default) in [("buildFlags", json!([])), ("env", json!({})), ("gofumpt", json!(false))] {
if settings.get(key).is_none() {
settings[key] = init.as_ref().and_then(|v| v.get(key)).cloned().unwrap_or(default);
let explicit = user_init.and_then(|v| v.get(key)).or_else(|| init.as_ref()?.get(key));
settings[key] = explicit.cloned().unwrap_or(default);
}
}
merge(&mut settings, build);
+25
Переглянути файл
@@ -86,6 +86,11 @@ pub(crate) fn java_runs(java: &Path) -> bool {
runnable
}
/// First runnable Java installation in discovery order, including standalone JREs.
pub fn java_runtime(jdks: &[Jdk], min_java: u32) -> Option<&Jdk> {
jdks.iter().find(|j| j.major >= min_java && java_runs(&java_executable(&j.home)))
}
fn project_jdk_is_usable(jdk: &Jdk) -> bool {
jdk.home.join("bin").join(crate::exe("javac")).is_file()
&& (jdk.major < 9 || ide_core::java_runtime::supports_java_bundles(&jdk.home))
@@ -748,6 +753,16 @@ pub(crate) fn write_test_java(home: &Path) {
mod tests {
use super::*;
#[test]
fn java_runtime_accepts_a_jre_without_a_compiler() {
let tmp = tempfile::tempdir().unwrap();
let jre = test_jdk(tmp.path(), 17, "jre");
std::fs::remove_file(jre.home.join("bin").join(crate::exe("javac"))).unwrap();
let jdks = [test_jdk(tmp.path(), 11, "old"), jre.clone()];
assert_eq!(java_runtime(&jdks, 17), Some(&jre));
assert_eq!(java_runtime(&jdks, 21), None);
}
fn test_jdk(root: &Path, major: u32, name: &str) -> Jdk {
let home = root.join(name.trim_start_matches('/'));
std::fs::create_dir_all(home.join("bin")).unwrap();
@@ -1619,6 +1634,16 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
)
}
/// Extracts the JDBC bridge into the application's data directory.
pub fn jdbc_bridge_jar(data_dir: &Path) -> Option<PathBuf> {
install_bundle(
data_dir,
"jdbc-bridge",
"1.0.0",
include_bytes!("../../../java/jdbc-bridge/openidea-jdbc-bridge.jar"),
)
}
/// Installs the app-owned JDT LS bundle that inspects java-debug's JVMs.
pub fn jvm_inspect_bundle(data_dir: &Path) -> Option<PathBuf> {
install_bundle(
+49 -5
Переглянути файл
@@ -2452,7 +2452,10 @@ fn go_constraints_change_only_protocol_settings() {
original.settings = Some(json!({"analyses":{"unusedparams":true}}));
let mut defaults = original.clone();
configure_server(&mut defaults, tmp.path(), tmp.path(), &settings);
assert_eq!(defaults.settings, Some(json!({"analyses":{"unusedparams":true}, "buildFlags":[], "env":{}})));
assert_eq!(
defaults.settings,
Some(json!({"analyses":{"unusedparams":true}, "buildFlags":[], "env":{}, "gofumpt":false}))
);
defaults.settings = original.settings.clone();
assert_eq!(defaults, original);
settings.languages.go.build_tags.custom = "integration".into();
@@ -2462,7 +2465,8 @@ fn go_constraints_change_only_protocol_settings() {
assert_eq!(
configured.settings.take(),
Some(json!({
"analyses":{"unusedparams":true}, "buildFlags":["-tags=integration"], "env":{"GOOS":"linux"}
"analyses":{"unusedparams":true}, "buildFlags":["-tags=integration"], "env":{"GOOS":"linux"},
"gofumpt":false
}))
);
configured.settings = original.settings.clone();
@@ -2477,10 +2481,50 @@ fn go_empty_constraints_preserve_explicit_server_defaults() {
use serde_json::json;
let tmp = tempfile::tempdir().unwrap();
let mut cfg = server("gopls");
cfg.initialization_options =
Some(toml::Value::try_from(json!({"buildFlags":["-tags=legacy"], "env":{"GOPROXY":"direct"}})).unwrap());
cfg.initialization_options = Some(
toml::Value::try_from(json!({"buildFlags":["-tags=legacy"], "env":{"GOPROXY":"direct"}, "gofumpt":true}))
.unwrap(),
);
configure_server(&mut cfg, tmp.path(), tmp.path(), &Settings::default());
assert_eq!(cfg.settings, Some(json!({"buildFlags":["-tags=legacy"], "env":{"GOPROXY":"direct"}})));
assert_eq!(cfg.settings, Some(json!({"buildFlags":["-tags=legacy"], "env":{"GOPROXY":"direct"}, "gofumpt":true})));
}
#[test]
fn go_gofumpt_setting_reaches_gopls_and_turns_off_in_place() {
use crate::apply::server_protocol_overrides;
use serde_json::json;
let tmp = tempfile::tempdir().unwrap();
let mut settings = Settings::default();
settings.languages.go.gofumpt = true;
let mut on = server("gopls");
configure_server(&mut on, tmp.path(), tmp.path(), &settings);
assert_eq!(on.settings.as_ref().unwrap()["gofumpt"], json!(true));
assert_eq!(on.initialization_options, server("gopls").initialization_options);
// The setting wins over the language definition's value.
let mut explicit = server("gopls");
explicit.settings = Some(json!({"gofumpt": false}));
configure_server(&mut explicit, tmp.path(), tmp.path(), &settings);
assert_eq!(explicit.settings.unwrap()["gofumpt"], json!(true));
// Turned off: an explicit false, because gopls keeps omitted keys on reconfiguration.
let mut off = server("gopls");
configure_server(&mut off, tmp.path(), tmp.path(), &Settings::default());
assert_eq!(off.settings.unwrap()["gofumpt"], json!(false));
// Off leaves a server-level value alone.
let mut own = server("gopls");
own.settings = Some(json!({"gofumpt": true}));
configure_server(&mut own, tmp.path(), tmp.path(), &Settings::default());
assert_eq!(own.settings.unwrap()["gofumpt"], json!(true));
// Off doesn't shadow gofumpt in Settings › Language Servers initializationOptions.
let mut user = Settings::default();
user.language_servers
.insert("gopls".into(), serde_json::from_value(json!({"initializationOptions": {"gofumpt": true}})).unwrap());
let mut from_user = server("gopls");
configure_server(&mut from_user, tmp.path(), tmp.path(), &user);
server_protocol_overrides(&mut from_user, &user);
assert_eq!(from_user.settings.unwrap()["gofumpt"], json!(true));
let mut other = server("rust-analyzer");
configure_server(&mut other, tmp.path(), tmp.path(), &settings);
assert_eq!(other.settings, None);
}
#[test]
+1 -1
Переглянути файл
@@ -317,7 +317,7 @@ impl Tools {
let _ = std::fs::remove_dir_all(&staging);
std::fs::create_dir_all(&staging)?;
let result = (|| {
let archive = fetch_verified(&http, &dl, &staging, cancel, emit)?;
let archive = fetch_verified(&self.downloads, &http, &dl, &staging, cancel, emit)?;
emit(InstallEvent::Line { text: "Extracting…".into() });
let pkg = staging.join("pkg");
archive::extract(&archive, archive::ArchiveKind::from_name(&dl.name), &pkg, "java", cancel)?;
+101 -26
Переглянути файл
@@ -19,6 +19,7 @@ pub mod archive;
mod bundled;
pub mod formatter;
pub mod jdk;
pub mod mirror;
mod moved_venv;
pub mod platform;
#[cfg(any(windows, test))]
@@ -29,6 +30,7 @@ pub mod server;
pub mod sources;
use ide_core::error::ErrorKind;
use ide_core::settings::ToolDownloadSettings;
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_language::LanguageConfig;
use parking_lot::Mutex;
@@ -468,6 +470,8 @@ pub struct Tools {
/// The project the tools are used for: tools that install into "the active runtime" (gems) run here,
/// so a version manager picks the project's Ruby.
work_dir: Option<PathBuf>,
/// Tools › Download sources: the mirror prefix and its fallback behaviour.
downloads: ToolDownloadSettings,
}
impl Tools {
@@ -492,9 +496,16 @@ impl Tools {
runtime_env: BTreeMap::new(),
version_timeout: Duration::from_secs(4),
work_dir: None,
downloads: ToolDownloadSettings::default(),
}
}
/// [`Self::downloads`] from Tools › Download sources.
pub fn with_downloads(mut self, downloads: ToolDownloadSettings) -> Self {
self.downloads = downloads;
self
}
/// Applies the project's SDKs to prerequisite lookup, probes and installer children.
pub fn with_runtime(mut self, commands: BTreeMap<String, PathBuf>, env: BTreeMap<String, String>) -> Self {
self.runtime_commands = commands;
@@ -1470,7 +1481,7 @@ impl Tools {
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<()> {
let archive = fetch_verified(http, dl, staging, cancel, emit)?;
let archive = fetch_verified(&self.downloads, http, dl, staging, cancel, emit)?;
emit(InstallEvent::Line { text: "Extracting…".into() });
let pkg = staging.join("pkg");
let kind = archive::ArchiveKind::from_name(&dl.name);
@@ -1703,9 +1714,14 @@ impl Tools {
}
}
/// Downloads `dl` into `staging` and checks its SHA-256 when one is published;
/// returns the downloaded file.
/// Downloads `dl` from the best source that answers (Tools › Download sources) and checks its
/// SHA-256 when one is published; returns the downloaded file.
///
/// A mirror may only deliver bytes that can be checked: when neither the release nor its
/// checksum file gives a hash, an archive from a mirror is discarded and the official host is
/// tried, because a third party must not be the only word on what gets installed.
fn fetch_verified(
downloads: &ToolDownloadSettings,
http: &Http,
dl: &sources::Download,
staging: &Path,
@@ -1713,33 +1729,92 @@ fn fetch_verified(
emit: Emit,
) -> IdeResult<PathBuf> {
let archive = staging.join(&dl.name);
http.download(&dl.url, &archive, dl.size, cancel, emit)?;
let expected = match (&dl.sha256, &dl.checksum_url) {
(Some(h), _) => Some(h.clone()),
(None, Some(url)) => match http.get_text(url, cancel) {
Ok(text) => sources::parse_checksum(&text, &dl.name),
let candidates = mirror::candidates(&dl.url, downloads);
let expected = expected_sha256(http, dl, cancel)?;
let mut failures: Vec<String> = Vec::new();
for (index, candidate) in candidates.iter().enumerate() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// Bytes a failed source left behind must not be resumed or mistaken for this one's.
if index > 0 {
let _ = std::fs::remove_file(&archive);
}
// Only worth saying when there is a choice of source: with one candidate the line
// would just repeat the download message that follows.
if candidates.len() > 1 {
emit(InstallEvent::Line {
text: format!("Trying {} ({} of {})…", candidate.describe(), index + 1, candidates.len()),
});
}
let attempt = http.download(&candidate.url, &archive, dl.size, cancel, emit);
match attempt {
Ok(()) => match check_sha256(&archive, dl, expected.as_deref(), candidate.mirror.is_some(), emit) {
Ok(()) => {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
return Ok(archive);
}
// A mismatch from a mirror is that mirror's failure: the official host below
// still gets its chance. From the official host it is the download's failure.
Err(e) if candidate.mirror.is_some() => {
failures.push(format!("{}: {}", candidate.describe(), e.message))
}
Err(e) => return Err(e),
},
// Cancelling stops the install: the remaining sources are not tried.
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
Err(_) => None,
},
(None, None) => None,
};
match expected {
Some(expected) => {
let actual = sources::sha256_file(&archive)?;
if actual != expected {
return Err(IdeError::new(
ErrorKind::Io,
format!("checksum mismatch for {}: expected {expected}, got {actual}", dl.name),
));
}
emit(InstallEvent::Line { text: "Checksum verified (SHA-256)".into() });
Err(e) => failures.push(format!("{}: {}", candidate.describe(), e.message)),
}
None => emit(InstallEvent::Line { text: "No checksum published; skipping verification".into() }),
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
Err(IdeError::new(ErrorKind::Io, format!("could not download {} ({})", dl.name, failures.join("; "))))
}
/// The SHA-256 `dl` must match, when one is published.
///
/// The checksum file is read from its official URL, never through the mirror: otherwise a
/// mirror could vouch for bytes it chose itself.
fn expected_sha256(http: &Http, dl: &sources::Download, cancel: &CancellationToken) -> IdeResult<Option<String>> {
match (&dl.sha256, &dl.checksum_url) {
(Some(h), _) => Ok(Some(h.clone())),
(None, Some(url)) => match http.get_text(url, cancel) {
Ok(text) => Ok(sources::parse_checksum(&text, &dl.name)),
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
Err(_) => Ok(None),
},
(None, None) => Ok(None),
}
Ok(archive)
}
/// Checks `archive` against `expected`, if any. `via_mirror` refuses an archive nothing can
/// vouch for rather than installing unverifiable bytes from a third party.
fn check_sha256(
archive: &Path,
dl: &sources::Download,
expected: Option<&str>,
via_mirror: bool,
emit: Emit,
) -> IdeResult<()> {
let Some(expected) = expected else {
if via_mirror {
return Err(IdeError::new(
ErrorKind::Io,
format!("{} has no published checksum, so the mirror's copy is not trusted", dl.name),
));
}
emit(InstallEvent::Line { text: "No checksum published; skipping verification".into() });
return Ok(());
};
let actual = sources::sha256_file(archive)?;
if actual != expected {
return Err(IdeError::new(
ErrorKind::Io,
format!("checksum mismatch for {}: expected {expected}, got {actual}", dl.name),
));
}
emit(InstallEvent::Line { text: "Checksum verified (SHA-256)".into() });
Ok(())
}
/// Removes the quarantine flag archives may carry, so macOS runs what was unpacked.
+127
Переглянути файл
@@ -0,0 +1,127 @@
//! Download mirrors: a user-configured proxy prefix the installer tries when an official host
//! is slow or unreachable (Tools › Download sources).
//!
//! The official URL is appended to the prefix unchanged, which is what the public GitHub
//! proxies speak. Only `github.com` is mirrored: those proxies hard-code that host, so an
//! Eclipse or Open VSX address through one answers 502. Hosts that carry credentials are
//! never mirrored either — the GitHub token must not reach a third party.
use ide_core::settings::ToolDownloadSettings;
/// The only host a mirror prefix may be prepended to.
const MIRRORED_PREFIX: &str = "https://github.com/";
/// Where one download is fetched from.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Candidate {
pub url: String,
/// The mirror this URL goes through; `None` for the official host.
pub mirror: Option<String>,
}
impl Candidate {
/// The source shown to the user in install messages.
pub fn describe(&self) -> &str {
match &self.mirror {
Some(mirror) => mirror,
None => "the official source",
}
}
}
/// The mirror prefix, normalised to end in `/`; `None` when none is set or it is not an
/// `http(s)://` URL.
pub fn prefix(mirror: &str) -> Option<String> {
let trimmed = mirror.trim();
let rest = trimmed.strip_prefix("https://").or_else(|| trimmed.strip_prefix("http://"))?;
if rest.split('/').next().unwrap_or("").is_empty() {
return None;
}
Some(if trimmed.ends_with('/') { trimmed.to_owned() } else { format!("{trimmed}/") })
}
/// `url` through `mirror`, or `None` when it is not a source a prefix can carry.
pub fn through(url: &str, mirror: &str) -> Option<String> {
let prefix = prefix(mirror)?;
if !url.starts_with(MIRRORED_PREFIX) {
return None;
}
Some(format!("{prefix}{url}"))
}
/// The URLs to try for `url`: the mirror when one is set, then the official host.
///
/// A configured mirror is tried first — the user set it because the official host is slow, so
/// waiting for that host to fail first would defeat the point. The official host stays last as
/// the fallback, and with no mirror the list is exactly `[url]`, so an unconfigured IDE
/// downloads as it always did.
pub fn candidates(url: &str, settings: &ToolDownloadSettings) -> Vec<Candidate> {
let official = Candidate { url: url.to_owned(), mirror: None };
match through(url, &settings.github_mirror) {
Some(mirrored) => vec![Candidate { url: mirrored, mirror: Some(settings.github_mirror.clone()) }, official],
None => vec![official],
}
}
#[cfg(test)]
mod tests {
use super::*;
const ASSET: &str = "https://github.com/LuaLS/lua-language-server/releases/download/3.13.5/x.zip";
fn settings(mirror: &str) -> ToolDownloadSettings {
ToolDownloadSettings { github_mirror: mirror.into() }
}
#[test]
fn no_mirror_keeps_the_official_url_only() {
assert_eq!(candidates(ASSET, &settings("")), vec![Candidate { url: ASSET.into(), mirror: None }]);
}
#[test]
fn the_prefix_gets_one_trailing_slash() {
for mirror in ["https://gh-proxy.com", "https://gh-proxy.com/", " https://gh-proxy.com "] {
assert_eq!(
through(ASSET, mirror).as_deref(),
Some(
"https://gh-proxy.com/https://github.com/LuaLS/lua-language-server/releases/download/3.13.5/x.zip"
),
);
}
}
#[test]
fn hosts_a_prefix_cannot_carry_stay_official() {
for url in [
// The public proxies only answer for github.com; these answer 502 through them.
"https://download.eclipse.org/jdtls/milestones/1.63.0/x.tar.gz",
"https://open-vsx.org/api/vscjava/vscode-java-debug/0.60.0/file/x.vsix",
"https://api.github.com/repos/cli/cli/releases/latest",
"https://repo1.maven.org/maven2/org/eclipse/lsp4j/1.0.0/x.jar",
] {
assert_eq!(through(url, "https://gh-proxy.com"), None, "{url}");
assert_eq!(candidates(url, &settings("https://gh-proxy.com")).len(), 1, "{url}");
}
}
#[test]
fn a_configured_mirror_goes_first() {
let candidates = candidates(ASSET, &settings("https://gh-proxy.com"));
assert_eq!(candidates[0].mirror.as_deref(), Some("https://gh-proxy.com"));
assert_eq!(candidates[1].mirror, None, "the official host is the fallback");
}
#[test]
fn a_prefix_that_is_not_a_url_is_ignored() {
for mirror in ["gh-proxy.com", "ftp://x", "https://", " "] {
assert_eq!(prefix(mirror), None, "{mirror}");
assert_eq!(through(ASSET, mirror), None, "{mirror}");
}
}
#[test]
fn an_already_prefixed_url_is_not_prefixed_twice() {
let once = through(ASSET, "https://gh-proxy.com").unwrap();
assert_eq!(through(&once, "https://gh-proxy.com"), None);
}
}
+3 -1
Переглянути файл
@@ -59,7 +59,9 @@ pub fn fetch(
size: None,
sha256: Some(sha256),
};
let archive = fetch_verified(&http, &dl, &staging, cancel, emit)?;
// The remote server binary is not part of Tools › Download sources: it always comes
// from its own release.
let archive = fetch_verified(&Default::default(), &http, &dl, &staging, cancel, emit)?;
let unpacked = staging.join("openidea-server");
let mut gz = flate2::read::GzDecoder::new(std::fs::File::open(&archive)?);
std::io::copy(&mut gz, &mut std::fs::File::create(&unpacked)?)?;
+100
Переглянути файл
@@ -1131,3 +1131,103 @@ fn npm_tools_report_a_newer_registry_version() {
);
assert_eq!(tools("5.4.0").updates(&cancel).unwrap(), vec![]);
}
/// Tools › Download sources: a configured mirror serves a GitHub release the official host
/// cannot, and the official host is kept as the fallback.
#[cfg(unix)]
#[test]
fn a_mirror_serves_what_the_official_host_cannot() {
let env = Env::new();
let fixtures = env.root.parent().unwrap().join("fixtures");
fs::create_dir_all(&fixtures).unwrap();
let archive = fixtures.join("lls.tar.gz");
{
let gz = flate2::write::GzEncoder::new(fs::File::create(&archive).unwrap(), flate2::Compression::fast());
let mut b = tar::Builder::new(gz);
let body = b"#!/bin/sh\necho 3.13.5\n";
let mut h = tar::Header::new_gnu();
h.set_size(body.len() as u64);
h.set_mode(0o755);
h.set_cksum();
b.append_data(&mut h, "bin/lua-language-server", &body[..]).unwrap();
b.into_inner().unwrap().finish().unwrap();
}
let digest = sources::sha256_file(&archive).unwrap();
// Release assets live on github.com: only those addresses are mirrored.
let assets: Vec<String> = ["darwin-arm64.tar.gz", "darwin-x64.tar.gz", "linux-x64.tar.gz", "linux-arm64.tar.gz"]
.iter()
.map(|s| {
format!(
r#"{{"name":"lua-language-server-3.13.5-{s}","browser_download_url":"https://github.com/LuaLS/lua-language-server/releases/download/3.13.5/{s}","size":{},"digest":"sha256:{digest}"}}"#,
fs::metadata(&archive).unwrap().len()
)
})
.collect();
let json = fixtures.join("release.json");
fs::write(&json, format!(r#"{{"tag_name":"3.13.5","assets":[{}]}}"#, assets.join(","))).unwrap();
// The mirror serves the asset; the official host is unreachable.
let log = fixtures.join("asked.log");
env.script(
&env.sys,
"curl",
&format!(
r#"out=""; url=""
while [ $# -gt 0 ]; do case "$1" in -o) out="$2"; shift 2;; -A|-H|--retry|--connect-timeout) shift 2;; -*) shift;; *) url="$1"; shift;; esac; done
/bin/echo "$url" >> '{log}'
case "$url" in
https://api.github.com/*) /bin/cat '{json}';;
https://mirror.test/https://github.com/*) /bin/cp '{archive}' "$out";;
*) exit 22;;
esac"#,
log = log.display(),
json = json.display(),
archive = archive.display()
),
);
let downloads = ToolDownloadSettings { github_mirror: "https://mirror.test/".into() };
let emit = |_: InstallEvent| {};
env.tools()
.with_downloads(downloads)
.install("lua-language-server", &langs(), &CancellationToken::new(), &emit)
.unwrap();
let asked = fs::read_to_string(&log).unwrap();
// A configured mirror is tried first — waiting for a slow official host would defeat it.
let mirror_at = asked.find("https://mirror.test/https://github.com/").expect("the mirror is tried");
assert!(!asked[..mirror_at].contains("releases/download"), "the mirror goes first: {asked}");
}
/// A mirror may only deliver bytes something can vouch for; the official host may not.
#[test]
fn a_mirror_never_installs_what_it_alone_vouches_for() {
let tmp = tempfile::tempdir().unwrap();
let archive = tmp.path().join("tool.tar.gz");
fs::write(&archive, b"bytes").unwrap();
let digest = sources::sha256_file(&archive).unwrap();
let dl = |sha256: Option<&str>| sources::Download {
version: "1.0.0".into(),
name: "tool.tar.gz".into(),
url: "https://github.com/o/r/releases/download/v1/tool.tar.gz".into(),
size: None,
sha256: sha256.map(str::to_owned),
checksum_url: None,
};
let lines = Mutex::new(Vec::new());
let emit = |e: InstallEvent| {
if let InstallEvent::Line { text } = e {
lines.lock().push(text);
}
};
// Nothing published: the official host is trusted, a mirror is not.
check_sha256(&archive, &dl(None), None, false, &emit).unwrap();
let err = check_sha256(&archive, &dl(None), None, true, &emit).unwrap_err();
assert!(err.message.contains("no published checksum"), "{}", err.message);
// A matching hash passes from either source.
check_sha256(&archive, &dl(Some(&digest)), Some(&digest), true, &emit).unwrap();
assert!(lines.lock().iter().any(|l| l.contains("Checksum verified")));
// A mismatch is refused whoever served it.
let err = check_sha256(&archive, &dl(Some(&digest)), Some(&"0".repeat(64)), true, &emit).unwrap_err();
assert!(err.message.contains("checksum mismatch"), "{}", err.message);
}
+7 -7
Переглянути файл
@@ -38,7 +38,7 @@ flowchart LR
## The server
```text
openidea-server --stdio | --connect <host> <port> | --version
openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <port> | --version
```
- `--stdio` serves one desktop client over stdin/stdout. stdout carries the protocol, so logs go to stderr (filter with `OPENIDEA_LOG`).
@@ -78,12 +78,12 @@ A few commands are always local even if the server knows them: `open_project` an
### What runs where
| On the remote machine | On the desktop |
| -------------------------------------------------------- | ------------------------------------ |
| The project: files, documents, settings | Windows, menus, the webview |
| Language servers, index, search | Client UI settings, keymaps, themes |
| Git, terminals, runs, debug adapters | The SSH connection and port forwards |
| Code plugins of the project, their processes and fetches | Plugin secrets (keychain) |
| On the remote machine | On the desktop |
| --------------------------------------------------------- | ------------------------------------ |
| The project: files, documents, settings | Windows, menus, the webview |
| Language servers, index, search | Client UI settings, keymaps, themes |
| Git, terminals, runs, debug adapters, built-in MCP server | The SSH connection and port forwards |
| Code plugins of the project, their processes and fetches | Plugin secrets (keychain) |
## Port forwarding
+12 -2
Переглянути файл
@@ -3,7 +3,7 @@ title: "Databases"
description: "Connect to SQL databases, browse schemas, run queries in a console, and view, edit, import and export data."
---
The **Database** tool window connects to SQLite, PostgreSQL, MySQL/MariaDB, Microsoft SQL Server, Oracle, ClickHouse and Snowflake, plus databases that speak one of their protocols. Drivers are built into the IDE; there are no JDBC drivers to download.
The **Database** tool window connects to SQLite, PostgreSQL, MySQL/MariaDB, Microsoft SQL Server, Oracle, ClickHouse and Snowflake, plus databases that speak one of their protocols. These presets use built-in drivers. You can also connect with a vendor JDBC driver installed locally.
Open it from **Tools › Database** or **View › Tool Windows › Database**. The **Tools** menu also has **New Data Source…** and **Open Query Console**.
@@ -23,6 +23,16 @@ Open it from **Tools › Database** or **View › Tool Windows › Database**. T
Presets set the default port and, where needed, SSL (for example Redshift, Neon and Supabase require SSL).
## Custom JDBC drivers
Choose **New › Data Source › Custom JDBC**, then **Manage Drivers…**. Add a named profile with the vendor's driver JAR, any dependency JARs, the fully qualified driver class, and an optional JDBC URL template. OpenIDEA reads the driver classes declared in the selected JARs. You can choose a different class or enter its full name manually. Use `{host}`, `{port}`, `{database}` or `{file}` in a template to get matching connection fields, or edit the JDBC URL directly. Only import drivers you trust. OpenIDEA loads their code in a separate process using an installed Java 17 or newer runtime.
Select the profile, enter the vendor's JDBC URL, and use the **User**, **Password**, and **Advanced** fields for credentials and driver properties. The URL and Advanced properties are stored in the data source configuration. Put credentials in the password field to use the existing OS credential store. On Linux, saving a password requires a running Secret Service. You can also enter the password for the current session. The **Read-only** option asks the JDBC driver for a read-only connection. Use a database account with read-only privileges to enforce it. Cancelling a query keeps the session and its temporary tables when the driver stops the statement. If the driver does not respond within three seconds, OpenIDEA closes the session. A submitted statement can still finish on the server. **Test Connection** reports the database product and version. Schema, table and column browsing use JDBC metadata; the SQL console supports auto-commit queries and updates. Vendor-specific DDL, execution plans and table-grid writes are unavailable for custom drivers.
For a file-backed database, use an absolute path to choose its location. Relative paths start in the persistent `jdbc/files` folder inside OpenIDEA’s application data directory.
Profiles are reused across projects. If a project file changes a connection's URL or properties outside the IDE, review the settings in the data source dialog and save them before reconnecting.
## Add a data source
Click **+** in the Database tool window (or press `⌘N` / `Alt+Insert` there) and choose:
@@ -205,7 +215,7 @@ Limits: `TIMESTAMP_LTZ` values are shown in UTC; SSH tunnels are not offered; re
## Not supported
- MongoDB, Redis, BigQuery and other non-listed databases; JDBC drivers.
- Native drivers for MongoDB, Redis and BigQuery.
- SQL Server `GO` batch separators.
- A "run the whole console" action (use a selection, or **Run SQL Script…**).
- Exporting more than the loaded page.
+1 -1
Переглянути файл
@@ -163,7 +163,7 @@ Each form has **Host** and **Port** fields and shows the command to start the re
- **Java HotSwap**: **Run › Debugging Actions › Reload Changed Classes** compiles your changes and reloads the changed classes into the running Java debug session. Active frames keep running the old code until they return. When JDT LS finishes a build after a save, the IDE offers the reload.
- **Maven and Gradle**: debugging a Maven or Gradle configuration starts the JVM with a JDWP agent and attaches java-debug to it.
- **Dart / Flutter**: **Hot Reload** and **Hot Restart** are available while a Dart session is running.
- **Dart / Flutter**: **Hot Reload** and **Hot Restart** are available while a Dart session is running. In a Flutter project, the device selector next to the run configuration chooses where Run and Debug start the app; a run configuration's **Device** field pins it to one device. Saving a Dart file of a running Flutter debug session also hot reloads the app, unless the file has errors. Turn this off with **Hot reload on save** in **Settings › Build, Execution, Deployment › Debugger**.
- **PHP**: if the PHP interpreter does not load Xdebug, breakpoints are skipped; the IDE warns about this when the session starts.
- **Python**: **Settings › Build, Execution, Deployment › Python Debugger** has **Attach to subprocess automatically while debugging** and **Gevent compatible**.
+4 -1
Переглянути файл
@@ -132,8 +132,11 @@ Plugins can add more tools; they appear in the same list. A plugin tool marked a
- **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.
## Remote development
In a remote window ([SSH](/en/guide/remote/ssh), WSL or [Dev Containers](/en/guide/remote/containers)), `openidea-server` runs its own MCP server on the remote host, configured independently in **Settings › Agents › IDE MCP Server** while that remote window is focused. Coding agents started inside the remote window connect to it automatically; external CLI clients on the remote host can use **Copy Stdio Config** (`~/.openidea/bin/openidea-server --mcp-stdio`) or **Copy HTTP Config**, and clients on your desktop can reach it by forwarding its port in the **Ports** tool window.
## Limits
- Remote projects (opened over SSH, on a server or in a container) are not supported by the MCP server yet.
- The server serves only projects open in OpenIDEA. Closing the project's window makes its tools unavailable.
- Responses are plain JSON; the server does not stream over SSE.
+6 -5
Переглянути файл
@@ -92,11 +92,12 @@ Build on, or cross-compile for, the host's platform, then point `OPENIDEA_SERVER
The flags are meant for the desktop app, but `--version` is handy for checking an installed build.
| Flag | Meaning |
| ------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `--version` | Print the server version and protocol version, then exit. |
| `--stdio` | Serve one desktop client over stdin / stdout. Logs go to stderr. |
| `--connect <host> <port>` | Relay one TCP connection to `<host>:<port>` over stdin / stdout. Used for port forwarding into dev containers. |
| Flag | Meaning |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `--version` | Print the server version and protocol version, then exit. |
| `--stdio` | Serve one desktop client over stdin / stdout. Logs go to stderr. |
| `--mcp-stdio [--project <dir>]` | Relay stdio MCP traffic to the running `openidea-server` MCP server on this host. |
| `--connect <host> <port>` | Relay one TCP connection to `<host>:<port>` over stdin / stdout. Used for port forwarding into dev containers. |
```bash
ls ~/.openidea/server/*/*/openidea-server
+2 -1
Переглянути файл
@@ -15,10 +15,11 @@ If gopls is missing, OpenIDEA shows a **gopls is not installed** notification wi
### Go SDK
**Settings › Languages & Frameworks › Go** has two settings:
**Settings › Languages & Frameworks › Go** has three settings:
- **GOROOT**: the Go SDK used by gopls and the go run and test configurations. **Default** uses `go` on `PATH`; if the project pins a Go version for mise or asdf, that install is used instead.
- **Project GOPATH**: empty uses `go env GOPATH`.
- **Format with gofumpt**: gopls formats with [gofumpt](https://github.com/mvdan/gofumpt), a stricter gofmt, when you reformat code (gopls `gofumpt` setting). Off by default.
The GOROOT list shows the SDKs the IDE finds: the `go` on `PATH`, `/usr/local/go`, Homebrew and `/usr/lib/go` installs, SDKs in `~/sdk` (installed with `golang.org/dl`), toolchains Go downloaded itself (`~/go/pkg/mod/golang.org/toolchain@…`), and mise and asdf installs.
+7 -7
Переглянути файл
@@ -38,7 +38,7 @@ flowchart LR
## 服务端
```text
openidea-server --stdio | --connect <host> <port> | --version
openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <port> | --version
```
- `--stdio` 通过 stdin/stdout 为一个桌面客户端提供服务。stdout 承载协议,所以日志写到 stderr(用 `OPENIDEA_LOG` 过滤)。
@@ -78,12 +78,12 @@ openidea-server --stdio | --connect <host> <port> | --version
### 什么在哪里运行
| 远程机器上 | 桌面端 |
| -------------------------------- | ---------------------------- |
| 项目:文件、文档、设置 | 窗口、菜单、webview |
| 语言服务器、索引、搜索 | 客户端 UI 设置、keymap、主题 |
| Git、终端、运行、调试适配器 | SSH 连接和端口转发 |
| 项目的代码插件及其进程和网络请求 | 插件密钥(钥匙串) |
| 远程机器上 | 桌面端 |
| -------------------------------------------- | ---------------------------- |
| 项目:文件、文档、设置 | 窗口、菜单、webview |
| 语言服务器、索引、搜索 | 客户端 UI 设置、keymap、主题 |
| Git、终端、运行、调试适配器、内置 MCP 服务器 | SSH 连接和端口转发 |
| 项目的代码插件及其进程和网络请求 | 插件密钥(钥匙串) |
## 端口转发
+12 -2
Переглянути файл
@@ -3,7 +3,7 @@ title: "数据库"
description: "连接 SQL 数据库、浏览架构、在查询控制台中执行查询,以及查看、编辑、导入和导出数据。"
---
**数据库** 工具窗口可以连接 SQLite、PostgreSQL、MySQL/MariaDB、Microsoft SQL Server、Oracle、ClickHouse 和 Snowflake,以及兼容这些协议的数据库。驱动内置在 IDE 中,不需要下载 JDBC 驱动。
**数据库** 工具窗口可以连接 SQLite、PostgreSQL、MySQL/MariaDB、Microsoft SQL Server、Oracle、ClickHouse 和 Snowflake,以及兼容这些协议的数据库。这些预设使用 IDE 内置的驱动,也可以选择本地安装的厂商 JDBC 驱动。
通过 **工具 › 数据库** 或 **视图 › 工具窗口 › 数据库** 打开。**工具** 菜单中还有 **新建数据源…** 和 **Open Query Console**(打开查询控制台)。
@@ -23,6 +23,16 @@ description: "连接 SQL 数据库、浏览架构、在查询控制台中执行
预设会填好默认端口,必要时还会设置 SSL(例如 Redshift、Neon 和 Supabase 要求 SSL)。
## 自定义 JDBC 驱动
选择 **新建 › 数据源 › 自定义 JDBC**,然后选择 **管理驱动…**。为驱动配置命名,添加厂商提供的驱动 JAR 及依赖 JAR,填写完整的驱动类名和可选的 JDBC URL 模板。请仅导入可信来源的驱动。OpenIDEA 使用已安装的 Java 17 或更高版本运行时在单独的进程中加载驱动。 IDE 会读取 JAR 声明的驱动类,也支持手动输入完整类名。URL 模板支持 `{host}`、`{port}`、`{database}` 和 `{file}`,也可直接填写 JDBC URL。 URL 和高级属性会写入数据源配置,密码请填在密码栏,以使用系统凭据存储。“只读”选项会请求 JDBC 驱动建立只读连接。使用具备只读权限的数据库账号可强制限制写入。取消查询时,如果驱动停止了语句,会话及其临时表会保留。如果驱动在三秒内未响应,OpenIDEA 会关闭该会话。已提交的语句仍可能在服务器上完成。
选择驱动配置,填写厂商的 JDBC URL,在 **用户**、**密码** 和 **高级** 中设置凭据和驱动属性。通过密码字段输入的密码可以保存到系统凭据库。在 Linux 上,保存密码需要正在运行的 Secret Service;也可以仅为当前会话输入密码。**测试连接** 显示数据库产品和版本。可以通过 JDBC 元数据浏览模式、表和列,在 SQL 控制台中查询或以自动提交方式更新数据。自定义驱动不支持厂商特有的 DDL、执行计划或表格编辑。
文件数据库可使用绝对路径指定存储位置。相对路径以 OpenIDEA 应用数据目录下的持久化 `jdbc/files` 文件夹为起点。
驱动配置可以跨项目复用。在 IDE 外更改项目数据源的 URL 或连接属性后,需要在数据源对话框中检查并保存设置,才能重新连接。
## 添加数据源
在数据库工具窗口中点击 **+**(或在窗口内按 `⌘N` / `Alt+Insert`),然后选择:
@@ -200,7 +210,7 @@ Oracle 的架构就是数据库用户;系统账户只在勾选 **显示内部
## 暂不支持
- MongoDB、Redis、BigQuery 等未列出的数据库,以及 JDBC 驱动。
- MongoDB、Redis 和 BigQuery 的原生驱动。
- SQL Server 的 `GO` 批处理分隔符。
- “执行整个控制台”的操作(请选中后执行,或使用 **运行 SQL 脚本…**)。
- 导出超出已加载页面的数据。
+1 -1
Переглянути файл
@@ -165,7 +165,7 @@ C 和 C++ 的配置也可以改用 GDB 14 及以上版本(`gdb -i dap`):
- **Java HotSwap**:**运行 › 调试操作 › 重新加载已更改的类** 编译改动,并把变化的类重新加载到正在运行的 Java 调试会话中。已经在执行的帧要等返回后才会用上新代码。保存后 JDT LS 自动完成构建时,IDE 也会提示是否重新加载。
- **Maven 和 Gradle**:调试 Maven 或 Gradle 配置时,IDE 会让 JVM 带上 JDWP agent 启动,再用 java-debug 附加上去。
- **Dart / Flutter**:Dart 会话运行时可以用 **热重载** 和 **热重启**。
- **Dart / Flutter**:Dart 会话运行时可以用 **热重载** 和 **热重启**。在 Flutter 项目中,运行配置旁边的设备选择器决定运行和调试在哪台设备上启动应用;运行配置的 **设备** 字段可以固定使用某台设备。保存正在运行的 Flutter 调试会话里的 Dart 文件时也会自动热重载,文件有错误时跳过。可在 **设置 › 构建、执行、部署 › 调试器** 中关闭 **保存时热重载**。
- **PHP**:如果 PHP 解释器没有加载 Xdebug,断点会被跳过;会话启动时 IDE 会提示。
- **Python**:**设置 › 构建、执行、部署 › Python 调试器** 中有 **调试时自动附加到子进程** 和 **兼容 Gevent**。
+4 -1
Переглянути файл
@@ -131,8 +131,11 @@ stdio 配置大致如下(路径以你机器上的为准):
- **运行和构建会先询问。** `execute_run_configuration`、`build_project`、`run_command` 和 `http_run_request` 会在 OpenIDEA 中弹出对话框,说明是哪个客户端、哪个项目、哪个工具以及要运行什么,选择 **允许** 或 **拒绝**;多个请求会排队。
- 会写入的工具拒绝项目之外的路径。
## 远程开发
在远程窗口([SSH](/zh/guide/remote/ssh)、WSL 或[容器](/zh/guide/remote/containers))中,`openidea-server` 会在远程主机上运行自己的 MCP 服务器,可在该远程窗口的 **Settings › Agents › IDE MCP Server** 中独立配置。远程窗口内启动的编程智能体会立即可用内置工具;在远程主机终端运行的外部客户端可使用 **Copy Stdio Config**(`~/.openidea/bin/openidea-server --mcp-stdio`)或 **Copy HTTP Config**,桌面端客户端则可在 **Ports** 工具窗口转发该端口后连接。
## 限制
- 远程项目(通过 SSH、服务器或容器打开的项目)暂不支持 MCP 服务器。
- 服务器只为 OpenIDEA 中已打开的项目提供服务,关闭项目窗口后该项目的工具就不可用了。
- 响应是普通 JSON,服务器不通过 SSE 推送流式结果。
+6 -5
Переглянути файл
@@ -79,11 +79,12 @@ cargo build --release -p ide-host --bin openidea-server
这些参数是给桌面端用的,不过 `--version` 可以用来检查已安装的构建。
| 参数 | 含义 |
| ------------------------- | -------------------------------------------------------------------------------- |
| `--version` | 输出服务端版本和协议版本后退出。 |
| `--stdio` | 通过标准输入输出服务一个桌面客户端,日志写到 stderr。 |
| `--connect <host> <port>` | 通过标准输入输出中转一个到 `<host>:<port>` 的 TCP 连接,用于开发容器的端口转发。 |
| 参数 | 含义 |
| ------------------------------- | -------------------------------------------------------------------------------- |
| `--version` | 输出服务端版本和协议版本后退出。 |
| `--stdio` | 通过标准输入输出服务一个桌面客户端,日志写到 stderr。 |
| `--mcp-stdio [--project <dir>]` | 将标准输入输出上的 MCP 消息转发给当前主机正在运行的 `openidea-server` MCP 服务。 |
| `--connect <host> <port>` | 通过标准输入输出中转一个到 `<host>:<port>` 的 TCP 连接,用于开发容器的端口转发。 |
```bash
ls ~/.openidea/server/*/*/openidea-server
+2 -1
Переглянути файл
@@ -15,10 +15,11 @@ gopls 负责 `.go`、`go.mod` 和 `go.work` 文件。工作区从最近的 `go.w
### Go SDK
**设置 › 语言和框架 › Go** 有两项设置:
**设置 › 语言和框架 › Go** 有三项设置:
- **GOROOT**:gopls 以及 go run / test 运行配置使用的 Go SDK。选 **默认** 时使用 `PATH` 上的 `go`;如果项目通过 mise 或 asdf 固定了 Go 版本,则改用那个安装。
- **项目 GOPATH**:留空时使用 `go env GOPATH`。
- **使用 gofumpt 格式化**:重新格式化代码时,gopls 使用更严格的 [gofumpt](https://github.com/mvdan/gofumpt) 代替 gofmt(gopls 的 `gofumpt` 设置)。默认关闭。
GOROOT 列表会显示 IDE 找到的 SDK:`PATH` 上的 `go`、`/usr/local/go`、Homebrew 和 `/usr/lib/go` 的安装、`~/sdk` 下的 SDK(通过 `golang.org/dl` 安装)、Go 自己下载的工具链(`~/go/pkg/mod/golang.org/toolchain@…`),以及 mise 和 asdf 的安装。
+81
Переглянути файл
@@ -0,0 +1,81 @@
/**
* The Flutter device selector next to the run configuration. The daemon is stubbed at the IPC
* layer; `crates/ide-flutter` covers its protocol and process.
*/
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const device = (id: string, name: string, category: string, unavailable: string | null = null) => ({
id,
name,
platformType: null,
category,
emulator: false,
unavailable,
});
const MACOS = device("macos", "macOS", "desktop");
const CHROME = device("chrome", "Chrome", "web");
const UNAUTHORIZED = device("R5C", "R5C", "mobile", "unauthorized");
async function stubFlutter(page: Page, status: unknown = { kind: "ready" }) {
await stubDesktop(page);
await page.evaluate(
async ({ list }) => {
const config = {
id: "flutter:run",
name: "flutter run",
kind: "flutter",
command: "flutter",
args: ["run", "-t", "lib/main.dart"],
cwd: null,
env: {},
detected: true,
isTest: false,
debugAdapter: "dart",
};
const h = window.__ipc.handlers;
h.run_configs = () => [config];
h.run_apply_settings = (args) => args.configs;
h.flutter_devices = () => list;
h.flutter_devices_refresh = () => null;
h.run_start = () => ({ id: 3, configId: config.id, name: config.name, pid: 42, running: true, pty: false });
const runModule = "/src/features/run/store.ts";
const { loadConfigs, selectConfig } = await import(/* @vite-ignore */ runModule);
await loadConfigs();
selectConfig(config.id);
},
{ list: { status, devices: [MACOS, CHROME, UNAUTHORIZED] } },
);
}
const chooser = (page: Page) => page.getByRole("button", { name: /^Flutter device:/ });
test("the chosen device is used for Run, and replaced while it is disconnected", async ({ workbench: page }) => {
await stubFlutter(page);
await expect(chooser(page)).toContainText("macOS");
await chooser(page).click();
await expect(page.getByRole("menuitemcheckbox", { name: "R5C (unauthorized)" })).toBeDisabled();
await page.getByRole("menuitemcheckbox", { name: "Chrome" }).click();
await expect(chooser(page)).toContainText("Chrome");
await page.keyboard.press("Control+r");
await expect.poll(async () => (await ipcCalls(page, "run_start")).length).toBe(1);
const [started] = await ipcCalls(page, "run_start");
expect((started!.config as { args: string[] }).args).toEqual(["run", "-t", "lib/main.dart", "-d", "chrome"]);
const emit = (devices: unknown[]) =>
page.evaluate(
(devices) => window.__ipc.emit({ type: "flutterDevices", list: { status: { kind: "ready" }, devices } }),
devices,
);
await emit([MACOS]);
await expect(chooser(page)).toContainText("macOS");
await emit([MACOS, CHROME]);
await expect(chooser(page)).toContainText("Chrome");
});
test("says when the Flutter SDK is missing", async ({ workbench: page }) => {
await stubFlutter(page, { kind: "notInstalled" });
await expect(chooser(page)).toContainText("Flutter SDK not found");
});
+122
Переглянути файл
@@ -0,0 +1,122 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("configures a local JDBC profile and a source through mocked IPC", async ({ workbench: page }, info) => {
await stubDesktop(page);
await page.evaluate(async () => {
const drivers: Record<string, unknown>[] = [];
let sources: Record<string, unknown>[] = [];
Object.assign(window.__ipc.handlers, {
db_jdbc_drivers: () => drivers,
db_jdbc_driver_classes: () => ["org.example.jdbc.Driver"],
db_save_jdbc_driver: ({ driver }: { driver: Record<string, unknown> }) => {
const at = drivers.findIndex((d) => d.id === driver.id);
if (at < 0) drivers.push(driver);
else drivers[at] = driver;
return null;
},
db_remove_jdbc_driver: ({ id }: { id: string }) => {
drivers.splice(
drivers.findIndex((d) => d.id === id),
1,
);
return null;
},
file_dialog_needs_gtk: () => false,
"plugin:dialog|open": () => ["/mock/driver.jar", "/mock/dependency.jar"],
db_test: () => "Mock JDBC database",
db_approve_jdbc_source: () => null,
db_save_sources: ({ sources: value }: { sources: Record<string, unknown>[] }) => {
sources = value;
return null;
},
db_sources: () => sources,
db_connected: () => [],
db_set_password: () => null,
});
const storePath = "/src/features/database/store.ts";
const { openSourceDialog } = await import(/* @vite-ignore */ storePath);
openSourceDialog(null, {
driver: "clickhouse",
name: "Mock connection",
host: "example.invalid",
port: 8443,
ssl: "verifyFull",
sslCaFile: "/mock/ca.pem",
sslCertFile: "/mock/client.pem",
sslKeyFile: "/mock/client.key",
});
});
const source = page.getByRole("dialog", { name: "New Data Source", exact: true });
await source.getByRole("tab", { name: "SSH/SSL", exact: true }).click();
await source.screenshot({
path: info.outputPath("mock-native-clickhouse-before-switch.png"),
animations: "disabled",
});
await source.getByRole("tab", { name: "General", exact: true }).click();
await source.getByRole("button", { name: "Data source type", exact: true }).click();
await page.getByRole("option", { name: "Custom JDBC", exact: true }).click();
await expect(source.getByRole("tab", { name: "SSH/SSL", exact: true })).toHaveCount(0);
await expect(source.locator("#db-url")).toHaveValue("");
await source.getByRole("button", { name: "Manage Drivers…", exact: true }).click();
const profiles = page.getByRole("dialog", { name: "JDBC Driver Profiles", exact: true });
await profiles.getByRole("button", { name: "Add…", exact: true }).click();
const editor = page.getByRole("dialog", { name: "Add JDBC Driver", exact: true });
await editor.getByLabel("Name:", { exact: true }).fill("Example local driver");
await editor.getByRole("button", { name: "Add JARs…", exact: true }).click();
await expect(editor.getByText("dependency.jar", { exact: true })).toBeVisible();
await expect(editor.getByLabel("Driver class:", { exact: true })).toHaveValue("org.example.jdbc.Driver");
await editor.getByLabel("URL template:", { exact: true }).fill("jdbc:example://{host}/{database}");
await editor.screenshot({ path: info.outputPath("jdbc-profile-editor.png"), animations: "disabled" });
await editor.getByRole("button", { name: "Save", exact: true }).click();
const trust = page.getByRole("dialog", { name: "Trust JDBC Driver?", exact: true });
await expect(trust).toContainText("execute local code with your user permissions");
expect(await ipcCalls(page, "db_save_jdbc_driver")).toHaveLength(0);
await trust.screenshot({ path: info.outputPath("mock-jdbc-driver-trust.png"), animations: "disabled" });
await trust.getByRole("button", { name: "Trust and Save", exact: true }).click();
await profiles.getByRole("button", { name: "Use Driver", exact: true }).click();
await expect(source.getByRole("button", { name: "JDBC driver profile", exact: true })).toHaveText(
"Example local driver",
);
await source.getByLabel("Host:", { exact: true }).fill("example.invalid");
await source.getByLabel("Database:", { exact: true }).fill("catalog");
await expect(source.locator("#db-url")).toHaveValue("jdbc:example://example.invalid/catalog");
await source.screenshot({ path: info.outputPath("jdbc-template.png"), animations: "disabled" });
const url = "jdbc:example://example.invalid/catalog?ssl=true";
await source.locator("#db-url").fill(url);
const test = source.getByRole("button", { name: "Test Connection", exact: true });
await expect(test).toBeDisabled();
await source.getByRole("checkbox", { name: "I have configured JDBC connection security.", exact: true }).check();
await source.locator("#db-user").fill("example-user");
await source.locator("#db-password").fill("mock secret");
await source.screenshot({ path: info.outputPath("mock-jdbc-source-after-switch.png"), animations: "disabled" });
await source.getByRole("tab", { name: "Options", exact: true }).click();
await expect(source.getByRole("button", { name: "Transaction control", exact: true })).toHaveCount(0);
await source.getByRole("checkbox", { name: "Read-only", exact: true }).check();
await expect(
source.getByText("For read-only access, use a database account with read-only privileges."),
).toBeVisible();
await source.screenshot({ path: info.outputPath("jdbc-read-only.png"), animations: "disabled" });
await source.getByRole("tab", { name: "Advanced", exact: true }).click();
await source.getByRole("button", { name: "Add Property", exact: true }).click();
await source.getByLabel("Property name", { exact: true }).fill("ssl");
await source.getByLabel("Property value", { exact: true }).fill("true");
await test.click();
await expect(source.getByRole("status")).toHaveText("Succeeded: Mock JDBC database");
const [{ source: tested, password }] = await ipcCalls(page, "db_test");
expect(password).toBe("mock secret");
expect(tested).toMatchObject({
driver: "jdbc",
url,
user: "example-user",
readOnly: true,
properties: [{ name: "ssl", value: "true" }],
});
await source.getByRole("button", { name: "OK", exact: true }).click();
await expect(source).not.toBeVisible();
const [{ sources }] = await ipcCalls(page, "db_save_sources");
const [saved] = sources as Record<string, unknown>[];
const [{ driver }] = await ipcCalls(page, "db_save_jdbc_driver");
expect(saved.readOnly).toBe(true);
expect(saved.jdbcDriver).toBe((driver as Record<string, unknown>).id);
for (const key of ["jars", "className", "classpath", "exec", "password"]) expect(saved).not.toHaveProperty(key);
});
+32
Переглянути файл
@@ -0,0 +1,32 @@
"""Build the committed Java 17 JDBC bridge, or run its standalone protocol tests."""
import argparse
import os
from pathlib import Path
import subprocess
import tempfile
import zipfile
root = Path(__file__).resolve().parent
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--test", action="store_true")
parser.add_argument("--out", type=Path, help="output JAR (with --test: the fixture driver for JDBC_FIXTURE_JAR)")
args = parser.parse_args()
java_home = os.environ.get("JAVA_HOME")
def tool(name):
return str(Path(java_home) / "bin" / name) if java_home else name
with tempfile.TemporaryDirectory() as scratch:
classes = Path(scratch) / "classes"
classes.mkdir()
sources = sorted((root / "src").rglob("*.java"))
if args.test:
sources += sorted((root / "tests").glob("*.java"))
subprocess.run([tool("javac"), "--release", "17", "-encoding", "UTF-8", "-g:none",
"-d", classes, *sources], check=True)
if args.test:
subprocess.run([tool("java"), "-ea", "-cp", classes, "ai.openidea.jdbc.SelfTest"], check=True, timeout=45)
if not args.test or args.out:
with zipfile.ZipFile(args.out or root / "openidea-jdbc-bridge.jar", "w") as jar:
for path in sorted(classes.rglob("SelfTest*.class" if args.test else "*.class")):
entry = zipfile.ZipInfo(path.relative_to(classes).as_posix(), (2026, 1, 1, 0, 0, 0))
jar.writestr(entry, path.read_bytes(), compress_type=zipfile.ZIP_DEFLATED)
Бінарний файл не відображається.
+348
Переглянути файл
@@ -0,0 +1,348 @@
// The JDBC driver lives in this process only. The parent owns its lifetime and sends
// credentials over stdin. Driver console output must never enter the reply stream.
package ai.openidea.jdbc;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
public final class OpenIdeaJdbc {
static final int LIMIT = 16 * 1024 * 1024;
final DataInputStream input = new DataInputStream(new BufferedInputStream(System.in));
final DataOutputStream output = new DataOutputStream(new BufferedOutputStream(System.out));
Connection connection;
boolean catalogs;
boolean namespaceKnown;
static void text(DataOutputStream out, String value) throws IOException {
// Leave room for the two flags and update count that terminate a result.
int available = LIMIT - out.size() - Integer.BYTES - 2 - Long.BYTES;
if (available < 0 || (value != null && value.length() > available))
throw new IOException("JDBC result exceeds 16 MiB; select fewer or smaller values");
if (value == null) { out.writeInt(-1); return; }
byte[] data = value.getBytes(StandardCharsets.UTF_8);
if (data.length > available) throw new IOException("JDBC result exceeds 16 MiB; select fewer or smaller values");
out.writeInt(data.length);
out.write(data);
}
static void header(DataOutputStream out, String... names) throws IOException {
out.writeInt(names.length);
for (String name : names) { text(out, name); text(out, "VARCHAR"); }
}
static void row(DataOutputStream out, String... cells) throws IOException {
out.writeBoolean(true);
for (String cell : cells) text(out, cell);
}
static void end(DataOutputStream out, boolean more, long affected) throws IOException {
out.writeBoolean(false);
out.writeBoolean(more);
out.writeLong(affected);
}
private static class UnsupportedUrl extends SQLException {}
private static class ReadOnlyUnavailable extends SQLException {}
void open(List<String> a, DataOutputStream out) throws Exception {
String className = a.get(0), url = a.get(1);
Driver driver = Class.forName(className).asSubclass(Driver.class).getConstructor().newInstance();
var props = new Properties();
for (int i = 5; i < a.size(); i += 2) props.setProperty(a.get(i), a.get(i+1));
if (!a.get(2).isEmpty()) props.setProperty("user", a.get(2));
if (!a.get(3).isEmpty()) props.setProperty("password", a.get(3));
connection = driver.connect(url, props);
if (connection == null) throw new UnsupportedUrl();
if (Boolean.parseBoolean(a.get(4))) {
try { connection.setReadOnly(true); }
catch (SQLException | UnsupportedOperationException e) {
throw new ReadOnlyUnavailable();
}
}
var m = connection.getMetaData();
header(out, "version", "quote");
row(out, m.getDatabaseProductName() + " " + m.getDatabaseProductVersion(), m.getIdentifierQuoteString());
}
static String pattern(DatabaseMetaData m, String literal) throws SQLException {
String escape = m.getSearchStringEscape();
if (escape == null || escape.isEmpty()) return literal;
return literal.replace(escape, escape + escape).replace("%", escape + "%").replace("_", escape + "_");
}
void schemas(DataOutputStream out) throws Exception {
var m = connection.getMetaData();
header(out, "schema");
Set<String> names = new TreeSet<>();
try (ResultSet rs = m.getSchemas()) {
while (rs.next() && names.size() < 20000) {
String s = rs.getString("TABLE_SCHEM");
if (s != null && !s.isEmpty()) names.add(s);
}
} catch (SQLFeatureNotSupportedException ignored) {}
catalogs = names.isEmpty();
namespaceKnown = true;
if (catalogs) {
try (ResultSet rs = m.getCatalogs()) {
while (rs.next() && names.size() < 20000) {
String s = rs.getString(1);
if (s != null && !s.isEmpty()) names.add(s);
}
} catch (SQLFeatureNotSupportedException ignored) {}
}
if (names.isEmpty()) names.add("");
for (String s : names) row(out, s);
}
void discoverNamespace() throws Exception {
if (!namespaceKnown) schemas(new DataOutputStream(OutputStream.nullOutputStream()));
}
void metadata(String op, List<String> a, DataOutputStream out) throws Exception {
discoverNamespace();
var m = connection.getMetaData();
String name = a.get(0);
String catalog = catalogs && !name.isEmpty() ? name : connection.getCatalog();
String schema = catalogs || name.isEmpty() ? null : pattern(m, name);
if (op.equals("tables")) {
header(out, "name", "kind");
try (ResultSet rs = m.getTables(catalog, schema, "%", null)) {
int n = 0;
while (rs.next() && n < 20000) {
String type = rs.getString("TABLE_TYPE").toLowerCase(Locale.ROOT);
if (!Set.of("table","base table","view","materialized view","system table","local temporary","foreign table").contains(type)) continue;
row(out, rs.getString("TABLE_NAME"), type);
n++;
}
}
} else {
header(out, "name", "type", "nullable", "default", "primary");
String table = a.get(1);
Set<String> keys = new HashSet<>();
try (ResultSet rs = m.getPrimaryKeys(catalog, catalogs || name.isEmpty() ? null : name, table)) {
while (rs.next()) keys.add(rs.getString("COLUMN_NAME"));
} catch (SQLFeatureNotSupportedException ignored) {}
try (ResultSet rs = m.getColumns(catalog, schema, pattern(m, table), "%")) {
int n = 0;
while (rs.next() && n < 20000) {
if (!table.equals(rs.getString("TABLE_NAME"))) continue;
String col = rs.getString("COLUMN_NAME");
row(out, col, rs.getString("TYPE_NAME"), rs.getInt("NULLABLE") == 0 ? "0" : "1",
rs.getString("COLUMN_DEF"), keys.contains(col) ? "1" : "0");
n++;
}
}
}
}
void execute(Work work, List<String> a, DataOutputStream out, boolean tablePage) throws Exception {
long skip = Long.parseLong(a.get(1));
int limit = Integer.parseInt(a.get(2));
try (Statement st = connection.createStatement()) {
long window = skip + limit + 1;
if (tablePage && window > 0 && window <= Integer.MAX_VALUE) {
try { st.setMaxRows((int)window); } catch (SQLException | UnsupportedOperationException ignored) {}
}
work.begin(st);
if (!st.execute(a.get(0))) {
header(out);
end(out, false, st.getUpdateCount());
return;
}
try (ResultSet rs = st.getResultSet()) {
var m = rs.getMetaData();
int cols = m.getColumnCount();
out.writeInt(cols);
for (int c = 1; c <= cols; c++) { text(out, m.getColumnLabel(c)); text(out, m.getColumnTypeName(c)); }
while (skip > 0) {
if (!rs.next()) { end(out, false, -1); return; }
skip--;
}
int n = 0;
while (n < limit && rs.next()) {
out.writeBoolean(true);
for (int c = 1; c <= cols; c++) {
int t = m.getColumnType(c);
if (t == Types.BINARY || t == Types.VARBINARY || t == Types.LONGVARBINARY || t == Types.BLOB) {
byte[] b = rs.getBytes(c);
if (b != null && b.length > (LIMIT - out.size()) / 2) throw new IOException("JDBC binary value exceeds the result limit");
text(out, b == null ? null : "0x" + HexFormat.of().formatHex(b));
} else {
text(out, rs.getString(c));
}
}
n++;
}
end(out, n == limit && rs.next(), -1);
}
}
}
// Only the query worker uses the connection. The reader may cancel its current statement.
static final class Work {
final long id;
private Statement statement;
private boolean cancelled;
Work(long id) { this.id = id; }
synchronized void begin(Statement st) throws SQLException {
if (cancelled) throw new SQLException("Cancelled");
statement = st;
}
void cancel() {
Statement st;
synchronized (this) {
cancelled = true;
st = statement;
}
if (st != null) {
try { st.cancel(); } catch (SQLException | UnsupportedOperationException ignored) {}
}
}
}
static List<String> readFields(DataInputStream in, int count) throws IOException {
if (count < 1 || count > 8192) throw new IOException("Invalid JDBC field count");
int remaining = LIMIT - Long.BYTES - Integer.BYTES;
var fields = new ArrayList<String>(count);
for (int i = 0; i < count; i++) {
remaining -= Integer.BYTES;
int n = in.readInt();
if (n < 0 || n > remaining) throw new IOException("Invalid JDBC request length");
byte[] bytes = in.readNBytes(n);
if (bytes.length != n) throw new EOFException();
fields.add(new String(bytes, StandardCharsets.UTF_8));
remaining -= n;
}
return fields;
}
ByteArrayOutputStream reply(Work work, List<String> a) throws IOException {
var buffer = new ByteArrayOutputStream();
var reply = new DataOutputStream(buffer);
String op = a.remove(0);
try {
reply.writeBoolean(true);
switch (op) {
case "open" -> open(a, reply);
case "schemas" -> schemas(reply);
case "tables", "columns" -> metadata(op, a, reply);
case "namespace" -> {
header(reply, "namespace");
String name = null;
try {
discoverNamespace();
name = catalogs ? connection.getCatalog() : connection.getSchema();
} catch (SQLException | AbstractMethodError ignored) {}
row(reply, name);
}
case "page" -> execute(work, a, reply, true);
case "query" -> {
if (a.size() == 3 || a.get(3).isEmpty()) {
execute(work, a, reply, false);
} else {
discoverNamespace();
String previous = catalogs ? connection.getCatalog() : connection.getSchema();
String wanted = a.get(3);
if (Objects.equals(previous, wanted)) {
execute(work, a, reply, false);
} else {
try {
if (catalogs) connection.setCatalog(wanted); else connection.setSchema(wanted);
if (!Objects.equals(wanted, catalogs ? connection.getCatalog() : connection.getSchema()))
throw new SQLException("The JDBC driver cannot switch to the selected schema");
execute(work, a, reply, false);
} finally {
try {
if (catalogs) connection.setCatalog(previous); else connection.setSchema(previous);
} catch (SQLException restoreError) {
connection.close();
throw restoreError;
}
}
}
}
}
default -> throw new IOException("Unknown JDBC operation");
}
if (!op.equals("query") && !op.equals("page")) end(reply, false, -1);
} catch (Exception | LinkageError e) {
buffer = new ByteArrayOutputStream();
reply = new DataOutputStream(buffer);
reply.writeBoolean(false);
if ((e instanceof ClassNotFoundException || e instanceof NoClassDefFoundError)
&& e.getMessage() != null && e.getMessage().matches("[A-Za-z0-9_.$/]+")) {
text(reply, "JDBC class " + e.getMessage() + " was not found. Check the driver class and include its dependency JARs.");
} else if (e instanceof ReadOnlyUnavailable) {
text(reply, "The JDBC driver rejected Read-only. Check the driver settings and database account privileges.");
} else if (e instanceof UnsupportedUrl) {
text(reply, "The selected JDBC driver does not accept this URL");
} else if (op.equals("open")) {
// Login exceptions may contain properties or credentials embedded in a vendor URL.
String state = e instanceof SQLException ? ((SQLException)e).getSQLState() : null;
text(reply, "JDBC connection failed (" + e.getClass().getSimpleName()
+ (state == null ? "" : ", SQLState " + state) + "). Check driver files, class, URL and credentials.");
} else {
text(reply, e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage());
}
}
return buffer;
}
synchronized void send(ByteArrayOutputStream reply) throws IOException {
output.writeInt(reply == null ? 0 : reply.size());
if (reply != null) reply.writeTo(output);
output.flush();
}
void run() throws IOException {
System.setOut(System.err);
var active = new AtomicReference<Work>();
var worker = Executors.newSingleThreadExecutor(r -> {
var thread = new Thread(r, "jdbc-session");
thread.setDaemon(true);
return thread;
});
try {
for (;;) {
long id;
try { id = input.readLong(); } catch (EOFException eof) { return; }
int count = input.readInt();
if (count == 0) {
var work = active.get();
if (work != null && work.id == id) work.cancel();
send(null); // Acknowledge even a cancel that raced with a completed request.
continue;
}
var fields = readFields(input, count);
var work = new Work(id);
if (!active.compareAndSet(null, work)) throw new IOException("Overlapping JDBC requests");
worker.execute(() -> {
try {
var result = reply(work, fields);
active.compareAndSet(work, null);
send(result);
} catch (Throwable fatal) {
// Without a complete frame the parent must discard this session.
Runtime.getRuntime().halt(1);
}
});
}
} finally {
worker.shutdownNow();
}
}
public static void main(String[] args) throws Exception {
var bridge = new OpenIdeaJdbc();
try { bridge.run(); }
finally { if (bridge.connection != null) bridge.connection.close(); }
}
}
+129
Переглянути файл
@@ -0,0 +1,129 @@
package ai.openidea.jdbc;
import java.io.*;
import java.lang.reflect.Proxy;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.sql.*;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
/** Drives the bridge over its actual pipes with a deterministic JDBC driver. */
public class SelfTest {
public static class Fixture implements Driver {
private boolean readonly;
private int changes;
private Path started;
@SuppressWarnings("unchecked")
static <T> T proxy(Class<T> type, java.lang.reflect.InvocationHandler handler) {
return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[]{type}, handler);
}
public Connection connect(String url, Properties props) {
String path = url.substring("jdbc:fixture:".length());
started = path.isEmpty() ? null : Path.of(path);
var meta = proxy(DatabaseMetaData.class, (p, m, a) -> switch (m.getName()) {
case "getDatabaseProductName" -> "Fixture";
case "getDatabaseProductVersion" -> "1";
case "getIdentifierQuoteString" -> "\"";
default -> throw new SQLFeatureNotSupportedException();
});
return proxy(Connection.class, (p, m, a) -> switch (m.getName()) {
case "setReadOnly" -> { readonly = (boolean) a[0]; yield null; }
case "getMetaData" -> meta;
case "close" -> null;
case "createStatement" -> statement();
default -> throw new SQLFeatureNotSupportedException();
});
}
Statement statement() {
var stop = new CountDownLatch(1);
return proxy(Statement.class, (p, m, a) -> switch (m.getName()) {
case "execute" -> {
String sql = (String) a[0];
if (sql.equals("wait") || sql.equals("ignore cancel")) {
if (started != null) java.nio.file.Files.writeString(started, "started");
System.err.println("statement started");
if (sql.equals("ignore cancel")) Thread.sleep(60_000);
if (!stop.await(20, TimeUnit.SECONDS)) throw new SQLException("test timed out");
throw new SQLException("statement cancelled");
}
if (sql.equals("write") && readonly) throw new SQLException("read-only");
changes++;
yield false;
}
case "cancel" -> { stop.countDown(); yield null; }
case "getUpdateCount" -> changes;
case "close" -> null;
default -> throw new SQLFeatureNotSupportedException();
});
}
public boolean acceptsURL(String url) { return true; }
public DriverPropertyInfo[] getPropertyInfo(String url, Properties p) { return new DriverPropertyInfo[0]; }
public int getMajorVersion() { return 1; }
public int getMinorVersion() { return 0; }
public boolean jdbcCompliant() { return false; }
public Logger getParentLogger() { return Logger.getGlobal(); }
}
static void send(DataOutputStream out, long id, String... fields) throws IOException {
out.writeLong(id);
out.writeInt(fields.length);
for (String s : fields) {
byte[] b = s.getBytes(StandardCharsets.UTF_8);
out.writeInt(b.length);
out.write(b);
}
out.flush();
}
static byte[] reply(DataInputStream in) throws IOException {
int size = in.readInt();
assert size >= 0 && size <= OpenIdeaJdbc.LIMIT;
byte[] bytes = new byte[size];
in.readFully(bytes);
return bytes;
}
public static void main(String[] args) throws Exception {
var boundary = new DataOutputStream(OutputStream.nullOutputStream());
OpenIdeaJdbc.text(boundary, "x".repeat(OpenIdeaJdbc.LIMIT - 14));
OpenIdeaJdbc.end(boundary, false, -1);
assert boundary.size() == OpenIdeaJdbc.LIMIT;
try {
OpenIdeaJdbc.text(boundary, "");
throw new AssertionError("Oversized reply accepted");
} catch (IOException expected) {}
var java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
var child = new ProcessBuilder(java, "-cp", System.getProperty("java.class.path"),
OpenIdeaJdbc.class.getName()).start();
try (var out = new DataOutputStream(child.getOutputStream());
var in = new DataInputStream(child.getInputStream());
var log = child.errorReader()) {
send(out, 1, "open", Fixture.class.getName(), "jdbc:fixture:", "", "", "true");
assert reply(in)[0] == 1;
send(out, 2, "query", "write", "0", "2");
assert reply(in)[0] == 0;
send(out, 3, "query", "first", "0", "2");
assert reply(in)[0] == 1;
send(out, 4, "query", "wait", "0", "2");
assert log.lines().anyMatch("statement started"::equals);
send(out, 3); // A late Cancel for the previous request cannot stop this one.
assert reply(in).length == 0;
send(out, 4);
var first = reply(in);
var second = reply(in);
assert (first.length == 0) != (second.length == 0);
assert (first.length == 0 ? second : first)[0] == 0;
send(out, 5, "query", "after cancel", "0", "2");
var result = reply(in);
assert result[0] == 1 && result[result.length - 1] == 2;
} finally {
child.destroyForcibly().waitFor();
}
}
}
+2 -12
Переглянути файл
@@ -214,15 +214,6 @@ pub(crate) fn settings_get(window: Window) -> Settings {
ide_host::ops::project::settings_get(&state.host, window.label())
}
/// Defaults plus the global layer, without any project's values: what new
/// projects (and projects without their own value) get.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn settings_get_global(state: State<'_, AppState>) -> Settings {
state.host.with_proxy_password(state.global_settings.effective())
}
pub(crate) fn settings_removed_theme(window: Window) -> Option<String> {
let state = window.state::<AppState>();
state.note_ipc();
@@ -258,7 +249,7 @@ fn settings_set_now(
) -> IdeResult<Settings> {
let applied = ide_host::ops::project::set_settings(&state.host, window, scope, key, value)?;
if key == "mcpServer" || key.starts_with("mcpServer.") {
crate::commands::mcp::apply(state);
state.host.mcp.apply(&state.host);
}
if !applied.project_scope {
state.updates.wake.notify_one();
@@ -319,7 +310,7 @@ pub async fn settings_import(window: Window, state: State<'_, AppState>, path: P
tauri::async_runtime::spawn(async move { lsp.reconfigure().await });
}
crate::commands::ssh::apply_ssh_settings(&state);
crate::commands::mcp::apply(&state);
state.host.mcp.apply(&state.host);
state.host.apply_proxy();
state.updates.wake.notify_one();
state.sink.emit(ide_core::IdeEvent::SettingsChanged { key: String::new() });
@@ -415,7 +406,6 @@ ide_command::desktop_domain!(
remove_recent_project,
set_recent_project_groups,
settings_export,
settings_get_global,
settings_import,
settings_list_jetbrains_ides,
settings_read_jetbrains,
+7 -2
Переглянути файл
@@ -3,13 +3,18 @@
use crate::state::AppState;
use ide_command::desktop_command;
use ide_core::{DebugSessionId, IdeResult};
use ide_dap::HotReloadReason;
use tauri::State;
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub async fn debug_hot_reload(state: State<'_, AppState>, session: DebugSessionId) -> IdeResult<()> {
ide_host::ops::debug::debug_hot_reload(&state.host, session).await
pub async fn debug_hot_reload(
state: State<'_, AppState>,
session: DebugSessionId,
reason: HotReloadReason,
) -> IdeResult<()> {
ide_host::ops::debug::debug_hot_reload(&state.host, session, reason).await
}
#[desktop_command(trust = trusted)]
-257
Переглянути файл
@@ -1,257 +0,0 @@
//! Agents › MCP Server: runs `ide_mcp::McpServer` over built-in host tools
//! while `mcpServer.enabled` is on, and reports where it listens.
use crate::state::AppState;
use ide_command::desktop_command;
use ide_core::{IdeResult, IpcPath};
use parking_lot::Mutex;
use serde::Serialize;
use specta::Type;
use std::net::IpAddr;
use std::path::PathBuf;
use std::sync::Arc;
use tauri::{State, Window};
/// The server while it runs, or why it doesn't.
#[derive(Default)]
pub struct McpService {
server: Mutex<Option<ide_mcp::McpServer>>,
/// The port and token settings the running server was started with.
running_with: Mutex<Option<Listen>>,
error: Mutex<Option<String>>,
}
/// What the address, port and token settings ask the server for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Listen {
/// `mcpServer.address`.
address: IpAddr,
/// `mcpServer.port` with `mcpServer.fixedPort`; otherwise a free port.
port: Option<u16>,
fixed_token: bool,
}
/// Starts, stops or restarts the server to match the global `mcpServer` settings: `enabled`,
/// and the address, port and token it listens with.
pub fn apply(state: &AppState) {
let settings = state.global_settings.effective().mcp_server;
let mut server = state.mcp.server.lock();
if !settings.enabled {
let was_running = server.take();
let stopped = was_running.is_some();
if let Some(running) = was_running {
running.stop();
}
*state.mcp.running_with.lock() = None;
ide_agent::set_mcp_executable(None);
state.host.set_mcp_executable(None);
*state.mcp.error.lock() = None;
drop(server);
if stopped {
for project in state.host.projects() {
project.agents.notify_mcp_servers_changed();
}
}
return;
}
let Ok(address) = settings.address.trim().parse::<IpAddr>() else {
if let Some(running) = server.take() {
running.stop();
}
*state.mcp.running_with.lock() = None;
*state.mcp.error.lock() =
Some(format!("the listen address `{}` is not an IP address", settings.address.trim()));
return;
};
let wanted = Listen {
address,
port: settings.fixed_port.then_some(settings.port).filter(|p| *p != 0),
fixed_token: settings.fixed_token,
};
if server.is_some() && *state.mcp.running_with.lock() == Some(wanted) {
return;
}
// Another address, port or token: clients connect anew.
if let Some(running) = server.take() {
let held = (running.address(), running.port());
running.stop();
if let Some(port) = port_to_wait_for(held, wanted.port) {
wait_until_free(address, port);
}
}
let token = if wanted.fixed_token {
match ide_mcp::kept_token(&ide_mcp::token_path(&state.data_dir)) {
Ok(token) => Some(token),
Err(e) => {
tracing::warn!("MCP server: cannot keep the token ({e}); using a new one for this run");
None
}
}
} else {
None
};
let discovery = ide_mcp::discovery_path(&state.data_dir);
match ide_mcp::McpServer::start_with(
Arc::new(ide_host::mcp::Registry::new(state.host.clone())),
Some(discovery),
&state.host.runtime,
ide_mcp::ServerOptions { address: Some(address), port: wanted.port, token },
) {
Ok(started) => {
let exe = std::env::current_exe().unwrap_or_default();
state.host.set_mcp_executable(Some(exe.clone()));
ide_agent::set_mcp_executable(Some(exe));
*server = Some(started);
*state.mcp.running_with.lock() = Some(wanted);
*state.mcp.error.lock() = None;
drop(server);
for project in state.host.projects() {
project.agents.notify_mcp_servers_changed();
}
}
Err(e) => {
tracing::warn!("MCP server: {e}");
*state.mcp.running_with.lock() = None;
*state.mcp.error.lock() = Some(e.to_string());
}
}
}
/// The port a restart listening on `wanted` waits for after stopping the server that listened
/// on `held`: only its own, at any address (`127.0.0.1` and `0.0.0.0` overlap). A port another
/// program holds (the run fell back to a free one) stays taken, and waiting for it would block
/// the window.
fn port_to_wait_for(held: (IpAddr, u16), wanted: Option<u16>) -> Option<u16> {
wanted.filter(|port| held.1 == *port)
}
/// Waits briefly for a stopped server's port to close, so the restart gets it again.
fn wait_until_free(address: IpAddr, port: u16) {
for _ in 0..100 {
if std::net::TcpListener::bind((address, port)).is_ok() {
return;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
/// Stops the server on exit (its discovery file goes with it).
pub fn stop(state: &AppState) {
state.host.set_mcp_executable(None);
ide_agent::set_mcp_executable(None);
if let Some(server) = state.mcp.server.lock().take() {
server.stop();
}
*state.mcp.running_with.lock() = None;
}
/// What Settings › Agents › MCP Server shows.
#[derive(Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct McpServerStatus {
pub running: bool,
/// Why it isn't running though turned on.
pub error: Option<String>,
/// The address listened on (`0.0.0.0` / `::`: every address).
pub address: Option<String>,
pub port: Option<u16>,
/// Why the fixed port (`mcpServer.port`) isn't the one listened on: it was in use or
/// reserved, so a free port was taken for this run.
pub port_unavailable: Option<String>,
/// The window's local project, which the URL and command below are for.
pub project: Option<IpcPath>,
/// `http://<address>:<port>/mcp?project=<root>`, with loopback for every address.
pub url: Option<String>,
/// Bearer token of `url` (changes with every run unless `mcpServer.fixedToken` is on).
pub token: Option<String>,
/// The stdio bridge: this executable and its arguments.
pub stdio_command: Vec<String>,
}
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub fn mcp_server_status(window: Window, state: State<'_, AppState>) -> IdeResult<McpServerStatus> {
let root: Option<PathBuf> = state.project(window.label()).ok().map(|p| p.root.clone());
let server = state.mcp.server.lock();
let exe = std::env::current_exe().unwrap_or_default();
Ok(McpServerStatus {
running: server.is_some(),
error: state.mcp.error.lock().clone(),
address: server.as_ref().map(|s| s.address().to_string()),
port: server.as_ref().map(|s| s.port()),
port_unavailable: server.as_ref().and_then(|s| s.port_unavailable().map(str::to_owned)),
url: server.as_ref().zip(root.as_ref()).map(|(s, r)| s.url(r)),
token: server.as_ref().map(|s| s.token().to_owned()),
stdio_command: root.as_ref().map(|r| ide_mcp::stdio_command(&exe, r)).unwrap_or_default(),
project: root.map(IpcPath::from),
})
}
/// Settings › Agents › MCP Server › Regenerate Token: forgets the kept token, and restarts the
/// server with a new one. Clients configured with the old token stop working.
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub fn mcp_regenerate_token(state: State<'_, AppState>) -> IdeResult<()> {
match std::fs::remove_file(ide_mcp::token_path(&state.data_dir)) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
*state.mcp.running_with.lock() = None;
apply(&state);
Ok(())
}
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub fn mcp_ui_ready(window: Window, state: State<'_, AppState>, ready: bool) -> IdeResult<()> {
state.project(window.label())?;
state.host.mcp_requests.set_ready(window.label(), ready);
Ok(())
}
/// The user closed the Run tool window tab of an agent command (`run_command`).
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub fn mcp_agent_run_closed(window: Window, state: State<'_, AppState>, name: String) -> IdeResult<()> {
let project = state.project(window.label())?;
state.host.mcp_agent_runs.closed(&project.root, &name);
Ok(())
}
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub fn mcp_respond(
window: Window,
state: State<'_, AppState>,
id: u32,
allow: bool,
error: Option<String>,
) -> IdeResult<()> {
state.host.mcp_requests.answer(window.label(), id, allow, error)
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::Ipv4Addr;
#[test]
fn a_restart_waits_only_for_the_port_the_stopped_server_held() {
let local = IpAddr::V4(Ipv4Addr::LOCALHOST);
let any = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
assert_eq!(port_to_wait_for((local, 64342), Some(64342)), Some(64342));
// Another address on the same port overlaps the old listener: wait for it too.
assert_eq!(port_to_wait_for((any, 64342), Some(64342)), Some(64342));
// The fixed port was taken by another program: the server ran on a free one.
assert_eq!(port_to_wait_for((local, 51234), Some(64342)), None);
assert_eq!(port_to_wait_for((local, 64342), None), None);
}
}
ide_command::desktop_domain!(mcp_agent_run_closed, mcp_regenerate_token, mcp_respond, mcp_server_status, mcp_ui_ready,);
-2
Переглянути файл
@@ -23,7 +23,6 @@ pub mod github;
pub mod hotkeys;
pub mod http;
pub mod lsp;
pub mod mcp;
pub mod nav;
pub mod notification;
pub mod perf;
@@ -207,7 +206,6 @@ fn catalogue() -> (tauri_specta::Commands<tauri::Wry>, Vec<Command>) {
desktop hotkeys;
desktop http;
desktop lsp;
desktop mcp;
desktop nav;
desktop notification;
desktop perf;
+5 -2
Переглянути файл
@@ -240,7 +240,10 @@ pub fn run() {
let menu_state = menu::MenuState::default();
menu::install(app.handle(), &menu_state, &state.recent.list());
app.manage(state);
commands::mcp::apply(&app.state::<AppState>());
{
let state = app.state::<AppState>();
state.host.mcp.apply(&state.host);
}
#[cfg(windows)]
if let Err(error) = windows::allow_external_launches(app.handle()) {
windows::report_cli_error(app.handle(), error);
@@ -348,7 +351,7 @@ pub fn run() {
windows::flush_auxiliary_geometry(app);
if let Some(state) = app.try_state::<AppState>() {
state.host.stop_processes_on_exit();
commands::mcp::stop(&state);
state.host.mcp.stop(&state.host);
state.host.clear_workspace_edit_history_on_exit();
state.host.shutdown_notebooks_on_exit();
}
+9 -1
Переглянути файл
@@ -223,6 +223,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
vec![
act("file.newProject", "Project…"),
act("workspace.create", "Workspace…"),
act("vcs.cloneProject", "Project from Version Control…"),
SEP,
act("file.new", "File…"),
act("file.newScratchFile", "Scratch File"),
@@ -2014,7 +2015,14 @@ mod tests {
};
assert_eq!(
action_ids(new),
["file.newProject", "workspace.create", "file.new", "file.newScratchFile", "file.newUntitled"],
[
"file.newProject",
"workspace.create",
"vcs.cloneProject",
"file.new",
"file.newScratchFile",
"file.newUntitled"
],
"{os:?}"
);
}
+20 -7
Переглянути файл
@@ -222,18 +222,25 @@ struct ClientHandler {
app: AppHandle,
window: String,
channels: Channels,
connection: Arc<std::sync::OnceLock<std::sync::Weak<Connection>>>,
}
impl Handler for ClientHandler {
fn on_notification(&self, method: &str, params: Value) {
match method {
"event" => match serde_json::from_value::<EventMessage>(params) {
Ok(m) if ide_host::rpc::client_accepts(&m.event) => {
// The server's windows are this window.
let _ = m.window;
TauriSink { app: self.app.clone(), window: Some(self.window.clone()) }.emit(m.event);
Ok(m) => {
let trusted = self
.connection
.get()
.and_then(std::sync::Weak::upgrade)
.is_some_and(|c| c.trusted_here(&self.app.state::<AppState>().host.trust) == Some(true));
if ide_host::rpc::client_accepts(&m.event, trusted) {
// The server's windows are this window.
let _ = m.window;
TauriSink { app: self.app.clone(), window: Some(self.window.clone()) }.emit(m.event);
}
}
Ok(_) => {}
Err(e) => tracing::warn!("remote event: {e}"),
},
// Plugin code of this window's project runs on the server.
@@ -506,8 +513,13 @@ pub async fn remote_connect(
progress(RemoteStage::Connecting, None);
let label = AppState::owner_window(window.label()).to_owned();
let channels: Channels = Arc::default();
let handler =
Arc::new(ClientHandler { app: window.app_handle().clone(), window: label.clone(), channels: channels.clone() });
let connection_slot: Arc<std::sync::OnceLock<std::sync::Weak<Connection>>> = Arc::default();
let handler = Arc::new(ClientHandler {
app: window.app_handle().clone(),
window: label.clone(),
channels: channels.clone(),
connection: connection_slot.clone(),
});
let tail = crate::remote_wsl::Tail::default();
let mut exec = None;
let (peer, session, host, title_tag) = match &target {
@@ -597,6 +609,7 @@ pub async fn remote_connect(
web_forwards: Mutex::new(Vec::new()),
exec,
});
let _ = connection_slot.set(Arc::downgrade(&connection));
if let RemoteTarget::DevContainer { folder, config } = &target {
forward_configured_ports(&connection, folder, config).await;
}
-3
Переглянути файл
@@ -19,8 +19,6 @@ pub struct AppState {
pub recent: RecentProjects,
/// Plugins (`ide_host::plugins`), shared by all windows.
pub plugins: Arc<ide_host::plugins::PluginHost>,
/// Agents › MCP Server: built-in IDE tools for agents.
pub mcp: crate::commands::mcp::McpService,
/// Credential prompts of `ssh` / `git` child processes (`None` if it failed to start).
pub askpass: Option<ide_ssh::askpass::AskpassServer>,
/// Remote development connections, by window label.
@@ -107,7 +105,6 @@ impl AppState {
askpass: start_askpass(&app),
sink: global_sink,
plugins: crate::commands::plugin::create_host(&app, &data_dir, &host)?,
mcp: Default::default(),
remote_dev: crate::remote_dev::Connections::default(),
host,
startup: Startup {
+14 -6
Переглянути файл
@@ -89,6 +89,7 @@ coverage_import always project_host bin
coverage_prepare trusted project_host bindings async
cucumber_sources trusted desktop bindings async
db_apply_edits trusted project_host bindings async
db_approve_jdbc_source trusted project_host bindings sync
db_completion trusted project_host bindings async
db_connect trusted project_host bindings async
db_connected trusted project_host bindings sync
@@ -106,10 +107,14 @@ db_explain trusted project_host bin
db_export_file always desktop bindings async
db_finish_transaction trusted project_host bindings async
db_history trusted project_host bindings async
db_jdbc_driver_classes trusted project_host bindings async
db_jdbc_drivers trusted project_host bindings sync
db_object_ddl trusted project_host bindings async
db_remove_history trusted project_host bindings async
db_remove_jdbc_driver trusted project_host bindings sync
db_retain_catalog trusted project_host bindings async
db_run_tool trusted desktop bindings async
db_save_jdbc_driver trusted project_host bindings sync
db_save_sources trusted project_host bindings async
db_saved_catalog trusted project_host bindings async
db_schema_objects trusted project_host bindings async
@@ -242,6 +247,9 @@ find_files always project_host bin
find_files_named always project_host bindings async
find_symbols always project_host bindings async
find_symbols_named always project_host bindings async
flutter_daemon_restart trusted project_host bindings sync
flutter_devices trusted project_host bindings sync
flutter_devices_refresh trusted project_host bindings sync
fs_compare_directories always project_host bindings async
fs_copy always project_host bindings async
fs_copy_merge always project_host bindings async
@@ -363,14 +371,14 @@ maven_dependency_completion trusted project_host bin
maven_dependency_declaration trusted project_host bindings async
maven_exclude_dependency trusted project_host bindings async
maven_goto_declaration trusted project_host bindings async
mcp_agent_run_closed trusted desktop bindings sync
mcp_regenerate_token trusted desktop bindings sync
mcp_agent_run_closed trusted project_host bindings sync
mcp_regenerate_token outside_restricted project_host bindings sync
mcp_report_problems trusted project_host bindings sync
mcp_respond trusted desktop bindings sync
mcp_server_status trusted desktop bindings sync
mcp_respond trusted project_host bindings sync
mcp_server_status outside_restricted project_host bindings sync
mcp_set_focused_editor trusted project_host bindings sync
mcp_set_open_editors trusted project_host bindings sync
mcp_ui_ready trusted desktop bindings sync
mcp_ui_ready trusted project_host bindings sync
menu_configure always desktop bindings sync
menu_model always desktop bindings sync
menu_refresh always desktop bindings sync
@@ -565,7 +573,7 @@ search_validate always project_host bin
set_recent_project_groups always desktop bindings sync
settings_export always desktop bindings async
settings_get always project_host bindings sync
settings_get_global always desktop bindings sync
settings_get_global always project_host bindings sync
settings_import always desktop bindings async
settings_list_jetbrains_ides always desktop bindings async
settings_read_jetbrains always desktop bindings async
+96 -6
Переглянути файл
@@ -286,6 +286,7 @@ export const commands = {
/** Cucumber feature files and step definition files, for step navigation. */
cucumberSources: () => typedError<StepSource[], IdeError>(__TAURI_INVOKE("cucumber_sources")),
dbApplyEdits: (id: string, schema: string, table: string, edits: DbRowEdit[]) => typedError<number | null, IdeError>(__TAURI_INVOKE("db_apply_edits", { id, schema, table, edits })),
dbApproveJdbcSource: (source: DataSource_Deserialize) => typedError<null, IdeError>(__TAURI_INVOKE("db_approve_jdbc_source", { source })),
dbCompletion: (id: string) => typedError<DbCompletion, IdeError>(__TAURI_INVOKE("db_completion", { id })),
dbConnect: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_connect", { id })),
dbConnected: () => typedError<string[], IdeError>(__TAURI_INVOKE("db_connected")),
@@ -310,14 +311,18 @@ export const commands = {
dbExportFile: (path: string, text: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_export_file", { path, text })),
dbFinishTransaction: (id: string, commit: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("db_finish_transaction", { id, commit })),
dbHistory: (id: string) => typedError<DbHistoryEntry[], IdeError>(__TAURI_INVOKE("db_history", { id })),
dbJdbcDriverClasses: (jars: string[]) => typedError<string[], IdeError>(__TAURI_INVOKE("db_jdbc_driver_classes", { jars })),
dbJdbcDrivers: () => typedError<DbJdbcDriver[], IdeError>(__TAURI_INVOKE("db_jdbc_drivers")),
dbObjectDdl: (id: string, schema: string, kind: DbObjectKind, name: string) => typedError<string, IdeError>(__TAURI_INVOKE("db_object_ddl", { id, schema, kind, name })),
dbRemoveHistory: (id: string, texts: string[] | null) => typedError<null, IdeError>(__TAURI_INVOKE("db_remove_history", { id, texts })),
dbRemoveJdbcDriver: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_remove_jdbc_driver", { id })),
dbRetainCatalog: (id: string, databases: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("db_retain_catalog", { id, databases })),
/**
* Runs `job` against target `id` and streams the tool's output; returns its exit code. Stays
* in the desktop shell like [`db_export_file`]: the paths in `job` are local.
*/
dbRunTool: (request: RequestId, id: string, executable: string, job: DbToolJob, onOutput: Channel<DbToolLine[]>) => typedError<number | null, IdeError>(__TAURI_INVOKE("db_run_tool", { request, id, executable, job, onOutput })),
dbSaveJdbcDriver: (driver: DbJdbcDriver) => typedError<null, IdeError>(__TAURI_INVOKE("db_save_jdbc_driver", { driver })),
dbSaveSources: (sources: DataSource_Deserialize[]) => typedError<null, IdeError>(__TAURI_INVOKE("db_save_sources", { sources })),
dbSavedCatalog: (id: string) => typedError<{
databases?: DbCatalogDatabase[],
@@ -381,7 +386,7 @@ export const commands = {
} | null, IdeError>(__TAURI_INVOKE("debug_heap_path", { snapshot, object })),
/** Copies the snapshot's dump to `path`, replacing a file there. */
debugHeapSave: (snapshot: HeapSnapshotId, path: IpcPath) => typedError<null, IdeError>(__TAURI_INVOKE("debug_heap_save", { snapshot, path })),
debugHotReload: (session: DebugSessionId) => typedError<null, IdeError>(__TAURI_INVOKE("debug_hot_reload", { session })),
debugHotReload: (session: DebugSessionId, reason: HotReloadReason) => typedError<null, IdeError>(__TAURI_INVOKE("debug_hot_reload", { session, reason })),
debugHotRestart: (session: DebugSessionId) => typedError<null, IdeError>(__TAURI_INVOKE("debug_hot_restart", { session })),
/** Breakpoints of a debugged page on DOM events and on requests (js-debug). */
debugJsCustomBreakpoints: (session: DebugSessionId, ids: string[], xhr: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("debug_js_custom_breakpoints", { session, ids, xhr })),
@@ -597,6 +602,15 @@ export const commands = {
findSymbols: (query: string, filter: SymbolFilter, limit: number) => typedError<SymbolMatch[], IdeError>(__TAURI_INVOKE("find_symbols", { query, filter, limit })),
/** Index symbols named exactly one of `names` inside `within` (an agent task's folder). */
findSymbolsNamed: (names: string[], within: IpcPath) => typedError<SymbolMatch[], IdeError>(__TAURI_INVOKE("find_symbols_named", { names, within })),
/** Replaces the project's `flutter daemon`, after a failure or an SDK change. */
flutterDaemonRestart: () => typedError<FlutterDeviceList, IdeError>(__TAURI_INVOKE("flutter_daemon_restart")),
/**
* The project's Flutter devices, starting its `flutter daemon` on first use. Changes arrive as
* `IdeEvent::FlutterDevices`.
*/
flutterDevices: () => typedError<FlutterDeviceList, IdeError>(__TAURI_INVOKE("flutter_devices")),
/** Looks at adb again, for Android devices Flutter doesn't report (awaiting authorization, offline). */
flutterDevicesRefresh: () => typedError<null, IdeError>(__TAURI_INVOKE("flutter_devices_refresh")),
fsCompareDirectories: (left: string, right: string, request: RequestId, onProgress: Channel<DirectoryCompareProgress>) => typedError<DirectoryCompareEntry[], IdeError>(__TAURI_INVOKE("fs_compare_directories", { left, right, request, onProgress })),
fsCopy: (from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_copy", { from, to })),
fsCopyMerge: (sourceRoot: string, destinationRoot: string, path: string, overwrite: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("fs_copy_merge", { sourceRoot, destinationRoot, path, overwrite })),
@@ -947,7 +961,7 @@ export const commands = {
/** The user closed the Run tool window tab of an agent command (`run_command`). */
mcpAgentRunClosed: (name: string) => typedError<null, IdeError>(__TAURI_INVOKE("mcp_agent_run_closed", { name })),
/**
* Settings › Agents › MCP Server › Regenerate Token: forgets the kept token, and restarts the
* Settings › Agents › IDE MCP Server › Regenerate Token: forgets the kept token, and restarts the
* server with a new one. Clients configured with the old token stop working.
*/
mcpRegenerateToken: () => typedError<null, IdeError>(__TAURI_INVOKE("mcp_regenerate_token")),
@@ -4113,6 +4127,8 @@ export type DataSource_Deserialize = {
id?: string,
name?: string,
driver?: DbDriver,
/** An app-wide driver profile id; classpaths never come from a project. */
jdbcDriver?: string,
host?: string,
port?: number | null,
database?: string,
@@ -4157,6 +4173,8 @@ export type DataSource_Serialize = {
id: string,
name: string,
driver: DbDriver,
/** An app-wide driver profile id; classpaths never come from a project. */
jdbcDriver?: string,
host: string,
port: number | null,
database: string,
@@ -4288,7 +4306,7 @@ export type DbDriver = "sqlite" | "postgres" |
/** Microsoft SQL Server. */
"sqlServer" | "clickhouse" |
/** Oracle Database (pure-Rust thin driver, no client library). */
"oracle" | "snowflake";
"oracle" | "snowflake" | "jdbc";
export type DbDumpContent = "all" | "schemaOnly" | "dataOnly";
@@ -4358,6 +4376,14 @@ export type DbIntrospection = {
objectFilter?: string,
};
export type DbJdbcDriver = {
id: string,
name: string,
jars: string[],
className: string,
urlTemplate: string,
};
export type DbMysqlOptions = {
/** Empty: the databases the dump names. */
database: string,
@@ -4731,6 +4757,11 @@ export type DebugEvent =
* changed and can be reloaded), `STARTING`, `END`, `WARNING` or `ERROR`.
*/
{ kind: "hotCodeReplace"; changeType: string; message: string } |
/**
* `flutter debug_adapter`'s `flutter.appStarted` event (launch and attach): the session is
* a Flutter app that can take a hot reload now. The plain Dart adapter never sends it.
*/
{ kind: "flutterAppStarted" } |
/** The session's capabilities changed after it started: fetch them again. */
{ kind: "capabilities" } |
/**
@@ -4769,6 +4800,8 @@ export type DebuggerSettings = {
skipLibraryCode?: boolean,
/** JavaScript: debugging a dev server (`vite`, `next dev`) also opens its page in a browser session. */
debugServerPage?: boolean,
/** Flutter: saving a Dart file of a running debug session hot reloads the app. */
flutterHotReloadOnSave?: boolean,
python?: PythonDebuggerSettings,
};
@@ -6082,6 +6115,34 @@ export type FilesChanged = {
removed: string[],
};
/** See [`FlutterDeviceList`]. */
export type FlutterDaemonStatus = { kind: "stopped" } |
/** Started; the first device discovery has not finished. */
{ kind: "starting" } | { kind: "ready" } |
/** No `flutter` executable on the search path. */
{ kind: "notInstalled" } |
/** The daemon could not start or exited: what it printed last. It is not restarted on its own. */
{ kind: "failed"; message: string };
/** A target `flutter run -d <id>` can name, or an Android device adb sees but Flutter can't use yet. */
export type FlutterDevice = {
id: string,
name: string,
/** `android`, `ios`, `macos`, `web`, … */
platformType: string | null,
/** `mobile`, `desktop` or `web`. */
category: string | null,
emulator: boolean,
/** The adb state keeping it from being used (`unauthorized`, `offline`, …). */
unavailable: string | null,
};
/** The project's Flutter devices, best default first. */
export type FlutterDeviceList = {
status: FlutterDaemonStatus,
devices: FlutterDevice[],
};
export type FocusedEditor = {
path: IpcPath,
/** Zero-based lines and UTF-16 columns, end exclusive. */
@@ -6385,6 +6446,8 @@ export type GoSettings = {
goroot?: string,
/** Empty = `go env GOPATH`. */
gopath?: string,
/** Format with gofumpt, a stricter gofmt (gopls `gofumpt`). */
gofumpt?: boolean,
buildTags?: GoBuildTags,
modules?: GoModules,
};
@@ -6743,6 +6806,9 @@ export type HistoryKind =
*/
"label";
/** What triggered a hot reload; `flutter debug_adapter` takes it as `reason`. */
export type HotReloadReason = "manual" | "save";
/** Result of [`DebugManager::redefine_classes`]. */
export type HotSwapResult = {
/** Fully qualified names of the classes reloaded (empty: nothing had changed). */
@@ -6849,6 +6915,8 @@ export type IdeEvent =
* from changed and it can be reloaded.
*/
{ type: "direnv"; root: IpcPath; status: DirenvStatus } |
/** The project's `flutter daemon` changed state, or a device came or went. */
{ type: "flutterDevices"; list: FlutterDeviceList } |
/** Files or directories changed on disk (after debouncing, ignore rules applied). */
{ type: "fsChanged"; created: IpcPath[]; modified: IpcPath[]; removed: IpcPath[];
/** Subtrees whose ignore rules changed, after the matchers were rebuilt. */
@@ -8394,7 +8462,7 @@ export type McpServerSettings = {
fixedToken?: boolean,
};
/** What Settings › Agents › MCP Server shows. */
/** What Settings › Agents › IDE MCP Server shows. */
export type McpServerStatus = {
running: boolean,
/** Why it isn't running though turned on. */
@@ -8407,13 +8475,13 @@ export type McpServerStatus = {
* reserved, so a free port was taken for this run.
*/
portUnavailable: string | null,
/** The window's local project, which the URL and command below are for. */
/** The window's project, which the URL and command below are for. */
project: IpcPath | null,
/** `http://<address>:<port>/mcp?project=<root>`, with loopback for every address. */
url: string | null,
/** Bearer token of `url` (changes with every run unless `mcpServer.fixedToken` is on). */
token: string | null,
/** The stdio bridge: this executable and its arguments. */
/** The stdio bridge: this host's executable and its arguments. */
stdioCommand: string[],
};
@@ -10834,6 +10902,8 @@ export type Settings_Deserialize = {
* options on top of the language definition, or a server defined here.
*/
languageServers?: { [key in string]: LanguageServerSettings_Deserialize },
/** Tools › Download sources: a mirror prefix for the release archives the installer fetches. */
toolDownloads?: ToolDownloadSettings,
/** Editor › Inspections profiles. */
inspections?: InspectionSettings,
/** Editor › Natural Languages › Spelling. */
@@ -10906,6 +10976,8 @@ export type Settings_Serialize = {
* options on top of the language definition, or a server defined here.
*/
languageServers: { [key in string]: LanguageServerSettings_Serialize },
/** Tools › Download sources: a mirror prefix for the release archives the installer fetches. */
toolDownloads: ToolDownloadSettings,
/** Editor › Inspections profiles. */
inspections: InspectionSettings,
/** Editor › Natural Languages › Spelling. */
@@ -11687,6 +11759,24 @@ export type ToolCallDisplay =
/** Each call on its own line. */
"each";
/**
* Tools › Download sources: a mirror the installer tries when `github.com` is slow or
* unreachable.
*
* The mirror is a proxy prefix: the official URL is appended to it unchanged
* (`https://mirror.example/https://github.com/o/r/releases/download/…`), which is what the
* public GitHub proxies speak. Only `github.com` downloads are affected — those proxies
* hard-code that host, so Eclipse JDT LS and Open VSX keep their official addresses. Empty by
* default, so every download stays on its official host until the user opts in.
*/
export type ToolDownloadSettings = {
/**
* Proxy prefix prepended to `https://github.com/…` archive addresses only; empty keeps
* every download on its official host.
*/
githubMirror?: string,
};
/** UI-facing state of one tool. */
export type ToolInfo = {
/** Server / adapter name from `languages/*.toml`. */
+44
Переглянути файл
@@ -370,6 +370,46 @@
font-size: var(--fs-small);
color: var(--fg-muted);
}
.jdbcJars {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: var(--space-2);
}
.jdbcJars ul {
width: 100%;
max-height: 160px;
overflow: auto;
margin: 0;
padding: 0;
list-style: none;
}
.jdbcJars li {
display: flex;
align-items: center;
gap: var(--space-2);
}
.jdbcJars li span {
flex: 1;
min-width: 0;
overflow-wrap: anywhere;
}
.jdbcDetails {
grid-column: 1 / -1;
margin: 0;
}
.jdbcDetails dt {
margin-top: var(--space-2);
color: var(--fg-secondary);
}
.jdbcDetails dd {
margin: var(--space-1) 0;
overflow-wrap: anywhere;
}
.jdbcDetails ul {
margin: 0;
padding-left: var(--space-4);
}
.formFull {
grid-column: 1 / -1;
}
@@ -1479,3 +1519,7 @@
.dumpError {
color: var(--danger);
}
.jdbcJarPath {
overflow-wrap: anywhere;
}
+345
Переглянути файл
@@ -0,0 +1,345 @@
import { useEffect, useState } from "react";
import { call, commands, type DbJdbcDriver } from "@/platform/ipc";
import { useTx } from "@/platform/i18n";
import { Button, Dialog, IconButton, Input, Select, T } from "@/ui";
import { baseName } from "./dumpTools";
import { newSourceId } from "./model";
import styles from "./Database.module.css";
export function useJdbcDrivers(enabled: boolean) {
const [drivers, setDrivers] = useState<DbJdbcDriver[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [attempt, setAttempt] = useState(0);
const [wasEnabled, setWasEnabled] = useState(enabled);
if (wasEnabled !== enabled) {
setWasEnabled(enabled);
setDrivers(null);
setError(null);
}
useEffect(() => {
if (!enabled) return;
let active = true;
void call(commands.dbJdbcDrivers()).then(
(value) => {
if (active) setDrivers(value);
},
(e: unknown) => {
if (active) setError(e instanceof Error ? e.message : String(e));
},
);
return () => {
active = false;
};
}, [enabled, attempt]);
const retry = () => {
setDrivers(null);
setError(null);
setAttempt((n) => n + 1);
};
return { drivers, setDrivers, error, retry };
}
const blankDriver = (): DbJdbcDriver => ({ id: newSourceId(), name: "", jars: [], className: "", urlTemplate: "" });
export function JdbcDriverProfiles({
drivers,
selected,
onSave,
onUse,
onRemove,
onClose,
}: {
drivers: DbJdbcDriver[];
selected: string;
onSave: (driver: DbJdbcDriver) => void;
onUse?: (driver: DbJdbcDriver) => void;
onRemove: (id: string) => void;
onClose: () => void;
}) {
const tx = useTx();
const [selection, setSelection] = useState(
drivers.some((d) => d.id === selected) ? selected : (drivers[0]?.id ?? ""),
);
const [draft, setDraft] = useState<DbJdbcDriver | null>(null);
const [confirm, setConfirm] = useState<"trust" | "delete" | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [classes, setClasses] = useState<string[]>([]);
const current = drivers.find((d) => d.id === selection);
const name = current?.name ?? "";
const set = (patch: Partial<DbJdbcDriver>) => setDraft((d) => d && { ...d, ...patch });
const classValid =
!!draft && /^[\p{L}_$][\p{L}\p{N}_$]*(?:\.[\p{L}_$][\p{L}\p{N}_$]*)+$/u.test(draft.className.trim());
const templateValid = !draft?.urlTemplate || /^jdbc:[^\s:]+:[^\r\n]*$/.test(draft.urlTemplate);
const valid = !!draft?.name.trim() && !!draft.jars.length && classValid && templateValid;
const edit = (driver: DbJdbcDriver) => {
setError(null);
setClasses([]);
setDraft({ ...driver, jars: [...driver.jars] });
};
const pickJars = async () => {
setBusy(true);
setError(null);
try {
const { open } = await import("@/platform/dialog");
const files = await open({
title: tx("Choose JDBC Driver and Dependency JARs"),
multiple: true,
directory: false,
filters: [{ name: tx("Java archives"), extensions: ["jar"] }],
});
if (files && draft) {
const jars = [...new Set([...draft.jars, ...files])];
set({ jars });
const names = await call(commands.dbJdbcDriverClasses(jars));
setClasses(names);
if (!draft.className && names.length) set({ className: names[0] });
}
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setBusy(false);
}
};
const save = async () => {
if (!draft || !valid || busy) return;
setBusy(true);
setError(null);
const driver = { ...draft, name: draft.name.trim(), className: draft.className.trim() };
try {
await call(commands.dbSaveJdbcDriver(driver));
onSave(driver);
setSelection(driver.id);
setDraft(null);
setConfirm(null);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
setConfirm(null);
} finally {
setBusy(false);
}
};
const remove = async () => {
if (!current || busy) return;
setBusy(true);
setError(null);
try {
await call(commands.dbRemoveJdbcDriver(current.id));
onRemove(current.id);
setSelection(drivers.find((d) => d.id !== current.id)?.id ?? "");
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
} finally {
setConfirm(null);
setBusy(false);
}
};
return (
<>
<Dialog
open
title={
draft
? drivers.some((d) => d.id === draft.id)
? "Edit JDBC Driver"
: "Add JDBC Driver"
: "JDBC Driver Profiles"
}
onClose={() => {
if (busy) return;
if (draft) setDraft(null);
else onClose();
}}
width={640}
buttons={
draft
? [
{ label: "Cancel", role: "cancel", disabled: busy },
{ label: "Save", role: "default", disabled: busy || !valid, onClick: () => setConfirm("trust") },
]
: [
{ label: "Close", role: "cancel", disabled: busy },
...(onUse && current
? [{ label: "Use Driver", role: "default" as const, onClick: () => onUse(current) }]
: []),
]
}
>
<div className={styles.form}>
<p className={styles.formFull}>
<T>Driver profiles are stored locally and shared by all projects.</T>
</p>
{draft ? (
<>
<label className={styles.formLabel} htmlFor="jdbc-driver-name">
<T>Name:</T>
</label>
<Input
id="jdbc-driver-name"
value={draft.name}
disabled={busy}
onChange={(e) => set({ name: e.target.value })}
/>
<span className={styles.formLabel}>
<T>Driver and dependency JARs:</T>
</span>
<div className={styles.jdbcJars}>
<ul aria-label={tx("Driver and dependency JARs")}>
{draft.jars.map((jar) => (
<li key={jar}>
<span title={jar}>{baseName(jar)}</span>
<IconButton
icon="close"
aria-label={tx`Remove JAR ${jar}`}
disabled={busy}
onClick={() => {
setClasses([]);
set({ jars: draft.jars.filter((path) => path !== jar) });
}}
/>
</li>
))}
</ul>
<Button icon="plus" disabled={busy} onClick={() => void pickJars()}>
<T>Add JARs…</T>
</Button>
</div>
<label className={styles.formLabel} htmlFor="jdbc-driver-class">
<T>Driver class:</T>
</label>
<Input
id="jdbc-driver-class"
list="jdbc-driver-providers"
mono
value={draft.className}
disabled={busy}
invalid={!!draft.className && !classValid}
onChange={(e) => set({ className: e.target.value })}
/>
<span />
<span className={styles.formHint}>
<datalist id="jdbc-driver-providers">
{classes.map((name) => (
<option key={name} value={name} />
))}
</datalist>
<T>Select a class declared by the JARs, or enter its fully qualified name.</T>
</span>
<label className={styles.formLabel} htmlFor="jdbc-url-template">
<T>URL template:</T>
</label>
<Input
id="jdbc-url-template"
mono
value={draft.urlTemplate}
disabled={busy}
invalid={!templateValid}
onChange={(e) => set({ urlTemplate: e.target.value })}
/>
<span />
<span className={styles.formHint}>
<T>{"Use {host}, {port}, {database} or {file} for fields on the connection form."}</T>
</span>
</>
) : (
<>
<span className={styles.formLabel}>
<T>JDBC driver profile:</T>
</span>
<Select
aria-label="JDBC driver profiles"
value={selection}
options={drivers.map((d) => ({ value: d.id, label: d.name, verbatim: true }))}
placeholder="No JDBC driver profiles"
onChange={setSelection}
/>
<span />
<div className={styles.formRow}>
<Button icon="plus" onClick={() => edit(blankDriver())}>
<T>Add…</T>
</Button>
<Button disabled={!current} onClick={() => current && edit(current)}>
<T>Edit…</T>
</Button>
<Button disabled={!current} onClick={() => setConfirm("delete")}>
<T>Delete…</T>
</Button>
</div>
{current && (
<dl className={styles.jdbcDetails}>
<dt>
<T>Driver class:</T>
</dt>
<dd>{current.className}</dd>
<dt>
<T>URL template:</T>
</dt>
<dd>{current.urlTemplate}</dd>
<dt>
<T>Driver and dependency JARs:</T>
</dt>
<dd>
<ul>
{current.jars.map((jar) => (
<li key={jar} title={jar}>
{baseName(jar)}
</li>
))}
</ul>
</dd>
</dl>
)}
</>
)}
{error && (
<div className={`${styles.formFull} ${styles.bad}`} role="alert">
{error}
</div>
)}
</div>
</Dialog>
{confirm && (
<Dialog
open
title={confirm === "trust" ? "Trust JDBC Driver?" : "Delete JDBC Driver?"}
onClose={() => {
if (!busy) setConfirm(null);
}}
width={520}
buttons={[
{ label: "Cancel", role: "cancel", disabled: busy, autoFocus: true },
{
label: confirm === "trust" ? "Trust and Save" : "Delete",
role: "default",
disabled: busy,
onClick: () => void (confirm === "trust" ? save() : remove()),
},
]}
>
<div className={styles.form}>
<p className={styles.formFull}>
{confirm === "trust"
? tx(
"JDBC drivers and their dependency JARs execute local code with your user permissions when connecting. Only import JARs from a source you trust.",
)
: tx`Delete driver profile ${name}? Data sources using it will need another driver profile.`}
</p>
{confirm === "trust" && (
<ul className={styles.formFull}>
{draft?.jars.map((jar) => (
<li key={jar} className={styles.jdbcJarPath}>
{jar}
</li>
))}
</ul>
)}
</div>
</Dialog>
)}
</>
);
}
+333
Переглянути файл
@@ -0,0 +1,333 @@
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DataSource, DbJdbcDriver } from "@/platform/ipc";
import { SourceDialog } from "./SourceDialog";
import { JdbcDriverProfiles } from "./JdbcDriverProfiles";
import { newMenu, nodeMenu } from "./treeMenu";
import { useDatabase } from "./store";
const backend = vi.hoisted(() => ({ call: vi.fn(), saveSource: vi.fn(), pick: vi.fn() }));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
const request =
(name: string) =>
(...args: unknown[]) => [name, ...args];
return {
...real,
call: backend.call,
commands: {
...real.commands,
dbJdbcDrivers: request("list"),
dbJdbcDriverClasses: request("classes"),
dbApproveJdbcSource: request("approve"),
dbSaveJdbcDriver: request("save"),
dbRemoveJdbcDriver: request("remove"),
dbTest: request("test"),
},
};
});
vi.mock("./store", async (importOriginal) => ({
...(await importOriginal<typeof import("./store")>()),
saveSource: backend.saveSource,
}));
vi.mock("@/platform/dialog", () => ({ open: backend.pick }));
const driver: DbJdbcDriver = {
id: "example-driver",
name: "Example JDBC",
jars: ["/local/example-driver.jar", "/local/dependency.jar"],
className: "org.example.jdbc.Driver",
urlTemplate: "jdbc:example://<host>:<port>/<database>",
};
function select(label: string, option: string) {
fireEvent.click(screen.getByRole("button", { name: label }));
fireEvent.click(within(screen.getByRole("listbox")).getByText(option, { exact: true }));
}
beforeEach(() => {
vi.clearAllMocks();
backend.call.mockImplementation(async ([command]: [string]) =>
command === "list" ? [driver] : command === "classes" ? [] : "Example database",
);
backend.saveSource.mockResolvedValue(undefined);
backend.pick.mockResolvedValue(driver.jars);
useDatabase.setState({ sources: [], dialog: null, loaded: true });
});
describe("custom JDBC data sources", () => {
it("expands the selected profile's URL template for testing and saving, and keeps a manual URL editable", async () => {
const first = { ...driver, urlTemplate: "jdbc:example://{host}:{port}/{database}" };
const second = { ...driver, id: "duck", name: "DuckDB", urlTemplate: "jdbc:duckdb:{file}" };
backend.call.mockImplementation(async ([op]) => (op === "list" ? [first, second] : "OK"));
render(<SourceDialog initial={null} preset={{ driver: "jdbc" }} />);
await waitFor(() => expect(screen.getByRole("button", { name: "JDBC driver profile" })).toBeEnabled());
select("JDBC driver profile", first.name);
const test = screen.getByRole("button", { name: "Test Connection" });
expect(test).toBeDisabled();
fireEvent.change(screen.getByLabelText("Host:"), { target: { value: "localhost" } });
fireEvent.change(screen.getByLabelText("Port:"), { target: { value: "5433" } });
fireEvent.change(screen.getByLabelText("Database:"), { target: { value: "sample" } });
expect(screen.getByLabelText("URL:")).toHaveValue("jdbc:example://localhost:5433/sample");
fireEvent.click(test);
await screen.findByText("Succeeded: OK");
expect(backend.call).toHaveBeenCalledWith([
"test",
expect.objectContaining({ url: "jdbc:example://localhost:5433/sample" }),
null,
null,
]);
select("JDBC driver profile", second.name);
fireEvent.change(screen.getByLabelText("File:"), { target: { value: "/tmp/example.db" } });
expect(screen.getByLabelText("URL:")).toHaveValue("jdbc:duckdb:/tmp/example.db");
fireEvent.change(screen.getByLabelText("URL:"), { target: { value: "jdbc:duckdb:" } });
expect(screen.queryByLabelText("File:")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Use URL template" }));
fireEvent.click(screen.getByRole("button", { name: "OK" }));
await waitFor(() =>
expect(backend.saveSource).toHaveBeenCalledWith(
expect.objectContaining({ url: "jdbc:duckdb:/tmp/example.db" }),
undefined,
undefined,
),
);
});
it("tests a read-only JDBC source and preserves the option on save", async () => {
render(
<SourceDialog initial={{ driver: "jdbc", jdbcDriver: driver.id, url: "jdbc:example:local", readOnly: true }} />,
);
const test = screen.getByRole("button", { name: "Test Connection" });
await waitFor(() => expect(test).toBeEnabled());
fireEvent.click(test);
await waitFor(() =>
expect(backend.call).toHaveBeenCalledWith(["test", expect.objectContaining({ readOnly: true }), null, null]),
);
fireEvent.click(screen.getByRole("tab", { name: "Options" }));
expect(screen.getByRole("checkbox", { name: "Read-only" })).toBeChecked();
fireEvent.click(screen.getByRole("button", { name: "OK" }));
await waitFor(() =>
expect(backend.saveSource).toHaveBeenCalledWith(
expect.objectContaining({ readOnly: true }),
undefined,
undefined,
),
);
});
it("offers Custom JDBC in the new data source menu", () => {
const dataSource = newMenu().find((item) => "label" in item && item.label === "Data Source");
expect(dataSource && "submenu" in dataSource && dataSource.submenu).toEqual(
expect.arrayContaining([expect.objectContaining({ label: "Custom JDBC" })]),
);
});
it("requires a profile and explicit URL, and keeps driver code out of source configuration", async () => {
render(<SourceDialog initial={null} preset={{ driver: "jdbc" }} />);
await waitFor(() => expect(screen.getByRole("button", { name: "JDBC driver profile" })).toBeEnabled());
const test = screen.getByRole("button", { name: "Test Connection" });
expect(test).toBeDisabled();
select("JDBC driver profile", driver.name);
expect(screen.getByLabelText("URL:")).toHaveValue(driver.urlTemplate);
expect(screen.getByLabelText("URL:")).toHaveAttribute("placeholder", driver.urlTemplate);
expect(test).toBeDisabled();
expect(screen.queryByRole("tab", { name: "SSH/SSL" })).toBeNull();
expect(screen.queryByLabelText("Host:")).toBeNull();
fireEvent.change(screen.getByLabelText("URL:"), { target: { value: "https://example.invalid" } });
expect(test).toBeDisabled();
const url = "jdbc:example://example.invalid/catalog?ssl=true&setting=a%20b";
fireEvent.change(screen.getByLabelText("URL:"), { target: { value: url } });
fireEvent.change(screen.getByLabelText("User:"), { target: { value: "reader" } });
fireEvent.change(screen.getByLabelText("Password:"), { target: { value: "typed secret" } });
fireEvent.click(screen.getByRole("tab", { name: "Options" }));
expect(screen.queryByRole("button", { name: "Transaction control" })).toBeNull();
expect(screen.queryByLabelText("Time zone:")).toBeNull();
expect(screen.queryByLabelText("Startup script:")).toBeNull();
fireEvent.click(screen.getByRole("tab", { name: "Advanced" }));
fireEvent.click(screen.getByRole("button", { name: "Add Property" }));
fireEvent.change(screen.getByLabelText("Property name"), { target: { value: "ssl" } });
fireEvent.change(screen.getByLabelText("Property value"), { target: { value: "true" } });
fireEvent.click(test);
await screen.findByText("Succeeded: Example database");
const request = backend.call.mock.calls.find(([request]) => request[0] === "test")![0];
expect(request).toEqual([
"test",
expect.objectContaining({
driver: "jdbc",
jdbcDriver: driver.id,
url,
user: "reader",
properties: [{ name: "ssl", value: "true" }],
}),
"typed secret",
null,
]);
for (const key of ["jars", "className", "classpath", "exec", "password"])
expect(request[1]).not.toHaveProperty(key);
fireEvent.click(screen.getByRole("button", { name: "OK" }));
await waitFor(() =>
expect(backend.saveSource).toHaveBeenCalledWith(
expect.objectContaining({ driver: "jdbc", jdbcDriver: driver.id, url }),
"typed secret",
undefined,
),
);
});
it("keeps an existing password unchanged and blocks a missing driver profile", async () => {
render(<SourceDialog initial={{ driver: "jdbc", jdbcDriver: "missing", url: "jdbc:example:local" }} />);
await screen.findByText("The JDBC driver profile is missing. Select or add a profile before connecting.");
expect(screen.getByRole("button", { name: "OK" })).toBeDisabled();
expect(screen.getByLabelText("Password:")).toHaveAttribute("placeholder", "<unchanged>");
select("JDBC driver profile", driver.name);
fireEvent.click(screen.getByRole("button", { name: "OK" }));
await waitFor(() => expect(backend.saveSource).toHaveBeenCalledWith(expect.anything(), undefined, undefined));
});
it("requires explicit security configuration after switching from native ClickHouse and restores native settings", async () => {
const source: DataSource = {
driver: "clickhouse",
name: "Secure native",
host: "example.invalid",
ssl: "verifyFull",
sslCaFile: "/local/ca.pem",
sslCertFile: "/local/client.pem",
sslKeyFile: "/local/client.key",
urlOnly: true,
url: "https://example.invalid:8443/default",
properties: [{ name: "max_threads", value: "2" }],
};
render(<SourceDialog initial={source} />);
select("Data source type", "Custom JDBC");
await waitFor(() => expect(screen.getByRole("button", { name: "JDBC driver profile" })).toBeEnabled());
select("JDBC driver profile", driver.name);
expect(screen.getByLabelText("URL:")).toHaveValue(driver.urlTemplate);
fireEvent.change(screen.getByLabelText("URL:"), { target: { value: "jdbc:example://example.invalid?ssl=true" } });
expect(screen.getByRole("button", { name: "Test Connection" })).toBeDisabled();
fireEvent.click(screen.getByRole("tab", { name: "Advanced" }));
expect(screen.queryByLabelText("Property name")).toBeNull();
fireEvent.click(screen.getByRole("tab", { name: "General" }));
fireEvent.click(screen.getByRole("checkbox", { name: "I have configured JDBC connection security." }));
expect(screen.getByRole("button", { name: "Test Connection" })).toBeEnabled();
select("Data source type", "ClickHouse");
expect(screen.getByLabelText("URL:")).toHaveValue(source.url!);
fireEvent.click(screen.getByRole("button", { name: "Test Connection" }));
await waitFor(() =>
expect(backend.call).toHaveBeenCalledWith(["test", expect.objectContaining(source), null, null]),
);
});
it("shows driver-list failures and retries without allowing a connection", async () => {
backend.call.mockRejectedValueOnce(new Error("Cannot read local profiles"));
render(<SourceDialog initial={null} preset={{ driver: "jdbc" }} />);
await screen.findByText("Cannot read local profiles");
expect(screen.getByRole("button", { name: "Test Connection" })).toBeDisabled();
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Manage Drivers…" })).toBeEnabled());
});
it("hides vendor-specific editing from JDBC tree nodes", () => {
useDatabase.setState({ sources: [{ id: "jdbc-source", driver: "jdbc" }] });
const menu = nodeMenu({ kind: "schema", id: "jdbc-source", key: "schema", schema: "PUBLIC" });
expect(menu).not.toEqual(expect.arrayContaining([expect.objectContaining({ action: "db.drop" })]));
expect(menu).not.toEqual(expect.arrayContaining([expect.objectContaining({ action: "db.compareSchemas" })]));
});
});
describe("local JDBC driver profiles", () => {
it("validates profiles, selects dependency JARs and requires trust before saving", async () => {
const saved = vi.fn();
render(<JdbcDriverProfiles drivers={[]} selected="" onSave={saved} onRemove={vi.fn()} onClose={vi.fn()} />);
fireEvent.click(screen.getByRole("button", { name: "Add…" }));
expect(
screen.getByText("Use {host}, {port}, {database} or {file} for fields on the connection form."),
).toBeVisible();
const save = screen.getByRole("button", { name: "Save" });
expect(save).toBeDisabled();
fireEvent.change(screen.getByLabelText("Name:"), { target: { value: "Example JDBC" } });
fireEvent.change(screen.getByLabelText("Driver class:"), { target: { value: "Driver" } });
fireEvent.click(screen.getByRole("button", { name: "Add JARs…" }));
await screen.findByTitle(driver.jars[1]!);
expect(backend.pick).toHaveBeenCalledWith(
expect.objectContaining({ multiple: true, filters: [{ name: "Java archives", extensions: ["jar"] }] }),
);
expect(save).toBeDisabled();
fireEvent.change(screen.getByLabelText("Driver class:"), { target: { value: driver.className } });
fireEvent.change(screen.getByLabelText("URL template:"), { target: { value: driver.urlTemplate } });
fireEvent.click(save);
const trust = screen.getByRole("dialog", { name: "Trust JDBC Driver?" });
expect(trust).toHaveTextContent("execute local code with your user permissions");
for (const jar of driver.jars) expect(within(trust).getByText(jar)).toBeVisible();
expect(backend.call.mock.calls.some(([[command]]) => command === "save")).toBe(false);
fireEvent.click(within(trust).getByRole("button", { name: "Cancel" }));
expect(saved).not.toHaveBeenCalled();
fireEvent.click(save);
fireEvent.click(screen.getByRole("button", { name: "Trust and Save" }));
await waitFor(() => expect(saved).toHaveBeenCalledWith({ ...driver, id: expect.any(String) }));
});
it("edits and deletes profiles through IPC and invalidates a deleted source reference", async () => {
render(<SourceDialog initial={{ driver: "jdbc", jdbcDriver: driver.id, url: "jdbc:example:local" }} />);
await waitFor(() => expect(screen.getByRole("button", { name: "Manage Drivers…" })).toBeEnabled());
fireEvent.click(screen.getByRole("button", { name: "Manage Drivers…" }));
fireEvent.click(screen.getByRole("button", { name: "Edit…" }));
fireEvent.change(within(screen.getByRole("dialog", { name: "Edit JDBC Driver" })).getByLabelText("Name:"), {
target: { value: "Renamed driver" },
});
fireEvent.click(screen.getByRole("button", { name: "Save" }));
fireEvent.click(screen.getByRole("button", { name: "Trust and Save" }));
await waitFor(() => expect(backend.call).toHaveBeenCalledWith(["save", { ...driver, name: "Renamed driver" }]));
await screen.findByRole("dialog", { name: "JDBC Driver Profiles" });
fireEvent.click(screen.getByRole("button", { name: "Delete…" }));
expect(screen.getByRole("dialog", { name: "Delete JDBC Driver?" })).toHaveTextContent(
"Data sources using it will need another driver profile.",
);
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
await waitFor(() => expect(backend.call).toHaveBeenCalledWith(["remove", driver.id]));
fireEvent.click(within(screen.getByRole("dialog", { name: "JDBC Driver Profiles" })).getByText("Close"));
await screen.findByText("The JDBC driver profile is missing. Select or add a profile before connecting.");
expect(screen.getByRole("button", { name: "OK" })).toBeDisabled();
});
it("keeps a failed profile edit available for correction and retry", async () => {
const saved = vi.fn();
backend.call.mockRejectedValueOnce(new Error("Driver JAR cannot be read"));
render(
<JdbcDriverProfiles
drivers={[driver]}
selected={driver.id}
onSave={saved}
onRemove={vi.fn()}
onClose={vi.fn()}
/>,
);
fireEvent.click(screen.getByRole("button", { name: "Edit…" }));
fireEvent.click(screen.getByRole("button", { name: "Save" }));
fireEvent.click(screen.getByRole("button", { name: "Trust and Save" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Driver JAR cannot be read");
expect(screen.getByLabelText("Driver class:")).toHaveValue(driver.className);
expect(saved).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Save" }));
fireEvent.click(screen.getByRole("button", { name: "Trust and Save" }));
await waitFor(() => expect(saved).toHaveBeenCalledWith(driver));
});
it("deduplicates picked JARs and lets users remove a dependency", async () => {
backend.pick.mockResolvedValue([driver.jars[0], driver.jars[1], driver.jars[0]]);
render(
<JdbcDriverProfiles
drivers={[driver]}
selected={driver.id}
onSave={vi.fn()}
onRemove={vi.fn()}
onClose={vi.fn()}
/>,
);
fireEvent.click(screen.getByRole("button", { name: "Edit…" }));
fireEvent.click(screen.getByRole("button", { name: "Add JARs…" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Add JARs…" })).toBeEnabled());
expect(screen.getAllByTitle(driver.jars[0]!)).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: `Remove JAR ${driver.jars[1]}` }));
expect(screen.queryByTitle(driver.jars[1]!)).toBeNull();
});
});
+1
Переглянути файл
@@ -388,6 +388,7 @@ function DropDatabaseDialog({ id, database }: { id: string; database: string })
// ---- Modify Table / New Table -----------------------------------------------
const TYPES: Record<DbDriver, string[]> = {
jdbc: [],
snowflake: [
"NUMBER(38,0)",
"NUMBER(10,2)",
+4 -2
Переглянути файл
@@ -3,6 +3,7 @@
* executed statement with its outcome, and a `Result N` tab per result set —
* a toolbar (re-run, export / copy as CSV, JSON, SQL…), the grid and a floating row count.
*/
import { canModifyTable } from "./objects";
import { copySelectionOnKeyDown } from "@/ui/selectableText";
import {
useCallback,
@@ -325,7 +326,7 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
!!target &&
!!pk &&
!readOnlySource &&
driver !== "clickhouse" &&
canModifyTable(driver) &&
sources.some((s) => s !== null);
// The pending edits belong to the result they were made on: fresh rows (a re-run,
@@ -493,7 +494,8 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
const tablePkCount = detailsValue?.columns.filter((c) => c.primaryKey).length ?? 0;
let notice: string | null = null;
if (!editable) {
if (driver === "clickhouse") notice = tx("Use the query console to change ClickHouse data.");
if (driver === "jdbc") notice = tx("Use the query console to change JDBC data.");
else if (driver === "clickhouse") notice = tx("Use the query console to change ClickHouse data.");
else if (readOnlySource) notice = tx("Read-only data source.");
else if (editability.kind === "readonly") notice = readonlyNotice(editability.reason);
else if (!target) notice = tx("Read-only: the table schema could not be identified in the result database.");
+7 -5
Переглянути файл
@@ -54,11 +54,13 @@ function SidePicker({ label, side, onChange }: { label: string; side: Side; onCh
useEffect(() => {
if (side.id && !useDatabase.getState().schemas[side.id]) void loadSchemas(side.id);
}, [side.id]);
const sourceOptions: SelectOption[] = sources.map((s) => ({
value: s.id ?? "",
label: s.name ?? "",
icon: "database",
}));
const sourceOptions: SelectOption[] = sources
.filter((s) => s.driver !== "jdbc")
.map((s) => ({
value: s.id ?? "",
label: s.name ?? "",
icon: "database",
}));
if (side.id && !sourceOptions.some((o) => o.value === side.id))
sourceOptions.push({ value: side.id, label: targetLabel(side.id), icon: "database" });
const names = schemas?.status === "ok" ? schemas.value : [];
+332 -95
Переглянути файл
@@ -2,7 +2,7 @@
* Data source properties (IDEA's Data Sources and Drivers page): name, colour and
* comment above General / Options / SSH/SSL / Schemas / Advanced tabs, Test Connection.
*/
import { useState, type ReactNode } from "react";
import { Fragment, useState, type ReactNode } from "react";
import {
call,
commands,
@@ -10,6 +10,7 @@ import {
type DataSource,
type DbColor,
type DbIntrospection,
type DbJdbcDriver,
type DbOptions,
type DbProperty,
type DbSnowflake,
@@ -37,6 +38,7 @@ import {
} from "./model";
import { closeDialog, loadDatabases, loadSchemas, saveSource, useDatabase } from "./store";
import { VENDORS, blankSnowflake, sourceUrl, vendorById, vendorOf } from "./vendors";
import { JdbcDriverProfiles, useJdbcDrivers } from "./JdbcDriverProfiles";
import styles from "./Database.module.css";
import { isImeKey } from "@/platform/ime";
@@ -90,6 +92,10 @@ export function snowflakeSecretLabel(auth: DbSnowflakeAuth | null | undefined):
/** Driver property names the Advanced tab suggests, and what the backend does with them. */
const PROPERTIES: Record<string, { names: string[]; hint: string }> = {
jdbc: {
names: [],
hint: "Passed to the JDBC driver as connection properties. Configure TLS and other driver-specific settings here or in the JDBC URL. Use the User and Password fields for credentials.",
},
clickhouse: {
names: ["max_execution_time", "max_threads", "connect_timeout"],
hint: "ClickHouse settings sent with each HTTP request. connect_timeout is in seconds.",
@@ -193,6 +199,7 @@ function blank(): DataSource {
comment: "",
urlOnly: false,
url: "",
jdbcDriver: "",
sslCaFile: "",
sslCertFile: "",
sslKeyFile: "",
@@ -388,6 +395,22 @@ export function SourceDialog({
const [showComment, setShowComment] = useState(!!s.comment);
// The URL being typed in default mode (null: show the fields' URL).
const [urlDraft, setUrlDraft] = useState<string | null>(null);
const [showJdbcProfiles, setShowJdbcProfiles] = useState(false);
const [nativeSource, setNativeSource] = useState<DataSource | null>(null);
const [jdbcSecurityConfirmed, setJdbcSecurityConfirmed] = useState(false);
const jdbc = s.driver === "jdbc";
const jdbcProfiles = useJdbcDrivers(jdbc);
const jdbcProfile = jdbcProfiles.drivers?.find((d) => d.id === s.jdbcDriver);
const reviewJdbcSecurity =
nativeSource &&
(nativeSource.driver === "clickhouse" ||
nativeSource.ssh?.enabled ||
nativeSource.urlOnly ||
["require", "verifyCa", "verifyFull"].includes(nativeSource.ssl ?? "") ||
nativeSource.sslCaFile ||
nativeSource.sslCertFile ||
nativeSource.sslKeyFile ||
(nativeSource.properties?.length ?? 0) > 0);
const loadedDbs = useDatabase((st) => (initial?.id ? st.databases[initial.id] : undefined));
const loadedSchemas = useDatabase((st) => (initial?.id ? st.schemas[initial.id] : undefined));
@@ -421,29 +444,104 @@ export function SourceDialog({
const setSnowflake = (patch: Partial<DbSnowflake>) =>
setS((x) => ({ ...x, snowflake: { ...blankSnowflake(), ...x.snowflake, ...patch } }));
const browserSignIn = snowflake && sf.auth === "browser";
const urlOnly = !sqlite && !!s.urlOnly;
const urlOnly = !sqlite && !jdbc && !!s.urlOnly;
const parsedUrl = urlOnly ? parseSourceUrl(s.url ?? "") : null;
const urlValid = !!parsedUrl && parsedUrl.source.driver === s.driver;
const host = urlOnly ? (parsedUrl?.source.host ?? "") : (s.host ?? "");
const database = urlOnly ? (parsedUrl?.source.database ?? "") : (s.database ?? "");
const name =
s.name?.trim() || (sqlite ? fileSourceName(s.file ?? "") : `${database || s.user || "db"}@${host || "localhost"}`);
s.name?.trim() ||
(jdbc
? (jdbcProfile?.name ?? tx("Custom JDBC"))
: sqlite
? fileSourceName(s.file ?? "")
: `${database || s.user || "db"}@${host || "localhost"}`);
// Snowflake is reached over HTTPS, where a tunnel to another host name cannot pass certificate checks.
const sshOn = !sqlite && !snowflake && !!ssh.enabled;
const valid = sqlite
? !!s.file?.trim()
: (urlOnly ? urlValid : !!s.host?.trim()) &&
(!sshOn || sshTunnelReady(ssh, sshConfigs)) &&
(!snowflake || (!!s.user?.trim() && (sf.auth !== "keyPair" || !!sf.privateKeyFile?.trim())));
const sshOn = !sqlite && !snowflake && !jdbc && !!ssh.enabled;
const template = jdbcProfile?.urlTemplate ?? "";
const templateFields = (["host", "port", "database", "file"] as const).filter((key) => template.includes(`{${key}}`));
const renderedUrl = template.replace(
/\{(host|port|database|file)\}/g,
(token, key: "host" | "port" | "database" | "file") => String(s[key] || token),
);
const fromTemplate = !!templateFields.length && (s.url === template || s.url === renderedUrl);
const jdbcUrl = fromTemplate ? renderedUrl : (s.url ?? "");
const chooseProfile = (profile?: DbJdbcDriver) => {
const wasDefault = !s.url || fromTemplate || s.url === jdbcProfile?.urlTemplate;
set({ jdbcDriver: profile?.id ?? "", url: wasDefault ? (profile?.urlTemplate ?? "") : s.url });
setTest(null);
};
const jdbcUrlValid =
/^jdbc:[^\s:]+:[^\r\n]*$/.test(jdbcUrl) && !/<[^>]+>|\{(?:host|port|database|file)\}/.test(jdbcUrl);
const valid = jdbc
? !!jdbcProfile && jdbcUrlValid && (!reviewJdbcSecurity || jdbcSecurityConfirmed)
: sqlite
? !!s.file?.trim()
: (urlOnly ? urlValid : !!s.host?.trim()) &&
(!sshOn || sshTunnelReady(ssh, sshConfigs)) &&
(!snowflake || (!!s.user?.trim() && (sf.auth !== "keyPair" || !!sf.privateKeyFile?.trim())));
const sslOn = (s.ssl ?? "prefer") !== "disable";
/** What is saved / tested: a preset's port when the field was left empty. */
const effective = (): DataSource => ({ ...s, name, port: s.port ?? (s.vendor ? vendor.port : null) });
const effective = (): DataSource => ({
...s,
name,
port: s.port ?? (s.vendor ? vendor.port : null),
...(jdbc
? {
jdbcDriver: s.jdbcDriver ?? "",
url: jdbcUrl,
urlOnly: true,
ssh: null,
options: { ...options, transaction: "auto" as const },
}
: {}),
});
const setType = (id: string) => {
const v = vendorById(id);
if (!v) return;
setS((x) => {
setTest(null);
setUrlDraft(null);
if (v.driver === "jdbc" && !jdbc) {
setNativeSource(s);
setJdbcSecurityConfirmed(false);
setS({
...s,
driver: "jdbc",
vendor: "",
port: s.port ?? vendor.port,
urlOnly: true,
url: "",
jdbcDriver: "",
properties: [],
options: blankOptions(),
ssh: null,
ssl: "disable",
sslCaFile: "",
sslCertFile: "",
sslKeyFile: "",
});
return;
}
if (v.driver === s.driver && v.id === vendor.id) return;
const previous =
jdbc && nativeSource
? {
...nativeSource,
name: s.name,
color: s.color,
comment: s.comment,
global: s.global,
}
: s;
setNativeSource(null);
if (jdbc && nativeSource && vendorOf(nativeSource).id === v.id) {
setS(previous);
return;
}
setS(() => {
const x = previous;
const old = vendorOf(x);
const port = x.port == null || x.port === old.port ? v.port : x.port;
return {
@@ -492,6 +590,7 @@ export function SourceDialog({
/** Test Connection, or with `tunnel` the SSH/SSL tab's Test SSH Tunnel (no database login). */
const runTest = async (tunnel = false) => {
if (!valid && !tunnel) return;
setBusy(true);
setTest(null);
try {
@@ -519,11 +618,14 @@ export function SourceDialog({
};
const save = async () => {
if (!valid) return;
const dialog = useDatabase.getState().dialog;
setBusy(true);
try {
const source = { ...effective(), properties: properties.filter((p) => p.name?.trim()) };
if (jdbc && !source.global) await call(commands.dbApproveJdbcSource(source));
await saveSource(
{ ...effective(), properties: properties.filter((p) => p.name?.trim()) },
source,
sqlite ? undefined : password === undefined ? undefined : password || null,
!sshOn || sshSecret === undefined || sshUsed.auth === "openSsh" ? undefined : sshSecret || null,
);
@@ -544,7 +646,7 @@ export function SourceDialog({
const tabs: Array<{ id: Tab; label: string }> = [
{ id: "general", label: "General" },
{ id: "options", label: "Options" },
...(sqlite ? [] : snowflake ? [] : [{ id: "ssh" as const, label: "SSH/SSL" }]),
...(sqlite || snowflake || jdbc ? [] : [{ id: "ssh" as const, label: "SSH/SSL" }]),
...(sqlite ? [] : [{ id: "schemas" as const, label: "Schemas" }]),
{ id: "advanced", label: "Advanced" },
];
@@ -568,42 +670,123 @@ export function SourceDialog({
/>
) : (
<>
<span className={styles.formLabel}>
<T>Connection type:</T>
</span>
<div className={styles.segmented} role="group" aria-label={tx("Connection type")}>
<button type="button" aria-pressed={!urlOnly} onClick={() => setUrlOnly(false)}>
<T>default</T>
</button>
<button type="button" aria-pressed={urlOnly} onClick={() => setUrlOnly(true)}>
<T>URL only</T>
</button>
</div>
{!urlOnly && (
{jdbc ? (
<>
<label className={styles.formLabel} htmlFor="db-host">
{tx(snowflake ? "Account:" : "Host:")}
</label>
<span className={styles.formLabel}>
<T>JDBC driver profile:</T>
</span>
<div className={styles.formRow}>
<Input
id="db-host"
<Select
className={styles.fill}
value={s.host ?? ""}
placeholder={snowflake ? "myorg-myaccount or xy12345.eu-central-1" : undefined}
onChange={(e) => set({ host: e.target.value })}
/>
<label className={styles.formLabel} htmlFor="db-port">
<T>Port:</T>
</label>
<Input
id="db-port"
className={styles.portInput}
inputMode="numeric"
value={s.port ?? ""}
placeholder={String(vendor.port ?? "")}
onChange={(e) => set({ port: parsePort(e.target.value) })}
aria-label="JDBC driver profile"
value={s.jdbcDriver ?? ""}
disabled={!jdbcProfiles.drivers}
onChange={(id) => chooseProfile(jdbcProfiles.drivers?.find((d) => d.id === id))}
options={[
{ value: "", label: "Choose a JDBC driver profile" },
...(jdbcProfiles.drivers ?? []).map((d) => ({ value: d.id, label: d.name, verbatim: true })),
...(s.jdbcDriver && !jdbcProfile
? [{ value: s.jdbcDriver, label: tx`${s.jdbcDriver} (missing)` }]
: []),
]}
/>
<Button disabled={!jdbcProfiles.drivers} onClick={() => setShowJdbcProfiles(true)}>
<T>Manage Drivers…</T>
</Button>
</div>
{fromTemplate &&
templateFields.map((key) => (
<Fragment key={key}>
<label className={styles.formLabel} htmlFor={`jdbc-template-${key}`}>
{tx({ host: "Host:", port: "Port:", database: "Database:", file: "File:" }[key])}
</label>
<div className={styles.formRow}>
<Input
id={`jdbc-template-${key}`}
className={styles.fill}
value={s[key] ?? ""}
inputMode={key === "port" ? "numeric" : undefined}
onChange={(e) =>
set({ [key]: key === "port" ? parsePort(e.target.value) : e.target.value, url: template })
}
/>
{key === "file" && (
<Button
onClick={() =>
void pickFile("Database File").then((file) => file && set({ file, url: template }))
}
>
<T>Browse…</T>
</Button>
)}
</div>
</Fragment>
))}
{!fromTemplate && templateFields.length > 0 && (
<>
<span />
<Button onClick={() => set({ url: template })}>
<T>Use URL template</T>
</Button>
</>
)}
{jdbcProfiles.error ? (
<div className={styles.formFull} role="alert">
{jdbcProfiles.error}{" "}
<Button onClick={jdbcProfiles.retry}>
<T>Retry</T>
</Button>
</div>
) : !jdbcProfiles.drivers ? (
<span className={styles.formFull} role="status">
<T>Loading JDBC driver profiles…</T>
</span>
) : s.jdbcDriver && !jdbcProfile ? (
<span className={`${styles.formFull} ${styles.bad}`} role="alert">
<T>The JDBC driver profile is missing. Select or add a profile before connecting.</T>
</span>
) : null}
</>
) : (
<>
<span className={styles.formLabel}>
<T>Connection type:</T>
</span>
<div className={styles.segmented} role="group" aria-label={tx("Connection type")}>
<button type="button" aria-pressed={!urlOnly} onClick={() => setUrlOnly(false)}>
<T>default</T>
</button>
<button type="button" aria-pressed={urlOnly} onClick={() => setUrlOnly(true)}>
<T>URL only</T>
</button>
</div>
{!urlOnly && (
<>
<label className={styles.formLabel} htmlFor="db-host">
{tx(snowflake ? "Account:" : "Host:")}
</label>
<div className={styles.formRow}>
<Input
id="db-host"
className={styles.fill}
value={s.host ?? ""}
placeholder={snowflake ? "myorg-myaccount or xy12345.eu-central-1" : undefined}
onChange={(e) => set({ host: e.target.value })}
/>
<label className={styles.formLabel} htmlFor="db-port">
<T>Port:</T>
</label>
<Input
id="db-port"
className={styles.portInput}
inputMode="numeric"
value={s.port ?? ""}
placeholder={String(vendor.port ?? "")}
onChange={(e) => set({ port: parsePort(e.target.value) })}
/>
</div>
</>
)}
</>
)}
{sshOn && (
@@ -676,7 +859,7 @@ export function SourceDialog({
label="Save password"
/>
</div>
{!urlOnly && (
{!urlOnly && !jdbc && (
<>
<label className={styles.formLabel} htmlFor="db-database">
<T>Database:</T>
@@ -725,22 +908,47 @@ export function SourceDialog({
<Input
id="db-url"
mono
value={urlOnly ? (s.url ?? "") : (urlDraft ?? sourceUrl(s))}
invalid={urlOnly ? !urlValid : urlDraft !== null && parseSourceUrl(urlDraft)?.source.driver !== s.driver}
placeholder={sourceUrl(s)}
onChange={(e) => (urlOnly ? set({ url: e.target.value }) : typeUrl(e.target.value))}
value={jdbc ? jdbcUrl : urlOnly ? (s.url ?? "") : (urlDraft ?? sourceUrl(s))}
invalid={
jdbc
? !!s.url && !jdbcUrlValid
: urlOnly
? !urlValid
: urlDraft !== null && parseSourceUrl(urlDraft)?.source.driver !== s.driver
}
placeholder={jdbc ? jdbcProfile?.urlTemplate : sourceUrl(s)}
onChange={(e) => (jdbc || urlOnly ? set({ url: e.target.value }) : typeUrl(e.target.value))}
onBlur={() => setUrlDraft(null)}
/>
<span />
<span className={styles.formHint}>
{txTemplate(
urlOnly
? urlValid || !s.url?.trim()
? "Connects with the URL alone: host, port, database, SSL and parameters come from it."
: `Not a ${vendor.label} URL`
: "Editing the URL fills in the settings above.",
)}
{jdbc
? tx(
"The URL and Advanced properties are saved with the data source. Enter passwords in the Password field.",
)
: txTemplate(
urlOnly
? urlValid || !s.url?.trim()
? "Connects with the URL alone: host, port, database, SSL and parameters come from it."
: `Not a ${vendor.label} URL`
: "Editing the URL fills in the settings above.",
)}
</span>
{jdbc && reviewJdbcSecurity && (
<div className={styles.formWide}>
<span className={styles.formHint}>
<T>
Review the JDBC URL, TLS settings and connection properties. If your native connection used an SSH
tunnel, configure the equivalent route before connecting.
</T>
</span>
<Checkbox
checked={jdbcSecurityConfirmed}
onChange={setJdbcSecurityConfirmed}
label="I have configured JDBC connection security."
/>
</div>
)}
</>
)}
</>
@@ -751,17 +959,26 @@ export function SourceDialog({
<Section title="Connection" />
<span />
<Checkbox checked={!!s.readOnly} onChange={(readOnly) => set({ readOnly })} label="Read-only" />
<span className={styles.formLabel}>
<T>Transaction control:</T>
</span>
<Select
aria-label="Transaction control"
className={styles.narrowSelect}
value={clickhouse ? "auto" : (options.transaction ?? "auto")}
options={clickhouse ? TX.filter((option) => option.value === "auto") : TX}
disabled={clickhouse}
onChange={(transaction) => setOptions({ transaction })}
/>
{jdbc && (
<span className={styles.formWide}>
<T>For read-only access, use a database account with read-only privileges.</T>
</span>
)}
{!jdbc && (
<>
<span className={styles.formLabel}>
<T>Transaction control:</T>
</span>
<Select
aria-label="Transaction control"
className={styles.narrowSelect}
value={clickhouse ? "auto" : (options.transaction ?? "auto")}
options={clickhouse ? TX.filter((option) => option.value === "auto") : TX}
disabled={clickhouse}
onChange={(transaction) => setOptions({ transaction })}
/>
</>
)}
{postgres && (
<>
<label className={styles.formLabel} htmlFor="db-default-schema">
@@ -788,7 +1005,7 @@ export function SourceDialog({
/>
</>
)}
{!sqlite && (
{!sqlite && !jdbc && (
<>
<label className={styles.formLabel} htmlFor="db-time-zone">
<T>Time zone:</T>
@@ -827,33 +1044,37 @@ export function SourceDialog({
/>
</>
)}
<label className={styles.formLabel} htmlFor="db-startup">
<T>Startup script:</T>
</label>
<textarea
id="db-startup"
className={styles.textArea}
spellCheck={false}
value={options.startupScript ?? ""}
placeholder={
postgres
? "SET statement_timeout = '30s';"
: clickhouse
? "SET max_execution_time = 30;"
: sqlite
? "PRAGMA foreign_keys = ON;"
: snowflake
? "ALTER SESSION SET QUERY_TAG = 'ide';"
: oracle
? "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS';"
: "SET SESSION sql_mode = 'ANSI';"
}
onChange={(e) => setOptions({ startupScript: e.target.value })}
/>
<span />
<span className={styles.formHint}>
<T>Runs on every new connection, before any other statement.</T>
</span>
{!jdbc && (
<>
<label className={styles.formLabel} htmlFor="db-startup">
<T>Startup script:</T>
</label>
<textarea
id="db-startup"
className={styles.textArea}
spellCheck={false}
value={options.startupScript ?? ""}
placeholder={
postgres
? "SET statement_timeout = '30s';"
: clickhouse
? "SET max_execution_time = 30;"
: sqlite
? "PRAGMA foreign_keys = ON;"
: snowflake
? "ALTER SESSION SET QUERY_TAG = 'ide';"
: oracle
? "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS';"
: "SET SESSION sql_mode = 'ANSI';"
}
onChange={(e) => setOptions({ startupScript: e.target.value })}
/>
<span />
<span className={styles.formHint}>
<T>Runs on every new connection, before any other statement.</T>
</span>
</>
)}
</>
);
@@ -1274,6 +1495,22 @@ export function SourceDialog({
)}
</div>
</div>
{jdbc && showJdbcProfiles && jdbcProfiles.drivers && (
<JdbcDriverProfiles
drivers={jdbcProfiles.drivers}
selected={s.jdbcDriver ?? ""}
onClose={() => setShowJdbcProfiles(false)}
onSave={(driver) => {
jdbcProfiles.setDrivers((drivers) => [...(drivers ?? []).filter((d) => d.id !== driver.id), driver]);
if (!s.jdbcDriver || s.jdbcDriver === driver.id) chooseProfile(driver);
}}
onUse={(driver) => {
chooseProfile(driver);
setShowJdbcProfiles(false);
}}
onRemove={(id) => jdbcProfiles.setDrivers((drivers) => (drivers ?? []).filter((d) => d.id !== id))}
/>
)}
</Dialog>
);
}
+9 -6
Переглянути файл
@@ -3,6 +3,7 @@
* a WHERE filter, and pending cell edits / added / deleted rows submitted
* together in one transaction. Tables without a primary key are read-only.
*/
import { canModifyTable } from "./objects";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
call,
@@ -122,7 +123,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
const pk = page?.details.columns.filter((c) => c.primaryKey).map((c) => c.name) ?? [];
const fkColumns = new Set(page?.details.foreignKeys.flatMap((k) => k.columns) ?? []);
const source = sourceById(ref.id);
const editable = pk.length > 0 && !source?.readOnly && source?.driver !== "clickhouse";
const editable = pk.length > 0 && !source?.readOnly && canModifyTable(source?.driver ?? "sqlite");
const loaded = page?.result.rows.length ?? 0;
const rowCount = loaded + edits.inserts.length;
const gridColumns = useMemo(
@@ -414,11 +415,13 @@ export function TableEditor({ input }: { input: EditorInput }) {
</div>
{page && !editable && (
<div className={styles.notice}>
{source?.driver === "clickhouse"
? tx("Use the query console to change ClickHouse data.")
: pk.length
? tx("Read-only data source.")
: tx("Read-only: the table has no primary key to identify rows.")}
{source?.driver === "jdbc"
? tx("Use the query console to change JDBC data.")
: source?.driver === "clickhouse"
? tx("Use the query console to change ClickHouse data.")
: pk.length
? tx("Read-only data source.")
: tx("Read-only: the table has no primary key to identify rows.")}
</div>
)}
{error ? (
+10 -7
Переглянути файл
@@ -477,7 +477,8 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
// SQL resolution scopes in the settings can move the console to another data source.
useProject((s) => s.settings);
const boundId = bound ? splitTarget(bound).id : null;
const supportsTransactions = sourceById(boundId)?.driver !== "clickhouse";
const jdbc = sourceById(boundId)?.driver === "jdbc";
const supportsTransactions = sourceById(boundId)?.driver !== "clickhouse" && !jdbc;
const sqlServer = sourceById(boundId)?.driver === "sqlServer";
const switchable = schemaSwitchable(sourceById(boundId)?.driver);
// The console's active schema: its pick, else the connection's default (`completion.defaultSchema`).
@@ -549,12 +550,14 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
disabled={!bound || running}
onClick={() => void executeScriptInView(view, path)}
/>
<IconButton
icon="db-plan"
title="Explain Plan"
disabled={!bound || running}
onClick={() => void explainInView(view, path)}
/>
{!jdbc && (
<IconButton
icon="db-plan"
title="Explain Plan"
disabled={!bound || running}
onClick={() => void explainInView(view, path)}
/>
)}
<IconButton
icon="stop"
title="Cancel Running Statement"
+1 -1
Переглянути файл
@@ -291,7 +291,7 @@ describe("data source types", () => {
expect(vendorPreset(vendorById("oracle")!)).toEqual({ driver: "oracle", vendor: "", port: 1521 });
expect(
VENDORS.every((v) =>
["postgres", "mysql", "sqlite", "sqlServer", "clickhouse", "oracle", "snowflake"].includes(v.driver),
["postgres", "mysql", "sqlite", "sqlServer", "clickhouse", "oracle", "snowflake", "jdbc"].includes(v.driver),
),
).toBe(true);
const labels = VENDORS.map((v) => v.label);
+1
Переглянути файл
@@ -353,6 +353,7 @@ export function activate(): () => void {
icon: "db-plan",
keywords: ["query plan", "explain", "sql"],
when: `editorTextFocus && editorLangId == ${SQL_LANGUAGE}`,
enabled: () => sourceById(consoleSource(activeEditor()?.ctx.path ?? ""))?.driver !== "jdbc",
run: async () => {
const current = projectRequest();
const e = activeEditor();
+14
Переглянути файл
@@ -337,6 +337,20 @@ export function targetOf(id: string, database: string | null, current: string |
/** Key of the Database tree node of database `name` of data source `id`. */
export const databaseKey = (id: string, name: string) => `${id}/@${name}`;
/**
* `expanded` without the Database tree nodes that show what target `id` loaded (a data source
* id: the source and all its databases). Once that is forgotten, an expanded node would wait
* for children nothing loads until it is expanded again.
*/
export function collapseTarget(expanded: ReadonlySet<string>, id: string): Set<string> {
const { id: source, database } = splitTarget(id);
const under = (key: string, node: string) => key === node || key.startsWith(`${node}/`);
const shows = database
? (key: string) => under(key, databaseKey(source, database)) || under(key, id)
: (key: string) => under(key, source) || key.startsWith(`${source}:`);
return new Set([...expanded].filter((key) => !shows(key)));
}
const SSL_MODES: Record<string, DbSslMode> = {
disable: "disable",
disabled: "disable",
+9 -7
Переглянути файл
@@ -82,10 +82,11 @@ const exists = (driver: DbDriver, o: DbObjectRef) =>
driver !== "snowflake" || (o.kind !== "index" && o.kind !== "trigger");
export const canRename = (driver: DbDriver, o: DbObjectRef) =>
o.kind === "table" ||
o.kind === "column" ||
(o.kind === "view" && driver !== "sqlite") ||
(o.kind === "index" && driver === "postgres");
driver !== "jdbc" &&
(o.kind === "table" ||
o.kind === "column" ||
(o.kind === "view" && driver !== "sqlite") ||
(o.kind === "index" && driver === "postgres"));
/** The statement renaming `o` to `to`. */
export function renameSql(driver: DbDriver, o: DbObjectRef, to: string): string {
@@ -116,11 +117,12 @@ export interface DropOptions {
}
export const canDrop = (driver: DbDriver, o: DbObjectRef) =>
driver === "clickhouse"
driver !== "jdbc" &&
(driver === "clickhouse"
? ["table", "view", "materializedView", "column", "schema"].includes(o.kind)
: !(o.kind === "schema" && driver === "sqlite") && exists(driver, o);
: !(o.kind === "schema" && driver === "sqlite") && exists(driver, o));
export const canModifyTable = (driver: DbDriver) => driver !== "clickhouse";
export const canModifyTable = (driver: DbDriver) => driver !== "clickhouse" && driver !== "jdbc";
/** IDEA's Confirm Drop preview. */
export function dropSql(driver: DbDriver, o: DbObjectRef, opts: DropOptions): string {
+30 -2
Переглянути файл
@@ -274,6 +274,31 @@ describe("database metadata request lifetimes", () => {
expect(useDatabase.getState().connected.has("pg:app")).toBe(false);
});
it("collapses the tree nodes of what a disconnect forgets", async () => {
const tree = [
"pg",
"pg/@app",
"pg/public",
"pg/public/tables",
"pg:other/public",
"pg/@other",
"pg2",
"pg2/public",
];
useDatabase.setState({ treeExpanded: new Set(tree) });
await disconnect("pg:other");
expect([...useDatabase.getState().treeExpanded]).toEqual([
"pg",
"pg/@app",
"pg/public",
"pg/public/tables",
"pg2",
"pg2/public",
]);
await disconnect("pg");
expect([...useDatabase.getState().treeExpanded]).toEqual(["pg2", "pg2/public"]);
});
it("disconnects one database without invalidating its sibling", async () => {
const response = deferred();
backend.schemas.mockReturnValueOnce(response.promise);
@@ -334,11 +359,14 @@ describe("database metadata request lifetimes", () => {
});
describe("connection and metadata continuations", () => {
it("reloads every level the tree had expanded after a data source is edited", async () => {
it.each([
["edited", () => saveSource({ ...pg, host: "new-host" }, undefined)],
["renamed", () => renameSource("pg", "Renamed")],
])("reloads every level the tree had expanded after a data source is %s", async (_, change) => {
await loadSchemas("pg");
await loadTables("pg", "public");
await loadDetails("pg", "public", "users");
await saveSource({ ...pg, host: "new-host" }, undefined);
await change();
const st = useDatabase.getState();
expect(st.schemas.pg).toEqual({ status: "ok", value: ["public"] });
expect(st.tables["pg\u0000public"]?.status).toBe("ok");
+7 -3
Переглянути файл
@@ -504,11 +504,15 @@ describe("read-only results with a reason", () => {
expect(screen.queryByRole("button", { name: "Submit" })).toBeNull();
});
it("keeps ClickHouse read-only", async () => {
backend.driver = "clickhouse";
it.each(["clickhouse", "jdbc"] as const)("keeps %s read-only", async (driver) => {
backend.driver = driver;
show("SELECT * FROM users", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]);
await act(async () => render(<ResultsView />));
expect(await screen.findByRole("note")).toHaveTextContent("Use the query console to change ClickHouse data.");
expect(await screen.findByRole("note")).toHaveTextContent(
driver === "jdbc"
? "Use the query console to change JDBC data."
: "Use the query console to change ClickHouse data.",
);
expect(screen.queryByRole("button", { name: "Submit" })).toBeNull();
});
+3
Переглянути файл
@@ -142,6 +142,7 @@ export function statementStarters(driver: DbDriver): string[] {
"COMMIT",
"ROLLBACK",
];
if (driver === "jdbc") return common;
if (driver === "sqlite") return [...common, "PRAGMA", "VACUUM", "ATTACH DATABASE", "REPLACE INTO", "CREATE TRIGGER"];
if (driver === "mysql")
return [
@@ -217,6 +218,7 @@ export function predicateKeywords(driver: DbDriver): string[] {
}
export const DATA_TYPES: Record<DbDriver, string[]> = {
jdbc: ["INTEGER", "BIGINT", "DECIMAL", "DOUBLE PRECISION", "VARCHAR", "BOOLEAN", "DATE", "TIME", "TIMESTAMP"],
snowflake: [
"NUMBER",
"INTEGER",
@@ -397,6 +399,7 @@ const COMMON: SqlFunction[] = [
];
const FUNCTIONS: Record<DbDriver, SqlFunction[]> = {
jdbc: COMMON,
snowflake: [
...COMMON,
f("listagg", "expr, delimiter", "varchar", true),
+8 -9
Переглянути файл
@@ -38,6 +38,7 @@ import { workflowSettings } from "@/platform/workflowSettings";
import { ask, confirm } from "@/workbench/messages";
import {
activeSchema,
collapseTarget,
colorVar,
connectRemedy,
databaseKey,
@@ -437,12 +438,8 @@ export async function duplicateSource(id: string): Promise<void> {
export async function renameSource(id: string, name: string): Promise<void> {
const src = sourceById(id);
if (!src || !name.trim() || name.trim() === src.name) return;
const sources = useDatabase.getState().sources.map((s) => (s.id === src.id ? { ...s, name: name.trim() } : s));
forget(id);
const current = sourceMutation(id);
await call(commands.dbSaveSources(sources));
if (!current()) return;
await loadSources();
// Saved like any edit, so what the tree had loaded under the source is loaded again.
await saveSource({ ...src, name: name.trim() }, undefined);
}
/** Removes the data source after asking (Database tree › Drop on a source). */
@@ -523,6 +520,7 @@ const lastUsed = new Map<string, number>();
function applyConnectDefaults(id: string) {
if (
sourceById(id)?.driver !== "clickhouse" &&
sourceById(id)?.driver !== "jdbc" &&
sourceById(id)?.options?.transaction === "manual" &&
!useDatabase.getState().manualCommit.has(id)
)
@@ -571,6 +569,7 @@ export async function disconnect(id: string): Promise<void> {
if (!targets.includes(id)) targets.push(id);
const current = projectRequest();
forget(id);
useDatabase.setState((s) => ({ treeExpanded: collapseTarget(s.treeExpanded, id) }));
const intent = {};
for (const target of targets) connectionIntents.set(target, intent);
if (!splitTarget(id).database) sourceConnectionIntents.set(id, {});
@@ -1353,7 +1352,7 @@ async function explain(id: string, statement: SqlStatement, schema?: string): Pr
/** Explain Plan: the plan of the statement at `from` (the first selected one) of console `path`. */
export async function explainConsole(path: string, text: string, from: number, to: number): Promise<void> {
const id = consoleSource(path);
if (!id) return;
if (!id || sourceById(id)?.driver === "jdbc") return;
try {
const [statement] = await consoleStatements(id, text, from, to);
if (!statement) return;
@@ -1530,7 +1529,7 @@ function setPending(id: string, pending: boolean) {
/** Commits or rolls back the open transaction of a manual-commit data source. */
export async function finishTransaction(id: string, commit: boolean): Promise<boolean> {
if (sourceById(id)?.driver === "clickhouse") return false;
if (sourceById(id)?.driver === "clickhouse" || sourceById(id)?.driver === "jdbc") return false;
try {
await call(commands.dbFinishTransaction(id, commit));
log("statement", commit ? "commit" : "rollback", `${promptOf(id)}>`);
@@ -1562,7 +1561,7 @@ async function askEndTransaction(source: DataSource): Promise<boolean | null> {
* whether to commit or roll them back.
*/
export async function setManualCommit(id: string, manual: boolean): Promise<void> {
if (sourceById(id)?.driver === "clickhouse" && manual) return;
if (sourceById(id)?.driver === "jdbc" || (sourceById(id)?.driver === "clickhouse" && manual)) return;
const st = useDatabase.getState();
if (manual === st.manualCommit.has(id)) return;
if (!manual && st.pendingTx.has(id)) {
+25 -15
Переглянути файл
@@ -66,21 +66,31 @@ beforeEach(() => {
});
describe("table editor capabilities", () => {
it("keeps ClickHouse rows read-only even when metadata marks a primary key", async () => {
await act(async () => {
render(<TableEditor input={tableInput("source", "default", "users")} />);
});
const cell = await screen.findByRole("gridcell", { name: "Ann" });
fireEvent.doubleClick(cell);
expect(screen.queryByRole("textbox", { name: "Edit name" })).toBeNull();
expect(screen.queryByRole("button", { name: "Add Row" })).toBeNull();
expect(screen.queryByRole("button", { name: "Submit" })).toBeNull();
expect(screen.getByText("Use the query console to change ClickHouse data.")).toBeTruthy();
fireEvent.mouseDown(cell, { button: 0 });
fireEvent.paste(screen.getByRole("grid"), { clipboardData: { getData: () => "Changed" } });
expect(screen.getByRole("gridcell", { name: "Ann" })).toBeTruthy();
expect(backend.applyEdits).not.toHaveBeenCalled();
});
it.each(["clickhouse", "jdbc"] as const)(
"keeps %s rows read-only even when metadata marks a primary key",
async (driver) => {
backend.driver = driver;
await act(async () => {
render(<TableEditor input={tableInput("source", "default", "users")} />);
});
const cell = await screen.findByRole("gridcell", { name: "Ann" });
fireEvent.doubleClick(cell);
expect(screen.queryByRole("textbox", { name: "Edit name" })).toBeNull();
expect(screen.queryByRole("button", { name: "Add Row" })).toBeNull();
expect(screen.queryByRole("button", { name: "Submit" })).toBeNull();
expect(
screen.getByText(
driver === "jdbc"
? "Use the query console to change JDBC data."
: "Use the query console to change ClickHouse data.",
),
).toBeTruthy();
fireEvent.mouseDown(cell, { button: 0 });
fireEvent.paste(screen.getByRole("grid"), { clipboardData: { getData: () => "Changed" } });
expect(screen.getByRole("gridcell", { name: "Ann" })).toBeTruthy();
expect(backend.applyEdits).not.toHaveBeenCalled();
},
);
it("keeps keyed PostgreSQL rows editable", async () => {
backend.driver = "postgres";
+9 -3
Переглянути файл
@@ -373,7 +373,7 @@ export function registerDatabaseTreeActions(): () => void {
keywords: ["delete all rows", "empty table"],
run: ({ arg }) => {
const n = nodeFrom(arg);
if (n?.kind === "table" && n.table.kind === "table")
if (n?.kind === "table" && n.table.kind === "table" && driverOf(n.id) !== "jdbc")
openDialog({ kind: "truncate", id: n.id, schema: n.schema, table: n.table.name });
},
}),
@@ -425,7 +425,7 @@ export function registerDatabaseTreeActions(): () => void {
run: ({ arg }) => {
const n = nodeFrom(arg);
const id = n && nodeTarget(n);
if (!n || !id) return;
if (!n || !id || driverOf(id) === "jdbc") return;
const schema =
"schema" in n && typeof n.schema === "string" ? n.schema : driverOf(id) === "sqlite" ? "main" : null;
if (schema !== null) openDialog({ kind: "modifyTable", id, schema, table: null });
@@ -441,6 +441,7 @@ export function registerDatabaseTreeActions(): () => void {
const n = nodeFrom(arg);
const id = n && nodeTarget(n);
const schema = n && "schema" in n && typeof n.schema === "string" ? n.schema : null;
if (id && driverOf(id) === "jdbc") return;
openDialog({
kind: "compareSchemas",
source: id ? { id, schema: schema ?? (driverOf(id) === "sqlite" ? "main" : "") } : null,
@@ -466,7 +467,12 @@ export function registerDatabaseTreeActions(): () => void {
keywords: ["csv", "tsv", "load data"],
run: ({ arg }) => {
const n = nodeFrom(arg);
if (n?.kind === "table" && n.table.kind === "table" && driverOf(n.id) !== "clickhouse")
if (
n?.kind === "table" &&
n.table.kind === "table" &&
driverOf(n.id) !== "clickhouse" &&
driverOf(n.id) !== "jdbc"
)
openDialog({ kind: "import", id: n.id, schema: n.schema, table: n.table.name });
},
}),
+11 -2
Переглянути файл
@@ -128,6 +128,16 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
submenu: [...extra, act("db.jumpToConsole", n)],
});
if (driver === "jdbc" && n.kind !== "source") {
return [
newConsole,
...(t ? [act("db.editData", n)] : []),
refresh,
{ label: "Copy/Paste", submenu: [copyRef] },
navigation(),
];
}
switch (n.kind) {
case "source": {
const connected = connectedTargets(n.source.id ?? "").length > 0;
@@ -156,8 +166,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
quickDoc,
navigation(),
sep,
sqlScripts(n, false),
act("db.compareSchemas", n),
...(driver === "jdbc" ? [act("db.runSqlScript", n)] : [sqlScripts(n, false), act("db.compareSchemas", n)]),
...importExport(dumpItems(n, true)),
sep,
act("db.drop", n, { label: "Remove Data Source…" }),
+2
Переглянути файл
@@ -44,6 +44,7 @@ export const VENDORS: readonly DbVendor[] = [
icon: "db-cockroach",
scheme: "postgresql",
},
{ id: "jdbc", label: "Custom JDBC", driver: "jdbc", port: null, icon: "database", scheme: "" },
{ id: "greenplum", label: "Greenplum", driver: "postgres", port: 5432, icon: "db-greenplum", scheme: "postgresql" },
{ id: "mariadb", label: "MariaDB", driver: "mysql", port: 3306, icon: "db-mariadb", scheme: "mariadb" },
{
@@ -180,6 +181,7 @@ const bracketed = (host: string) => (host.includes(":") && !host.startsWith("[")
/** The JDBC URL of a data source's fields (the General tab's URL preview). */
export function sourceUrl(s: DataSource): string {
const v = vendorOf(s);
if (v.driver === "jdbc") return s.url ?? "";
if (v.driver === "sqlite") return `jdbc:sqlite:${s.file ?? ""}`;
const host = bracketed(s.host?.trim() || "localhost");
const port = s.port ?? v.port;
+310
Переглянути файл
@@ -0,0 +1,310 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Diagnostic } from "@/bindings";
const ipc = vi.hoisted(() => ({
fsReadText: vi.fn(),
debugHotReload: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return { ...real, commands: { ...real.commands, ...ipc } };
});
import { _emitEditorEvent } from "@/editor/api";
import { setFileDiagnostics } from "@/editor/lsp/diagnostics";
import type { DebugSessionId } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { installFlutterHotReloadOnSave, packageRoots } from "../flutterReload";
import { useDebug, type DebugSession } from "../state";
const ok = <T>(data: T) => Promise.resolve({ status: "ok" as const, data });
const failed = (message: string) => Promise.resolve({ status: "error" as const, error: { kind: "internal", message } });
const CONFIG = "/repo/apps/shop/.dart_tool/package_config.json";
const PACKAGES = JSON.stringify({
packages: [
{ name: "shop", rootUri: "../" },
{ name: "shared", rootUri: "../../../packages/shared" },
{ name: "http", rootUri: "file:///home/me/.pub-cache/http-1.0.0/" },
],
});
function session(id: number, patch: Partial<DebugSession> = {}): DebugSession {
return {
id: id as DebugSessionId,
name: "shop",
adapter: "dart",
parent: null,
launch: {
name: "shop",
adapter: "dart",
request: "launch",
program: "/repo/apps/shop/lib/main.dart",
args: [],
cwd: "/repo/apps/shop",
env: {},
extraJson: null,
},
process: null,
status: "running",
stoppedThread: null,
stopReason: null,
stopDescription: null,
threads: [],
selectedThread: null,
frames: [],
selectedFrame: null,
hits: 0,
stops: 0,
exitCode: null,
caps: null,
flutterAppStarted: true,
...patch,
};
}
const withSessions = (...sessions: DebugSession[]) =>
useDebug.setState({ sessions: Object.fromEntries(sessions.map((s) => [s.id, s])), console: {} });
const save = (...paths: string[]) => paths.forEach((path) => _emitEditorEvent({ type: "docSaved", doc: 1, path }));
const diagnostic = (severity: Diagnostic["severity"], source = "dart"): Diagnostic => ({
range: { start: { line: 0, col: 0 }, end: { line: 0, col: 1 } },
severity,
message: "problem",
source,
code: null,
});
const settle = () => vi.advanceTimersByTimeAsync(1000);
const reloaded = () => ipc.debugHotReload.mock.calls.map(([id, reason]) => [id, reason]);
const MAIN = "/repo/apps/shop/lib/main.dart";
const HOME = "/repo/apps/shop/lib/home.dart";
const SHARED = "/repo/packages/shared/lib/shared.dart";
const OTHER_APP = "/repo/apps/admin/lib/main.dart";
describe("Flutter hot reload on save", () => {
let uninstall: () => void;
beforeEach(() => {
vi.useFakeTimers();
ipc.debugHotReload.mockReset().mockImplementation(() => ok(null));
ipc.fsReadText
.mockReset()
.mockImplementation((path: string) => (path === CONFIG ? ok(PACKAGES) : failed("not found")));
useProject.setState({ settings: null });
withSessions(session(1));
uninstall = installFlutterHotReloadOnSave();
});
afterEach(() => {
uninstall();
for (const path of [MAIN, HOME, SHARED]) setFileDiagnostics(path, "dart", []);
vi.useRealTimers();
});
it("reloads the session with reason save", async () => {
save(MAIN);
expect(ipc.debugHotReload).not.toHaveBeenCalled();
await settle();
expect(reloaded()).toEqual([[1, "save"]]);
});
it("merges a Save All and repeated autosaves into one reload", async () => {
save(MAIN, HOME);
await vi.advanceTimersByTimeAsync(200);
save(MAIN);
await settle();
expect(reloaded()).toEqual([[1, "save"]]);
});
it("waits for a paused session to resume", async () => {
withSessions(session(1, { status: "paused" }));
save(MAIN);
await settle();
expect(ipc.debugHotReload).not.toHaveBeenCalled();
withSessions(session(1));
await settle();
expect(reloaded()).toEqual([[1, "save"]]);
});
it("does not reload on resume when nothing was saved", async () => {
withSessions(session(1, { status: "paused" }));
withSessions(session(1));
await settle();
expect(ipc.debugHotReload).not.toHaveBeenCalled();
});
it("still reloads a running session while another one is paused", async () => {
withSessions(session(1, { status: "paused" }), session(2));
save(MAIN);
await settle();
expect(reloaded()).toEqual([[2, "save"]]);
});
it.each([
["a plain Dart session or an app still starting", { flutterAppStarted: undefined }],
["a session being stopped", { status: "stopping" as const }],
["a finished session", { status: "terminated" as const }],
])("skips %s", async (_name, patch) => {
withSessions(session(1, patch));
save(MAIN);
await settle();
expect(ipc.debugHotReload).not.toHaveBeenCalled();
});
it("skips a session that ends before the reload goes out", async () => {
save(MAIN);
withSessions(session(1, { status: "terminated" }));
await settle();
expect(ipc.debugHotReload).not.toHaveBeenCalled();
});
it("ignores other file types", async () => {
save("/repo/apps/shop/pubspec.yaml");
await settle();
expect(ipc.debugHotReload).not.toHaveBeenCalled();
});
it("does nothing when the setting is off", async () => {
useProject.setState({ settings: { debugger: { flutterHotReloadOnSave: false } } as never });
save(MAIN);
await settle();
expect(ipc.debugHotReload).not.toHaveBeenCalled();
});
describe("when the setting is turned off with a reload pending", () => {
const setEnabled = (flutterHotReloadOnSave: boolean) =>
useProject.setState({ settings: { debugger: { flutterHotReloadOnSave } } as never });
it("drops a save waiting for a paused session", async () => {
withSessions(session(1, { status: "paused" }));
save(MAIN);
await settle();
setEnabled(false);
withSessions(session(1));
await settle();
expect(ipc.debugHotReload).not.toHaveBeenCalled();
});
it("does not replay that save after the setting comes back", async () => {
withSessions(session(1, { status: "paused" }));
save(MAIN);
await settle();
setEnabled(false);
setEnabled(true);
withSessions(session(1));
await settle();
expect(ipc.debugHotReload).not.toHaveBeenCalled();
});
it("drops a save still in the debounce window", async () => {
save(MAIN);
setEnabled(false);
setEnabled(true);
await settle();
expect(ipc.debugHotReload).not.toHaveBeenCalled();
});
it("does not send a reload whose package list was still being read", async () => {
let finishRead = (_: unknown) => {};
ipc.fsReadText.mockImplementation(() => new Promise((resolve) => (finishRead = resolve)));
save(MAIN);
await settle();
setEnabled(false);
finishRead(await ok(PACKAGES));
await settle();
expect(ipc.debugHotReload).not.toHaveBeenCalled();
});
it("reloads for saves made after it comes back", async () => {
save(MAIN);
setEnabled(false);
setEnabled(true);
save(HOME);
await settle();
expect(reloaded()).toEqual([[1, "save"]]);
});
});
it("reloads for a package the app depends on, not for another app of the monorepo", async () => {
save(SHARED);
await settle();
expect(reloaded()).toEqual([[1, "save"]]);
ipc.debugHotReload.mockClear();
save(OTHER_APP);
await settle();
expect(ipc.debugHotReload).not.toHaveBeenCalled();
});
it("uses the working directory of an attach session without a package config", async () => {
const launch = { ...session(1).launch!, request: "attach", program: null, cwd: "/repo/module" };
withSessions(session(1, { launch }));
save("/repo/module/lib/a.dart", MAIN);
await settle();
expect(reloaded()).toEqual([[1, "save"]]);
ipc.debugHotReload.mockClear();
save(MAIN);
await settle();
expect(ipc.debugHotReload).not.toHaveBeenCalled();
});
it("reloads only the sessions whose project holds the file", async () => {
const launch = { ...session(2).launch!, program: "/repo/apps/admin/lib/main.dart", cwd: "/repo/apps/admin" };
withSessions(session(1), session(2, { launch }));
save(OTHER_APP);
await settle();
expect(reloaded()).toEqual([[2, "save"]]);
});
it("skips a file with errors until it is fixed, including an error published after the save", async () => {
save(MAIN);
await vi.advanceTimersByTimeAsync(100);
setFileDiagnostics(MAIN, "dart", [diagnostic("error")]);
await settle();
expect(ipc.debugHotReload).not.toHaveBeenCalled();
save(HOME);
await settle();
expect(ipc.debugHotReload).not.toHaveBeenCalled();
setFileDiagnostics(MAIN, "dart", []);
save(MAIN);
await settle();
expect(reloaded()).toEqual([[1, "save"]]);
});
it("is not blocked by warnings or by errors of other tools", async () => {
setFileDiagnostics(MAIN, "dart", [diagnostic("warning")]);
setFileDiagnostics(HOME, "dart", [diagnostic("error", "custom-lint")]);
save(MAIN, HOME);
await settle();
expect(reloaded()).toEqual([[1, "save"]]);
setFileDiagnostics(HOME, "dart", []);
});
it("reports a failed request in the Debug console only", async () => {
ipc.debugHotReload.mockImplementation(() => failed("timed out"));
save(MAIN);
await settle();
const lines = useDebug.getState().console[1]!;
expect(lines.map((l) => l.text).join("\n")).toContain("Hot reload on save failed: timed out");
});
});
describe("packageRoots", () => {
it("resolves relative and absolute package roots against the config file", () => {
expect(packageRoots(PACKAGES, CONFIG)).toEqual([
"/repo/apps/shop",
"/repo/packages/shared",
"/home/me/.pub-cache/http-1.0.0",
]);
});
it("decodes escapes and keeps Windows drives", () => {
const text = JSON.stringify({ packages: [{ rootUri: "../" }, { rootUri: "file:///D:/pub%20cache/a/" }] });
expect(packageRoots(text, "C:/my app/.dart_tool/package_config.json")).toEqual(["C:/my app", "D:/pub cache/a"]);
});
});
+69
Переглянути файл
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { RunConfig } from "@/platform/ipc";
import { usePlatform } from "@/platform/platformInfo";
import { useFlutterDevices } from "@/workbench/flutterDevices";
import { debugUnsupportedReason, launchConfigFor, withEnvFiles } from "../launch";
const ipc = vi.hoisted(() => {
@@ -37,6 +38,74 @@ beforeEach(() => {
});
afterEach(() => usePlatform.setState(originalPlatform));
describe("Flutter device", () => {
const device = { platformType: null, category: "desktop", emulator: false, unavailable: null };
const flutter = (p: Partial<RunConfig> = {}) =>
rc({ kind: "flutter", command: "flutter", args: ["run", "-t", "lib/main.dart"], debugAdapter: "dart", ...p });
beforeEach(() =>
useFlutterDevices.setState({
preferred: "macos",
list: {
status: { kind: "ready" },
devices: [
{ ...device, id: "chrome", name: "Chrome" },
{ ...device, id: "macos", name: "macOS" },
],
},
}),
);
afterEach(() => useFlutterDevices.setState({ preferred: null, list: null }));
it("debugs on the toolbar's device, through the backend's Flutter check", () => {
const launch = launchConfigFor(flutter({ args: ["run", "-t", "lib/app.dart", "--flavor", "dev"] }), "/p");
expect(launch?.program).toBe("/p/lib/app.dart");
expect(extra(launch)).toEqual({ toolArgs: ["--flavor", "dev"], __flutterDevice: "macos" });
});
it("takes the entry point from the target option, not from any argument ending in .dart", () => {
const debug = (...args: string[]) => launchConfigFor(flutter({ args: ["run", ...args] }), "/p");
expect(debug("--target=lib/app.dart")?.program).toBe("/p/lib/app.dart");
expect(debug("--target", "lib/app.dart")?.program).toBe("/p/lib/app.dart");
const define = debug("-t", "lib/main.dart", "--dart-define=CFG=dev.dart");
expect(define?.program).toBe("/p/lib/main.dart");
expect(extra(define).toolArgs).toEqual(["--dart-define=CFG=dev.dart"]);
expect(debug("--dart-define=CFG=dev.dart")?.program).toBe("/p/lib/main.dart");
});
it("keeps a file-scoped Dart configuration's last .dart argument as its entry point", () => {
const file = rc({ kind: "dart", command: "dart", args: ["run", "bin/tool.dart"], debugAdapter: "dart" });
expect(launchConfigFor(file, "/p")?.program).toBe("/p/bin/tool.dart");
});
it("reads the pinned device from every spelling of the option", () => {
const pinned = flutter({ args: ["run", "--device-id=chrome"] });
expect(extra(launchConfigFor(pinned, "/p"))).toEqual({ __flutterDevice: "chrome" });
});
it("prefers the device the configuration pins", () => {
const pinned = flutter({ args: ["run", "-t", "lib/main.dart", "-d", "chrome"] });
expect(extra(launchConfigFor(pinned, "/p"))).toEqual({ __flutterDevice: "chrome" });
});
it("falls back to a connected device when the chosen one is gone", () => {
useFlutterDevices.setState({ preferred: "R5C" });
expect(extra(launchConfigFor(flutter(), "/p")).__flutterDevice).toBe("chrome");
});
it("attaches on the pinned device, else the toolbar's", () => {
const attach = (params: Record<string, string>) =>
extra(launchConfigFor(rc({ debugAdapter: "dart", params: { request: "attach", ...params } }), "/p"));
expect(attach({}).toolArgs).toEqual(["-d", "macos"]);
expect(attach({ device: "chrome" }).toolArgs).toEqual(["-d", "chrome"]);
});
it("leaves the choice to flutter without a device list", () => {
useFlutterDevices.setState({ list: null });
expect(launchConfigFor(flutter(), "/p")?.extraJson).toBeNull();
});
});
describe("run config → launch config", () => {
it("returns null without an adapter", () => {
expect(launchConfigFor(rc({}), "/p")).toBeNull();
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff. Show more