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

...
Автор SHA1 Повідомлення Дата
arookieofc 7c46cf7719 i18n: add zh translation for 'Sessions from other apps' 2026-11-11 11:25:43 +08:00
arookieofc 5638c3386b feat(agents): list and import sessions started outside OpenIDEA
Sessions started in a terminal, another editor or the CLIs never showed
up in OpenIDEA, so users had to re-explain their work (#312). The agent
history popup now lists them under Sessions from other apps: Claude Code
transcripts and Codex rollouts on this machine, with title, working
directory and age. Importing one creates a task whose first turn loads
and replays the transcript through the existing session/load path.
2026-11-11 11:21:51 +08:00
arookieofc 14e4881418 fix(debug): load run configuration .env files for debug launches (#2633)
Debug launches only copied the explicit env map into the DAP launch
arguments and dropped the configuration's .env files, which Run loads
via ide_run::envfile. Add a run_env_files command that loads the files
with the same loader over the system environment, and merge the result
under the explicit variables when building debug launches (generic,
plugin-hosted and java-debug paths); explicit variables still win and a
missing file fails the launch with the same error Run reports.

Fixes #753 (comment): .env applied in Run but ignored in Debug.
2026-11-11 10:41:16 +08:00
l0ng-ai 55bc093fe5 chore: v0.1.41 2026-11-11 09:51:47 +08:00
l0ng-ai 37ba544733 fix(run): run JUnit configurations with the build's JDK (#2627)
JUnit configurations in Maven and Gradle projects ran their build command without the project JDK, so with no JAVA_HOME the build failed with "Unable to locate a Java Runtime". apply_to_run_configs now gives junit configurations the Maven runner or Gradle build environment (JDK, MAVEN_OPTS, settings) without changing the command line, and ide-host applies it to junit configurations.
2026-11-11 09:42:19 +08:00
55 змінених файлів з 846 додано та 89 видалено

No files matched your search

Створено
+39 -39
Переглянути файл
@@ -4145,7 +4145,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"dunce",
"encoding_rs",
@@ -4169,7 +4169,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4183,7 +4183,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"ide-core",
"serde",
@@ -4194,7 +4194,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"blake3",
"chardetng",
@@ -4212,7 +4212,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4226,7 +4226,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4236,7 +4236,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"dunce",
"encoding_rs",
@@ -4253,7 +4253,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"ide-core",
"ide-run",
@@ -4267,7 +4267,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"futures",
"ide-core",
@@ -4288,7 +4288,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"bb8",
"blake3",
@@ -4318,7 +4318,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"ide-core",
"serde",
@@ -4331,7 +4331,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4352,7 +4352,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4364,7 +4364,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4377,7 +4377,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4443,7 +4443,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"ide-core",
"ide-vfs",
@@ -4462,7 +4462,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"blake3",
"criterion",
@@ -4484,7 +4484,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"encoding_rs",
"futures",
@@ -4501,7 +4501,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"blake3",
"criterion",
@@ -4557,7 +4557,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"dunce",
"futures",
@@ -4583,7 +4583,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"bytes",
"dunce",
@@ -4602,7 +4602,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"futures",
"ide-core",
@@ -4625,7 +4625,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"blake3",
"dunce",
@@ -4648,7 +4648,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"ide-core",
"ide-run",
@@ -4661,7 +4661,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"dunce",
"globset",
@@ -4680,7 +4680,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"dunce",
"encoding_rs",
@@ -4704,7 +4704,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"dunce",
"ide-core",
@@ -4724,7 +4724,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"criterion",
"globset",
@@ -4744,7 +4744,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"ide-core",
"parking_lot",
@@ -4757,7 +4757,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4778,7 +4778,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"ide-core",
"ide-language",
@@ -4793,7 +4793,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"ide-core",
"libc",
@@ -4806,7 +4806,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"criterion",
"ide-core",
@@ -4819,7 +4819,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"flate2",
"hex",
@@ -4840,7 +4840,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"blake3",
"dunce",
@@ -4861,7 +4861,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"chardetng",
"dunce",
@@ -4885,7 +4885,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"ide-core",
"open",
@@ -4901,7 +4901,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"blake3",
"dunce",
@@ -6479,7 +6479,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.40"
version = "0.1.41"
dependencies = [
"base64 0.22.1",
"blake3",
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.40"
version = "0.1.41"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+270
Переглянути файл
@@ -0,0 +1,270 @@
//! Sessions the user started outside OpenIDEA (a terminal, another editor, the CLI):
//! scanned so they can be listed and imported as tasks instead of re-explained (#312).
//!
//! Only the native providers keep transcripts on disk in a readable form: Claude Code
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`) and Codex
//! (`<home>/.codex/sessions/**`, rollout files with a `session_meta` line).
use super::native::claude::history;
use serde::Serialize;
use specta::Type;
use std::path::{Path, PathBuf};
/// A session on this machine that no task holds yet.
#[derive(Clone, Debug, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExternalSession {
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`).
pub provider: String,
/// The id resuming it names (`--resume`, `thread/resume`).
pub session_id: String,
pub title: String,
/// Where it ran, when the transcript names one.
pub cwd: Option<String>,
/// File modification time, ms since the epoch.
pub updated_ms: f64,
}
/// Modification time of `path` in ms, else 0.
fn mtime(path: &Path) -> f64 {
path.metadata()
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as f64)
.unwrap_or(0.0)
}
/// Short display text: collapsed whitespace, truncated to `MAX_TITLE` chars.
fn short(text: &str) -> String {
const MAX_TITLE: usize = 80;
let flat: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
if flat.chars().count() <= MAX_TITLE {
flat
} else {
format!("{}…", flat.chars().take(MAX_TITLE - 1).collect::<String>())
}
}
/// The text of a Claude Code transcript entry's message, when it carries prose.
fn message_text(e: &serde_json::Value) -> Option<String> {
match e.pointer("/message/content") {
Some(serde_json::Value::String(s)) => Some(s.clone()),
Some(serde_json::Value::Array(blocks)) => {
let text: Vec<&str> = blocks
.iter()
.filter(|b| b.get("type").and_then(serde_json::Value::as_str) == Some("text"))
.filter_map(|b| b.get("text").and_then(serde_json::Value::as_str))
.collect();
(!text.is_empty()).then(|| text.join("\n"))
}
_ => None,
}
}
/// Claude Code transcripts: `<config>/projects/*/<id>.jsonl`.
pub fn claude_sessions(config_dir: &Path) -> Vec<ExternalSession> {
let mut out = Vec::new();
let projects = config_dir.join("projects");
let dirs: Vec<PathBuf> = std::fs::read_dir(&projects).into_iter().flatten().flatten().map(|d| d.path()).collect();
for dir in dirs {
let files: Vec<PathBuf> = std::fs::read_dir(&dir)
.into_iter()
.flatten()
.flatten()
.map(|d| d.path())
.filter(|p| p.extension().is_some_and(|e| e == "jsonl"))
.collect();
for path in files {
let id = path.file_stem().and_then(|s| s.to_str()).unwrap_or_default().to_owned();
if id.is_empty() {
continue;
}
let entries = history::read(&path).unwrap_or_default();
if entries.is_empty() {
continue;
}
let title = history::title(&entries)
.or_else(|| entries.iter().filter(|e| history::is_turn_start(e)).filter_map(message_text).next())
.map(|t| short(&t))
.unwrap_or_else(|| format!("Claude Code session {}", &id[..id.len().min(8)]));
let cwd = entries
.iter()
.filter_map(|e| e.get("cwd").and_then(serde_json::Value::as_str))
.next()
.map(str::to_owned);
out.push(ExternalSession {
provider: "claude".to_owned(),
session_id: id,
title,
cwd,
updated_ms: mtime(&path),
});
}
}
out
}
/// The `session_meta` line of a Codex rollout file: `(id, cwd)`, across shapes.
fn codex_meta(line: &serde_json::Value) -> Option<(String, Option<String>)> {
let payload =
line.get("payload").filter(|p| p.get("type").and_then(serde_json::Value::as_str) == Some("session_meta"));
let inner = payload.and_then(|p| p.get("payload")).or_else(|| {
line.get("type").and_then(serde_json::Value::as_str).filter(|t| *t == "session_meta").and(Some(line))
})?;
let id = inner.get("id").and_then(serde_json::Value::as_str)?.to_owned();
let cwd = inner.get("cwd").and_then(serde_json::Value::as_str).map(str::to_owned);
Some((id, cwd))
}
/// A prose line of a Codex rollout file (a user message), across shapes.
fn codex_user_text(line: &serde_json::Value) -> Option<String> {
let payload = line.get("payload")?;
let ty = payload.get("type").and_then(serde_json::Value::as_str)?;
if !(ty == "user_message" || ty == "userMessage" || ty == "event_msg") {
return None;
}
let inner = payload.get("payload").unwrap_or(&serde_json::Value::Null);
for v in [payload, inner] {
if let Some(s) = v.get("message").and_then(serde_json::Value::as_str) {
return Some(s.to_owned());
}
if let Some(s) = v.get("text").and_then(serde_json::Value::as_str) {
return Some(s.to_owned());
}
}
None
}
/// One rollout file's session, or `None` when it names no `session_meta`.
fn codex_file(path: &Path) -> Option<ExternalSession> {
let text = std::fs::read_to_string(path).ok()?;
let mut id: Option<(String, Option<String>)> = None;
let mut title: Option<String> = None;
// `session_meta` is first, but cap the scan: giant rollouts must not stall listing.
for line in text.lines().take(400) {
let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else { continue };
if id.is_none()
&& let Some(meta) = codex_meta(&v)
{
id = Some(meta);
}
if title.is_none()
&& let Some(t) = codex_user_text(&v)
{
title = Some(short(&t));
}
if id.is_some() && title.is_some() {
break;
}
}
let (session_id, cwd) = id?;
Some(ExternalSession {
provider: "codex".to_owned(),
title: title.unwrap_or_else(|| format!("Codex session {}", &session_id[..session_id.len().min(8)])),
session_id,
cwd,
updated_ms: mtime(path),
})
}
/// Collects `*.jsonl` below `dir`, up to 4 levels (`sessions/YYYY/MM/DD/<rollout>`).
fn rollout_files(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
if depth == 0 {
return;
}
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let path = entry.path();
if path.is_dir() {
rollout_files(&path, depth - 1, out);
} else if path.extension().is_some_and(|e| e == "jsonl") {
out.push(path);
}
}
}
/// Codex sessions: `<home>/.codex/sessions/**`.
pub fn codex_sessions(codex_home: &Path) -> Vec<ExternalSession> {
let mut files = Vec::new();
rollout_files(&codex_home.join("sessions"), 4, &mut files);
files.iter().filter_map(|p| codex_file(p)).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use std::io::Write;
fn write(path: &Path, lines: &[serde_json::Value]) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut f = std::fs::File::create(path).unwrap();
for line in lines {
writeln!(f, "{line}").unwrap();
}
}
fn claude_user(uuid: &str, text: &str) -> serde_json::Value {
json!({"type": "user", "uuid": uuid, "parentUuid": null,
"message": {"role": "user", "content": text}, "cwd": "/work/app"})
}
#[test]
fn lists_claude_transcripts_with_titles() {
let tmp = tempfile::tempdir().unwrap();
write(
&tmp.path().join("projects/-work-app/abc123.jsonl"),
&[
claude_user("u1", "fix the login bug"),
json!({"type": "assistant", "uuid": "a1", "parentUuid": "u1",
"message": {"role": "assistant", "content": []}}),
json!({"type": "ai-title", "aiTitle": "Login fix"}),
],
);
write(&tmp.path().join("projects/-work-app/empty.jsonl"), &[]);
let sessions = claude_sessions(tmp.path());
assert_eq!(sessions.len(), 1);
let s = &sessions[0];
assert_eq!((s.provider.as_str(), s.session_id.as_str()), ("claude", "abc123"));
assert_eq!(s.title, "Login fix");
assert_eq!(s.cwd.as_deref(), Some("/work/app"));
assert!(s.updated_ms > 0.0);
}
#[test]
fn claude_title_falls_back_to_the_first_prompt() {
let tmp = tempfile::tempdir().unwrap();
write(&tmp.path().join("projects/-x/def456.jsonl"), &[claude_user("u1", "hello there")]);
let sessions = claude_sessions(tmp.path());
assert_eq!(sessions.len(), 1);
assert_eq!(sessions[0].title, "hello there");
}
#[test]
fn lists_codex_rollouts_with_meta() {
let tmp = tempfile::tempdir().unwrap();
write(
&tmp.path().join("sessions/2026/01/02/rollout-01.jsonl"),
&[
json!({"timestamp": "t", "payload": {"type": "session_meta",
"payload": {"id": "thread-1", "cwd": "/work/app"}}}),
json!({"timestamp": "t", "payload": {"type": "user_message",
"payload": {"message": "add tests"}}}),
],
);
write(&tmp.path().join("sessions/notes.jsonl"), &[json!({"nope": true})]);
let sessions = codex_sessions(tmp.path());
assert_eq!(sessions.len(), 1);
let s = &sessions[0];
assert_eq!((s.provider.as_str(), s.session_id.as_str()), ("codex", "thread-1"));
assert_eq!(s.title, "add tests");
assert_eq!(s.cwd.as_deref(), Some("/work/app"));
}
#[test]
fn missing_directories_list_nothing() {
let tmp = tempfile::tempdir().unwrap();
assert!(claude_sessions(&tmp.path().join("nope")).is_empty());
assert!(codex_sessions(&tmp.path().join("nope")).is_empty());
}
}
+92
Переглянути файл
@@ -10,6 +10,7 @@
mod acp;
mod config;
mod conversation;
mod external;
pub mod mcp;
mod model;
mod native;
@@ -19,6 +20,7 @@ mod skills;
mod timeline;
mod worktree;
pub use external::ExternalSession;
pub use model::*;
use conversation::{Conversation, SavedSubagent, Session};
@@ -585,6 +587,91 @@ impl AgentManager {
Ok(timeline.entries.clone())
}
/// Session ids the tasks already hold (native drivers reuse the CLI's own id).
fn imported_session_ids(&self) -> HashSet<String> {
self.tasks.read().values().filter_map(|t| t.state.lock().session_id.clone()).collect()
}
/// Sessions on this machine that no task holds yet, newest first (#312).
pub fn external_sessions(&self) -> Vec<ExternalSession> {
let mut out = Vec::new();
if let Some(spec) = self.shared.spec("claude")
&& let Some(dir) = native::claude::cli::config_dir(&spec.env)
{
out.extend(external::claude_sessions(&dir));
}
let home = self.shared.paths.home_dir.clone().or_else(home_dir);
if let Some(home) = home {
out.extend(external::codex_sessions(&home.join(".codex")));
}
let known = self.imported_session_ids();
out.retain(|s| !known.contains(&s.session_id));
out.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
out.truncate(50);
out
}
/// Imports an external session as a task: its first turn loads and replays it (#312).
pub fn import_session(&self, provider: &str, session_id: &str) -> IdeResult<AgentTask> {
if !matches!(provider, "claude" | "codex") {
return Err(IdeError::invalid(format!("cannot import {provider} sessions")));
}
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
if self.imported_session_ids().contains(session_id) {
return Err(IdeError::invalid("that session is already a task"));
}
let found = self
.external_sessions()
.into_iter()
.find(|s| s.provider == provider && s.session_id == session_id)
.ok_or_else(|| IdeError::not_found(format!("unknown {provider} session {session_id}")))?;
let root = self.shared.paths.project_root.clone();
let cwd = found.cwd.map(PathBuf::from).filter(|p| p.is_absolute()).unwrap_or_else(|| root.clone());
let config = self.shared.known_config(&spec.id);
let now = now_ms();
let id = uuid::Uuid::new_v4().simple().to_string();
let task = AgentTask {
project_root: Some(IpcPath(root)),
id,
title: found.title,
provider: spec.id.clone(),
model: model_of(&config),
status: AgentStatus::Ready,
isolation: Isolation::Local,
cwd: IpcPath(cwd),
branch: None,
base: None,
base_commit: None,
error: None,
created_ms: now,
updated_ms: now,
config,
commands: self.shared.known_commands(&spec.id),
usage: None,
queue: Vec::new(),
capabilities: self.shared.probes.lock().get(&spec.id).map(|p| p.capabilities).unwrap_or_default(),
resets_ms: None,
retry: None,
background: Box::default(),
};
let file = TaskFile {
task: task.clone(),
session_id: Some(session_id.to_owned()),
entries: Vec::new(),
wanted: Vec::new(),
before: BTreeMap::new(),
saved: None,
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: true,
};
let handle = Task::restore(file, self.shared.clone());
self.tasks.write().insert(task.id.clone(), handle.clone());
handle.emit_task();
handle.persist();
Ok(task)
}
/// Creates the task (and its worktree) and sends `req.prompt` as its first message.
pub async fn create(&self, req: NewAgentTask) -> IdeResult<AgentTask> {
let spec = self
@@ -2429,6 +2516,11 @@ fn now_ms() -> f64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_millis() as f64)
}
/// The user's home, for tools that keep state there (Codex sessions).
fn home_dir() -> Option<PathBuf> {
std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from)
}
fn write_file(path: &Path, bytes: &[u8]) -> Result<(), String> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
+1 -1
Переглянути файл
@@ -135,7 +135,7 @@ impl Cli for Process {
}
/// Claude Code's configuration directory (`CLAUDE_CONFIG_DIR`, else `~/.claude`).
pub(super) fn config_dir(env: &[(String, String)]) -> Option<PathBuf> {
pub(crate) fn config_dir(env: &[(String, String)]) -> Option<PathBuf> {
let set = env
.iter()
.find(|(k, _)| k == "CLAUDE_CONFIG_DIR")
+3 -3
Переглянути файл
@@ -35,7 +35,7 @@ pub(super) fn escape(cwd: &Path) -> String {
cwd.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect()
}
pub(super) fn read(path: &Path) -> std::io::Result<Vec<Value>> {
pub(crate) fn read(path: &Path) -> std::io::Result<Vec<Value>> {
let text = std::fs::read_to_string(path)?;
Ok(text.lines().filter_map(|l| serde_json::from_str(l).ok()).collect())
}
@@ -111,7 +111,7 @@ fn block_ids<'a>(e: &'a Value, ty: &'a str, key: &'a str) -> impl Iterator<Item
/// Whether `e` is a message that started a turn: the user's own, not a tool result, a
/// steer, or text Claude Code added.
pub(super) fn is_turn_start(e: &Value) -> bool {
pub(crate) fn is_turn_start(e: &Value) -> bool {
if kind(e) != "user" || e.get("isMeta").and_then(Value::as_bool) == Some(true) {
return false;
}
@@ -149,7 +149,7 @@ pub(super) fn cut(chain: &[&Value], turns: usize) -> Result<Option<String>, Stri
}
/// The newest title Claude Code gave the session.
pub(super) fn title(entries: &[Value]) -> Option<String> {
pub(crate) fn title(entries: &[Value]) -> Option<String> {
entries
.iter()
.rev()
+2 -2
Переглянути файл
@@ -7,8 +7,8 @@
//! <id>.json`): loading that session, from this connection or a fresh one, starts it that
//! way.
mod cli;
mod history;
pub(crate) mod cli;
pub(crate) mod history;
mod settings;
mod tools;
mod translate;
+16 -1
Переглянути файл
@@ -6,7 +6,7 @@ use crate::rpc::Dispatcher;
use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AgentChange, AgentCommand, AgentEntry, AgentEvent, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentTask,
McpScope, McpServer, McpServerInput, NewAgentTask,
ExternalSession, McpScope, McpServer, McpServerInput, NewAgentTask,
};
use ide_core::error::ErrorKind;
use ide_core::{IdeError, IdeEvent, IdeResult, IpcPath, RequestId, SharedSink, TaskId};
@@ -181,6 +181,17 @@ pub fn entries(host: &Host, window: &str, task: String, subagent: Option<String>
host.project(window)?.agents.entries(&task, subagent)
}
/// Sessions on this machine that no task holds yet, newest first (#312).
pub fn external_sessions(host: &Host, window: &str) -> IdeResult<Vec<ExternalSession>> {
Ok(host.project(window)?.agents.external_sessions())
}
/// Imports an external session as a task: its first turn loads and replays it (#312).
pub fn import_session(host: &Host, window: &str, provider: String, session_id: String) -> IdeResult<AgentTask> {
host.require_trust(window)?;
host.project(window)?.agents.import_session(&provider, &session_id)
}
pub async fn create(host: &Host, window: &str, mut request: NewAgentTask) -> IdeResult<AgentTask> {
host.require_trust(window)?;
let project = host.project(window)?;
@@ -398,6 +409,10 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("agent_commands", |c| async move { commands(&c.host, &c.window, c.arg("provider")?, c.arg("task")?).await });
d.add("agent_entries", |c| async move { entries(&c.host, &c.window, c.arg("task")?, c.arg("subagent")?) });
d.add("agent_create", |c| async move { create(&c.host, &c.window, c.arg("request")?).await });
d.add("agent_external_sessions", |c| async move { external_sessions(&c.host, &c.window) });
d.add("agent_import_session", |c| async move {
import_session(&c.host, &c.window, c.arg("provider")?, c.arg("sessionId")?)
});
d.add("agent_prompt", |c| async move {
prompt(&c.host, &c.window, c.arg("task")?, c.arg("prompt")?, c.arg("now")?).await
});
+1 -1
Переглянути файл
@@ -337,7 +337,7 @@ async fn start_inner(
// what makes the setting take effect without reopening the project.
if config.kind == "maven" {
ide_sdk::apply::prepare_maven_run(&mut config, root, &settings);
} else if matches!(config.kind.as_str(), "gradle" | "tomcat") {
} else if matches!(config.kind.as_str(), "gradle" | "tomcat" | "junit") {
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
} else {
ide_sdk::apply::resolve_run_command(&mut config, root, &settings);
+12
Переглянути файл
@@ -130,6 +130,17 @@ pub fn run_system_env(_host: &Host, _window: &str) -> std::collections::BTreeMap
ide_run::system_env()
}
/// Variables of the `.env` files a debug launch names, in order (later files win):
/// the same files a run loads, over the system environment debug adapters inherit.
pub fn run_env_files(
_host: &Host,
_window: &str,
files: Vec<std::path::PathBuf>,
) -> IdeResult<std::collections::BTreeMap<String, String>> {
ide_run::envfile::load(&files, &ide_run::system_env())
.map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))
}
/// Writes the Gradle init script that adds `jvm_args` to the JVMs the build forks
/// (`bootRun`, `run`, tests) and returns its path, for `--init-script`.
pub async fn run_gradle_jvm_args_script(_host: &Host, _window: &str, jvm_args: Vec<String>) -> IdeResult<String> {
@@ -332,6 +343,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
run_import_configs(&c.host, &c.window, c.arg("source")?, c.arg("existing")?)
});
d.add("run_system_env", |c| async move { Ok(run_system_env(&c.host, &c.window)) });
d.add("run_env_files", |c| async move { run_env_files(&c.host, &c.window, c.arg("files")?) });
d.add("run_gradle_jvm_args_script", |c| async move {
run_gradle_jvm_args_script(&c.host, &c.window, c.arg("jvmArgs")?).await
});
+19
Переглянути файл
@@ -157,3 +157,22 @@ async fn gradle_init_scripts_are_written_by_the_host_that_runs_the_build() {
let escaped = ops::run::run_gradle_init_script(&host, "main", "../escape".into(), String::new()).await;
assert!(escaped.is_err(), "{escaped:?}");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn debug_env_files_load_in_order_like_a_run() {
let tmp = tempfile::tempdir().unwrap();
let host = host(tmp.path());
let first = tmp.path().join("first.env");
let second = tmp.path().join("second.env");
std::fs::write(&first, "SHARED=one\nONLY_FIRST=1\nREF=${SHARED}-suffix\n").unwrap();
std::fs::write(&second, "SHARED=two\nONLY_SECOND=2\n").unwrap();
let vars = ops::run::run_env_files(&host, "main", vec![first, second]).unwrap();
// Later files win; references resolve against earlier files, then the system environment.
assert_eq!(vars.get("SHARED").map(String::as_str), Some("two"));
assert_eq!(vars.get("ONLY_FIRST").map(String::as_str), Some("1"));
assert_eq!(vars.get("ONLY_SECOND").map(String::as_str), Some("2"));
assert_eq!(vars.get("REF").map(String::as_str), Some("one-suffix"));
// An unreadable file is an error, like a run that names a missing `.env`.
let missing = ops::run::run_env_files(&host, "main", vec![tmp.path().join("nope.env")]);
assert!(missing.is_err(), "{missing:?}");
}
+18
Переглянути файл
@@ -1561,6 +1561,24 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
c.env.entry("JAVA_HOME".into()).or_insert_with(|| jdk.home.to_string_lossy().into_owned());
}
}
// A JUnit configuration runs the module's own Maven or Gradle command line: it needs
// that build's environment (its JDK), not another launcher or extra options.
"junit" => {
let name = Path::new(&c.command).file_name().map(|n| n.to_string_lossy().to_ascii_lowercase());
match name.as_deref() {
Some(n) if n.starts_with("mvn") => apply_maven_env(c, root, s),
Some(n) if n.starts_with("gradle") => {
let build_dir =
c.cwd.as_ref().map(|p| root.join(p.as_ref())).unwrap_or_else(|| root.to_path_buf());
let env = gradle_build_env(root, &build_dir, &c.command, s, None);
apply_java_home(c, &env, java_home_is_derived(c));
for (key, value) in env {
c.env.entry(key).or_insert(value);
}
}
_ => {}
}
}
"maven" => {
apply_maven_env(c, root, s);
if let Some(mvn) = &mvn
+13
Переглянути файл
@@ -409,6 +409,19 @@ fn project_jdk_and_maven_settings() {
);
assert_eq!(configs[0].env["JAVA_HOME"], home);
assert_eq!(configs[1].env["JAVA_HOME"], home);
// JUnit runs the build's own command line: the build's JDK, its command and arguments unchanged.
let mut junit = vec![
run("junit", "./mvnw", &["test", "-Dtest=a.T"]),
run("junit", "./gradlew", &[":api:test", "--tests", "a.T"]),
];
apply_to_run_configs(&mut junit, tmp.path(), &s);
assert_eq!(
(junit[0].command.as_str(), junit[0].args.as_slice()),
("./mvnw", &["test".to_owned(), "-Dtest=a.T".to_owned()][..])
);
assert_eq!(junit[0].env["JAVA_HOME"], home);
assert_eq!(junit[1].command, "./gradlew");
assert_eq!(junit[1].env["JAVA_HOME"], home);
apply_to_run_configs(&mut configs, tmp.path(), &s);
assert_eq!(configs[0].args.len(), 6, "applied once");
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.40",
"version": "0.1.41",
"license": "Apache-2.0",
"type": "module",
"scripts": {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// The commit being prepared in the window the current command or event came
/// from (the Commit tool window, or the Commit dialog while it is open): the
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Plugin-owned project data sources. Requires database.sources and project trust.
/// Runs on the Database subsystem's host, including on remote project servers.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Project-scoped decorations (API 1.4). Requires project.read; paths must be inside
/// an open project. Sets belong to the plugin and disappear when it stops.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// What the pane beside the Services tree shows for a plugin's node.
interface detail-types {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Optional export (world `plugin-diagnostics`): problems in the current,
/// possibly unsaved document, for the languages declared with the
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
interface endpoints-provider {
+4 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Workbench events, delivered in batches to `event-handler.handle`.
interface events {
@@ -32,6 +32,9 @@ interface events {
/// API 1.4 also delivers `file-closed` (JSON path string), `settings-changed`
/// (JSON array of the plugin's changed setting keys), and `input-mode-changed`
/// (JSON {path, mode, sub}) through `other`. The last needs `events.input`.
/// API 1.5 also delivers `extensions-changed` (JSON array of the extension
/// points this plugin declares whose contributions changed) through `other`,
/// to the declaring plugin only and without a capability.
/// Kinds: `file-opened`, `file-saved`, `files-changed` (batched disk changes
/// as `other`, with created/modified/removed path lists in JSON), `editor-focused` (the focused editor
/// changed), `vcs-changed` (a repository's state changed: commit,
+20 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
interface lifecycle {
use types.{context, error};
@@ -73,3 +73,22 @@ interface syntax-provider {
outline: func(language: string, text: string) -> list<symbol>;
folding: func(language: string, text: string) -> list<fold>;
}
/// Optional pre-launch gate for targets owned by this plugin (API 1.5).
interface run-target-validation {
enum operation { run, test }
record launch-info {
operation: operation,
/// Bare program name before wrapping; no arguments or environment.
program: string,
/// Absolute working directory on the machine hosting the plugin.
cwd: string,
}
/// Called after trust, ownership, process grants and executable pin checks.
/// An error refuses the launch without changing the selected target. The
/// host prefixes and bounds the message. Missing exports allow the launch.
/// Calls wake reclaimed instances, use the host call timeout (5s by default),
/// and are cancelled with the launch. Traps/timeouts refuse the launch.
/// For remote projects this runs on the server, where the plugin lives.
validate: func(project: string, target-id: string, launch: launch-info) -> result<_, string>;
}
+21
Переглянути файл
@@ -0,0 +1,21 @@
package openidea:[email protected];
/// What other plugins contributed to the extension points this plugin declares
/// (`[[extension-points]]` in `plugin.toml`; the contributors list this plugin
/// in `[[depends]]`). A change is announced by the `extensions-changed` event.
interface extensions {
use types.{error};
record contribution {
/// The contributing plugin's id.
plugin: string,
/// Its `[[contributes."<point>"]]` table as JSON, checked by the host
/// against the fields the point declares.
data: string,
}
/// The contributions to `point`, in the order the plugins started. Only the
/// plugin that declares `point` may read it (`denied` otherwise); `not-found`
/// when no running plugin declares it.
contributions: func(point: string) -> result<list<contribution>, error>;
}
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Optional export (world `plugin-file-actions`): quick fixes and
/// refactorings that create, rename or delete files, next to the text edits
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Files outside the open projects: the configuration of the program a
/// plugin integrates with, a tool installed elsewhere, a licence file.
+8 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Writes to the IDE log, tagged with the plugin id.
interface log {
@@ -9,6 +9,7 @@ interface log {
interface ui {
use types.{error, notification-level};
use workspace.{project};
record status-item {
text: string,
@@ -50,6 +51,12 @@ interface ui {
/// dismisses the balloon and runs the command in its window. An invalid
/// action or an undeclared command fails the call and shows nothing.
notify: func(level: notification-level, title: string, body: string, actions: list<notification-action>) -> result<_, error>;
/// `notify` in a window of `target` only (API 1.5), with or without an
/// invoking window: the most recently focused one when the project is open
/// in several. Actions run in that window. A project closed by the time of
/// the call fails it with `not-found` and shows nothing; there is no
/// fallback to another window. A shown balloon goes away with its window.
notify-project: func(target: borrow<project>, level: notification-level, title: string, body: string, actions: list<notification-action>) -> result<_, error>;
/// Shows or updates the plugin's status bar item `id` in every window.
set-status-item: func(id: string, item: status-item);
remove-status-item: func(id: string);
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Optional export (world `plugin-hover`): Markdown added to the hover of
/// documents of the languages declared with the `hover` provider kind,
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Cross-file associations a plugin publishes for the files it declares under
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Embedded languages. The host routes plugin providers and configured language
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
/// the languages declared with the `inlay-hints` provider kind, including
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Problems in files, shown in the editor and the Problems view.
interface diagnostics {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Additional language features, called only for declared API 1.4 provider kinds.
/// Editor calls have a 50 ms soft / 500 ms hard budget; formatting has 5 seconds.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Discovery of the IDE's built-in MCP server; never exposes its URL or token.
interface mcp {
+7 -1
Переглянути файл
@@ -8,7 +8,7 @@
/// `fs` and `workspace`, and everything else goes through the imports below,
/// gated by the capabilities granted in `plugin.toml` (a missing one returns
/// `error::denied`).
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
world plugin {
import log;
@@ -37,6 +37,7 @@ world plugin {
import database;
import mcp;
import settings;
import extensions;
export lifecycle;
export commands;
@@ -200,3 +201,8 @@ world language-injections { export injections; }
world plugin-mcp { include plugin; export mcp-provider; }
/// Export-only MCP tools, composed with the base plugin world.
world mcp-tools { export mcp-provider; }
/// A plugin that validates launches through its run targets (API 1.5).
world plugin-run-target-validation { include plugin; export run-target-validation; }
/// Export-only validation, composed with the base plugin world.
world run-target-validator { export run-target-validation; }
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Editor features a plugin provides for the languages it declares under
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
+25 -5
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Project-scoped targets owned by the registering plugin (API 1.4).
interface run-targets {
@@ -16,10 +16,7 @@ interface run-targets {
/// Without workdir-args the wrapper manages its container directory itself.
/// The wrapper always starts in the configuration's LOCAL working directory.
/// Environment reaches the wrapper; forwarding into a container depends on its conventions.
/// Registration never selects the target. Debugging requires container-root and an
/// explicitly supported language debugger placement. Connect-back adapters listen
/// on the host; the target must configure the debuggee to connect to that host.
/// Stdio adapters run inside the target and must be installed there.
/// Registration never selects the target. Debugging plugin targets is invalid.
record run-target {
id: string,
name: string,
@@ -34,6 +31,29 @@ interface run-targets {
/// Targets survive idle reclamation, and disappear on unregister or plugin stop.
/// Remote project registration and execution take place on the server.
register: func(project: borrow<project>, target: run-target) -> result<_, error>;
/// Per-command prefix and optional replacement working-directory arguments (API 1.5).
/// None inherits the target's workdir-args; some([]) omits them.
/// Replacement arguments use the same {cwd} substitution and path restrictions.
record command-override {
name: string,
args: list<string>,
workdir-args: option<list<string>>,
}
/// Like run-target, with per-command working-directory argument control (API 1.5).
/// Matching commands use program + override args + selected workdir-args + command arguments.
record run-target-with-overrides {
id: string,
name: string,
program: string,
args: list<string>,
workdir-args: list<string>,
container-root: option<string>,
commands: list<command-override>,
}
/// Same ownership, trust, process grant and pin checks as register (API 1.5).
register-with-overrides: func(project: borrow<project>, target: run-target-with-overrides) -> result<_, error>;
/// Removes only this plugin's target from the project; missing ids are harmless.
unregister: func(project: borrow<project>, id: string);
}
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Launches this plugin's configurations in the invoking window's Run tool window.
interface run {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Optional export (world `plugin-semantic-tokens`): semantic colouring of
/// documents of the languages declared with the `semantic-tokens` provider
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
/// as in the editor and LSP.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
/// Declarative views: tool windows declared
/// under `[[contributes.views]]` and custom editors under
+7 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.4.0;
package openidea:plugin@1.5.0;
interface workspace {
use types.{error, location};
@@ -66,6 +66,12 @@ interface workspace {
/// contents win over the disk. A missing path is `not-found`.
/// Requires `project.read`.
read-file: func(path: string) -> result<string, error>;
/// Reads the bytes of a file inside the project (absolute, or
/// relative to the root) — images, archives, fonts — at most 16 MiB,
/// as `fs.read-bytes` allows; paths leaving the root are refused and
/// a missing path is `not-found`. The file on disk: unsaved editor
/// contents don't apply. Requires `project.read`.
read-bytes: func(path: string) -> result<list<u8>, error>;
/// Replaces the text of a file inside the project (absolute, or
/// relative to the root), or creates it with missing parent
/// directories; paths leaving the root are refused. Written in one
+20 -1
Переглянути файл
@@ -4,7 +4,7 @@ use crate::state::AppState;
use ide_agent::registry::AgentRegistry;
use ide_agent::{
AgentChange, AgentCommand, AgentEntry, AgentEvent, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentTask,
McpServer, McpServerInput, NewAgentTask,
ExternalSession, McpServer, McpServerInput, NewAgentTask,
};
use ide_core::{IdeResult, IpcPath, RequestId};
use ide_host::ops::agent;
@@ -166,6 +166,25 @@ pub async fn agent_create(window: Window, state: State<'_, AppState>, request: N
agent::create(&state.host, window.label(), request).await
}
/// Sessions on this machine that no task holds yet, newest first (#312).
#[tauri::command]
#[specta::specta]
pub fn agent_external_sessions(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<ExternalSession>> {
agent::external_sessions(&state.host, window.label())
}
/// Imports an external session as a task: its first turn loads and replays it (#312).
#[tauri::command]
#[specta::specta]
pub fn agent_import_session(
window: Window,
state: State<'_, AppState>,
provider: String,
session_id: String,
) -> IdeResult<AgentTask> {
agent::import_session(&state.host, window.label(), provider, session_id)
}
/// Sends a message; while the agent works it is queued, or with `now` it interrupts the turn.
#[tauri::command]
#[specta::specta]
+3
Переглянути файл
@@ -128,6 +128,8 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
agent::agent_commands,
agent::agent_entries,
agent::agent_create,
agent::agent_external_sessions,
agent::agent_import_session,
agent::agent_prompt,
agent::agent_unqueue,
agent::agent_send_queued_now,
@@ -380,6 +382,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
run::run_import_sources,
run::run_import_configs,
run::run_system_env,
run::run_env_files,
run::run_start,
run::run_stop,
run::run_stdin,
+11
Переглянути файл
@@ -179,6 +179,17 @@ pub fn run_system_env(state: State<'_, AppState>) -> std::collections::BTreeMap<
ide_host::ops::run::run_system_env(&state.host, "")
}
/// Variables of the `.env` files a debug launch names, for the debugger to start with.
#[tauri::command]
#[specta::specta]
pub fn run_env_files(
window: Window,
state: State<'_, AppState>,
files: Vec<std::path::PathBuf>,
) -> IdeResult<std::collections::BTreeMap<String, String>> {
ide_host::ops::run::run_env_files(&state.host, window.label(), files)
}
/// Writes the Gradle init script adding `jvm_args` to the JVMs the build forks; returns its path.
#[tauri::command]
#[specta::specta]
+1 -1
Переглянути файл
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenIDEA",
"version": "0.1.40",
"version": "0.1.41",
"identifier": "ai.l0ng.openidea",
"build": {
"beforeDevCommand": "pnpm dev",
+19
Переглянути файл
@@ -162,6 +162,10 @@ export const commands = {
/** Entries of `task`'s conversation, or of its subagent `subagent`'s. */
agentEntries: (task: string, subagent: string | null) => typedError<AgentEntry[], IdeError>(__TAURI_INVOKE("agent_entries", { task, subagent })),
agentCreate: (request: NewAgentTask) => typedError<AgentTask, IdeError>(__TAURI_INVOKE("agent_create", { request })),
/** Sessions on this machine that no task holds yet, newest first (#312). */
agentExternalSessions: () => typedError<ExternalSession[], IdeError>(__TAURI_INVOKE("agent_external_sessions")),
/** Imports an external session as a task: its first turn loads and replays it (#312). */
agentImportSession: (provider: string, sessionId: string) => typedError<AgentTask, IdeError>(__TAURI_INVOKE("agent_import_session", { provider, sessionId })),
/** Sends a message; while the agent works it is queued, or with `now` it interrupts the turn. */
agentPrompt: (task: string, prompt: AgentPrompt, now: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("agent_prompt", { task, prompt, now })),
/** Drops a queued message and returns it (to edit it). */
@@ -733,6 +737,8 @@ export const commands = {
runImportConfigs: (source: RunImportSource, existing: RunConfig_Deserialize[]) => typedError<RunImport_Serialize, IdeError>(__TAURI_INVOKE("run_import_configs", { source, existing })),
/** The environment runs inherit when "Include system environment variables" is on. */
runSystemEnv: () => __TAURI_INVOKE<{ [key in string]: string }>("run_system_env"),
/** Variables of the `.env` files a debug launch names, for the debugger to start with. */
runEnvFiles: (files: string[]) => typedError<{ [key in string]: string }, IdeError>(__TAURI_INVOKE("run_env_files", { files })),
runStart: (config: RunConfig_Deserialize, onOutput: Channel<OutputChunk>, request: number | null) => typedError<RunInfo, IdeError>(__TAURI_INVOKE("run_start", { config, onOutput, request })),
runStop: (id: RunId) => typedError<null, IdeError>(__TAURI_INVOKE("run_stop", { id })),
runStdin: (id: RunId, data: string) => typedError<null, IdeError>(__TAURI_INVOKE("run_stdin", { id, data })),
@@ -4297,6 +4303,19 @@ export type ExternalFormatterSettings = {
runOnSave?: boolean,
};
/** A session on this machine that no task holds yet. */
export type ExternalSession = {
/** The [`crate::AgentProvider`] id that owns it (`claude`, `codex`). */
provider: string,
/** The id resuming it names (`--resume`, `thread/resume`). */
sessionId: string,
title: string,
/** Where it ran, when the transcript names one. */
cwd: string | null,
/** File modification time, ms since the epoch. */
updatedMs: number | null,
};
/** Tools › External Tools entry. */
export type ExternalTool = {
id?: string,
+12
Переглянути файл
@@ -187,3 +187,15 @@
border-bottom: 1px solid var(--border);
font-weight: 600;
}
/* Imported sessions below the task list: compact rows, not growing space. */
.external {
flex: none;
overflow-y: auto;
padding: 4px 12px 8px;
display: flex;
flex-direction: column;
gap: 4px;
}
.external > .row {
flex: none;
}
+45 -1
Переглянути файл
@@ -25,7 +25,7 @@ import {
sessionKey,
type TaskGroup,
} from "./model";
import { openHome, useAgents } from "./store";
import { importExternalSession, openHome, refreshExternalSessions, useAgents } from "./store";
import { taskMenu } from "./taskActions";
import { SessionEditor } from "./SessionEditor";
import { HomeEditor } from "./HomeEditor";
@@ -93,6 +93,19 @@ export function AgentsView() {
const inline = docked !== null || homeOpen;
const historyRef = useRef<HTMLButtonElement>(null);
const [historyOpen, setHistoryOpen] = useState(false);
const external = useAgents((s) => s.external);
const externalError = useAgents((s) => s.externalError);
const [importing, setImporting] = useState<string | null>(null);
// Sessions started elsewhere (a terminal, another editor) list on demand (#312).
useEffect(() => {
if (historyOpen) void refreshExternalSessions();
}, [historyOpen]);
const importSession = (provider: string, sessionId: string) => {
setImporting(`${provider}:${sessionId}`);
void importExternalSession(provider, sessionId)
.catch(() => {})
.finally(() => setImporting(null));
};
const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set(["g:archived"]));
const [selected, setSelected] = useState<Set<string>>(() => {
const task = sessionTask(maybeEditorService()?.activeInput?.());
@@ -285,6 +298,37 @@ export function AgentsView() {
<T>Agent sessions</T>
</div>
{taskList}
{(external.length > 0 || externalError) && (
<>
<div className={styles.historyTitle}>
<T>Sessions from other apps</T>
</div>
{externalError ? (
<div className={styles.empty}>{externalError}</div>
) : (
<div className={styles.external}>
{external.map((s) => {
const key = `${s.provider}:${s.sessionId}`;
return (
<div key={key} className={styles.row} title={s.cwd ?? s.sessionId}>
<Icon name={providerIcon(s.provider)} size={16} label={providerName(s.provider)} />
<span className={styles.title}>{s.title}</span>
<span className={styles.age}>{age(s.updatedMs ?? 0)}</span>
<button
type="button"
className={styles.link}
disabled={importing === key}
onClick={() => importSession(s.provider, s.sessionId)}
>
<T>Import</T>
</button>
</div>
);
})}
</div>
)}
</>
)}
</Popup>
)}
</div>
+57
Переглянути файл
@@ -22,6 +22,15 @@ const backend = vi.hoisted(() => ({
fetched: [] as string[],
entryError: null as string | null,
entryWait: null as Promise<void> | null,
external: [] as Array<{
provider: string;
sessionId: string;
title: string;
cwd: string | null;
updatedMs: number;
}>,
imported: [] as Array<[string, string]>,
externalError: null as string | null,
}));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
@@ -40,6 +49,16 @@ vi.mock("@/platform/ipc", async (original) => ({
backend.answers.push([task, permission, option]);
return { status: "ok", data: null };
},
agentExternalSessions: async () => {
if (backend.externalError !== null) throw new Error(backend.externalError);
return { status: "ok", data: backend.external };
},
agentImportSession: async (provider: string, sessionId: string) => {
backend.imported.push([provider, sessionId]);
const found = backend.external.find((e) => e.provider === provider && e.sessionId === sessionId);
if (!found) throw new Error("unknown session");
return { status: "ok", data: { ...task("imported"), id: "imported", title: found.title, provider } };
},
},
}));
vi.mock("@tauri-apps/api/webview", () => ({
@@ -118,6 +137,9 @@ beforeEach(() => {
disconnect();
localStorage.clear();
backend.changes = [];
backend.external = [];
backend.imported = [];
backend.externalError = null;
backend.entries = new Map([
["A", [{ type: "agent", text: "Answer A" }, subagent]],
[entriesKey("A", "child"), [{ type: "agent", text: "Child answer" }]],
@@ -129,6 +151,8 @@ beforeEach(() => {
homeOpen: false,
tasks: new Map([task("A"), task("B")].map((t) => [t.id, t])),
entries: new Map(backend.entries),
external: [],
externalError: null,
});
});
@@ -1256,3 +1280,36 @@ describe("meters in the task header", () => {
expect(screen.getByText("$0.42")).toBeInTheDocument();
});
});
describe("sessions from other apps", () => {
const openHistory = async () => {
act(() => useAgents.setState({ docked: "A" }));
render(<AgentsView />);
fireEvent.click(screen.getByRole("button", { name: "Agent sessions" }));
await waitFor(() => expect(screen.getByText("Sessions from other apps")).toBeInTheDocument());
};
it("lists external sessions in the history popup and imports one as a task", async () => {
backend.external = [
{ provider: "claude", sessionId: "abc", title: "Login fix", cwd: "/work/app", updatedMs: Date.now() },
{ provider: "codex", sessionId: "thread-1", title: "Add tests", cwd: null, updatedMs: 0 },
];
await openHistory();
expect(screen.getByText("Login fix")).toBeInTheDocument();
expect(screen.getByText("Add tests")).toBeInTheDocument();
await act(async () => {
fireEvent.click(screen.getAllByRole("button", { name: "Import" })[0]!);
});
expect(backend.imported).toEqual([["claude", "abc"]]);
const state = useAgents.getState();
expect(state.tasks.get("imported")?.title).toBe("Login fix");
expect(state.external.map((e) => e.sessionId)).toEqual(["thread-1"]);
});
it("shows listing errors instead of the section", async () => {
backend.externalError = "no home";
await openHistory();
expect(screen.getByText("no home")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Import" })).toBeNull();
});
});
+27
Переглянути файл
@@ -12,6 +12,7 @@ import type {
AgentLimit,
AgentProvider,
AgentTask,
ExternalSession,
Isolation,
} from "@/bindings";
import { useProject } from "@/platform/project";
@@ -77,6 +78,10 @@ interface AgentsState {
lastComposer: string;
/** First messages of past tasks, newest first (New Task page ↑). */
history: string[];
/** Sessions on this machine that no task holds yet (#312). */
external: ExternalSession[];
/** Why the external sessions could not be listed. */
externalError: string | null;
/** The composer asked to take focus (`seq` tells repeated requests apart). */
focus: { key: string; seq: number } | null;
/** Task shown inside the Agents tool window instead of an editor tab. */
@@ -138,6 +143,8 @@ export const useAgents = create<AgentsState>(() => ({
composers: new Map(),
lastComposer: HOME,
history: load<string[]>(HISTORY_KEY, []),
external: [],
externalError: null,
focus: null,
docked: null,
sessionLocation: load<unknown>(SESSION_LOCATION_KEY, null) === "toolWindow" ? "toolWindow" : "editor",
@@ -715,6 +722,26 @@ export async function startTask(
if ((await editorService().closeInput?.(HOME_KEY)) !== false) openTask(task.id);
}
/** Sessions on this machine that no task holds yet (a terminal, another editor: #312). */
export async function refreshExternalSessions() {
try {
const external = await call(commands.agentExternalSessions());
useAgents.setState({ external, externalError: null });
} catch (e) {
useAgents.setState({ externalError: e instanceof Error ? e.message : String(e) });
}
}
/** Imports an external session as a task and opens it: its first turn loads it (#312). */
export async function importExternalSession(provider: string, sessionId: string) {
const task = await call(commands.agentImportSession(provider, sessionId));
useAgents.setState((s) => ({
tasks: s.tasks.has(task.id) ? s.tasks : new Map(s.tasks).set(task.id, task),
external: s.external.filter((e) => !(e.provider === provider && e.sessionId === sessionId)),
}));
openTask(task.id);
}
function remember(text: string) {
if (!text) return;
const history = [text, ...useAgents.getState().history.filter((h) => h !== text)].slice(0, HISTORY_SIZE);
+32 -3
Переглянути файл
@@ -1,7 +1,18 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { RunConfig } from "@/platform/ipc";
import { usePlatform } from "@/platform/platformInfo";
import { debugUnsupportedReason, launchConfigFor } from "../launch";
import { debugUnsupportedReason, launchConfigFor, withEnvFiles } from "../launch";
const ipc = vi.hoisted(() => {
const ok = <T>(data: T) => Promise.resolve({ status: "ok" as const, data });
return { ok, runEnvFiles: vi.fn((_files: string[]) => ok({} as Record<string, string>)) };
});
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
const { ok: _ok, ...cmds } = ipc;
return { ...real, commands: { ...real.commands, ...cmds } };
});
const rc = (p: Partial<RunConfig>): RunConfig => ({
id: "x",
@@ -20,7 +31,10 @@ const rc = (p: Partial<RunConfig>): RunConfig => ({
const extra = (l: { extraJson: string | null } | null) => JSON.parse(l?.extraJson ?? "{}");
const originalPlatform = usePlatform.getState();
beforeEach(() => usePlatform.setState({ os: "linux" }));
beforeEach(() => {
usePlatform.setState({ os: "linux" });
vi.clearAllMocks();
});
afterEach(() => usePlatform.setState(originalPlatform));
describe("run config → launch config", () => {
@@ -494,3 +508,18 @@ it("raw and typed Go debug configurations inherit custom tags unless explicitly
}
}
});
describe("withEnvFiles", () => {
it("leaves configurations without .env files alone (no backend call)", async () => {
const config = rc({ env: { A: "1" } });
await expect(withEnvFiles(config, "/p")).resolves.toBe(config);
expect(ipc.runEnvFiles).not.toHaveBeenCalled();
});
it("loads .env files under the explicit variables, resolved against the project root", async () => {
ipc.runEnvFiles.mockResolvedValueOnce({ status: "ok", data: { FROM_FILE: "file", A: "file" } });
const out = await withEnvFiles(rc({ env: { A: "explicit" }, envFiles: [".env", "env/local.env"] }), "/p");
expect(ipc.runEnvFiles).toHaveBeenCalledWith(["/p/.env", "/p/env/local.env"]);
expect(out.env).toEqual({ FROM_FILE: "file", A: "explicit" });
});
});
+3 -3
Переглянути файл
@@ -30,7 +30,7 @@ import { fieldAt, methodAt } from "./breakpoints/symbols";
import { toggleBreakpointSmart } from "./breakpoints/toggle";
import { isJavaAttachTarget, isJavaDebuggable, javaAttachConfig, javaLaunchConfig } from "./java";
import { cancelHotSwapBuild, reloadChangedClasses } from "./hotswap";
import { debugUnsupportedReason, launchConfigFor } from "./launch";
import { debugUnsupportedReason, launchConfigFor, withEnvFiles } from "./launch";
import {
isPythonAttachTarget,
isRemoteConfig,
@@ -329,7 +329,7 @@ async function startConfig(arg: unknown) {
// php-debug starts the PHP chosen in Settings unless the command names one.
const php =
config.debugAdapter === "php-debug" && isTauri() ? await call(commands.sdkPhpEffective()).catch(() => null) : null;
const launch = launchConfigFor(prepared, root, php);
const launch = launchConfigFor(await withEnvFiles(prepared, root), root, php);
if (!launch) {
notifications().notify({
group: "run",
@@ -399,7 +399,7 @@ export function registerDebugActions(): () => void {
const config = await call(commands.pluginPrepareDebugRun(a.config));
const root = useProject.getState().project?.root;
if (!root) throw new Error("No project");
const launch = launchConfigFor(config, root);
const launch = launchConfigFor(await withEnvFiles(config, root), root);
if (!launch) throw new Error("This configuration has no debugger");
let id: number | null = null;
let stopped = false;
+2
Переглянути файл
@@ -16,6 +16,7 @@ import {
type JavaPreparation,
} from "@/platform/javaLaunch";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { withEnvFiles } from "./launch";
export const JAVA_ADAPTER = "java-debug";
export const KOTLIN_ADAPTER = "kotlin-debug-adapter";
@@ -111,6 +112,7 @@ export async function javaLaunchConfig(
preparation?: JavaPreparation,
): Promise<LaunchConfig> {
const cwd = rc.cwd ? join(root, rc.cwd) : root;
rc = await withEnvFiles(rc, root);
const parsed = parseJavaArgs(rc.args);
if (!parsed.mainClass) throw new Error(`No main class in '${rc.name}'`);
preparation?.signal.throwIfAborted();
+13 -1
Переглянути файл
@@ -1,7 +1,7 @@
import { parseArgs, formatArgs } from "@/platform/commandLine";
/** Run configuration → DAP launch configuration, per adapter. */
import { workflowSettings } from "@/platform/workflowSettings";
import type { LaunchConfig, RunConfig } from "@/platform/ipc";
import { call, commands, type LaunchConfig, type RunConfig } from "@/platform/ipc";
import { hostOs } from "@/platform/remote";
function isAbsolute(p: string) {
@@ -37,6 +37,18 @@ function base(rc: RunConfig, adapter: string, cwd: string): LaunchConfig {
};
}
/**
* `rc` with its `.env` files loaded underneath its explicit variables (mirrors Run):
* Debug used to drop them because `base` only copies `env`. Absolute paths go to the
* backend, which parses with the same loader runs use.
*/
export async function withEnvFiles(rc: RunConfig, root: string): Promise<RunConfig> {
const files = rc.envFiles?.filter((f) => f.trim()) ?? [];
if (!files.length) return rc;
const loaded = await call(commands.runEnvFiles(files.map((f) => join(root, f))));
return { ...rc, env: { ...loaded, ...rc.env } };
}
function cargoLaunch(rc: RunConfig, cwd: string, adapter: string): LaunchConfig {
const [cargoArgs, programArgs] = splitAtDashDash(rc.args);
const [sub, ...rest] = cargoArgs;
+1
Переглянути файл
@@ -2333,6 +2333,7 @@
"Services": "服务",
"Services actions": "服务操作",
"Session finished": "会话已结束",
"Sessions from other apps": "来自其他应用的智能体会话",
"Set Active Changelist": "设置活动更改列表",
"Set DEFAULT": "设为默认值",
"Set NULL": "设为 NULL",