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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 21c7de45d9 fix(vim): let af / if work on the right-hand side of a noremap
A noremap runs its keys against codemirror-vim's built-in keymap only, and
the function text objects were mapped after it as user mappings, so
`nnoremap X daf` deleted nothing. af / if are now part of the built-in
keymap through the existing vim-core patch (as <C-g>u is), and are no
longer re-mapped after every mapclear.
2026-12-02 12:58:26 +08:00
l0ng-ai a372385788 feat(vim): apply number and relativenumber from the rc file to the line numbers (#7381)
set relativenumber in ~/.ideavimrc was reported as an unsupported option and the gutter kept absolute numbers. As in IdeaVim, number (nu) and relativenumber (rnu) now set every editor's line numbers over Settings › Editor › General › Appearance › Show line numbers: both on is hybrid, relativenumber alone shows 0 on the caret line, both off hides them. An option the rc file leaves alone reads and follows Settings, nothing is written back, and turning Vim mode off or reloading an rc file without them returns to Settings. The options live in an editor-core store that lineNumbersExtension reads; the controller re-applies settings when it changes, as for Distraction Free Mode.

Fixes #7341
2026-12-02 12:53:37 +08:00
nako-ruruтаnako-ruru 7ff8d472f7 feat(chooser): mark interface targets in the implementation chooser (#7328)
Go to Implementation can list an interface declaration among the implementations (gopls answers both ways), and every row carried the same file icon. A target that is an interface or trait, or a method declared in one, now shows the editor's interface badge in place of the file icon, as GoLand does. LSP implementation answers carry no symbol kind, so the target file's outline supplies it; with targets in more than eight files the chooser opens with the kinds the index already knows instead of opening every file in the language server.

Covered by navigationInterfaceMark.test.ts.

Co-authored-by: nako-ruru <[email protected]>
2026-12-02 12:48:35 +08:00
GuoYuтаguoyucode 4de01a91c5 fix(mcp): list_directory_tree's maxDepth counts the levels below the directory (#7375)
list_directory_tree with maxDepth 1 listed nothing: the directory's own line took the first level, so 1 returned only that line with total 0, and the default 5 listed four levels. maxDepth now counts the levels below the directory (0: the directory alone, 1: its entries, …) and the parameter description says so. Paging, markers and the output format are unchanged.

Covered by max_depth_counts_the_levels_below_the_directory.

Co-authored-by: guoyucode <[email protected]>
2026-12-02 12:45:26 +08:00
LU XIANGRUIтаwildcatDownstairs 657d49e30a fix(debug): bind Xcode breakpoints for projects under /private/tmp (#7368)
Debugging an Xcode app whose project lives under /private/tmp never stopped at a breakpoint: the IDE sends breakpoints on the canonical /private/tmp/… path, while Xcode writes the files into the debug info as /tmp/…. The simulator attach now passes lldb-dap a sourceMap (/tmp, /var, /etc → /private/…). The map is Xcode-only: clang, swift build and cargo record /private/tmp/…, and LLDB uses only the first matching entry.

lldb-dap and CodeLLDB give no reason for a breakpoint they cannot bind; such breakpoints now carry one (code not loaded yet, or debug info under another path), shown translated on hover in the gutter and in the Breakpoints dialog, and dropped once the breakpoint binds.

Fixes #7367

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 12:40:05 +08:00
LU XIANGRUIтаwildcatDownstairs 2a7975a077 fix(xcode): select the root scheme and the backend's default simulator in Xcode projects (#7366)
An Xcode project with an npm package in a subfolder opened with that package's dev script selected, and the simulator chooser showed an iPad when nothing was booted.

- defaultSelection scored a root Xcode scheme the same as any run/dev script, so list order decided. A root scheme (kind xcode, no cwd) now scores like a Spring Boot application; schemes in subfolders and other project types keep their order, and a saved selection still wins.
- currentIosSimulator fell back to the first listed simulator, while the backend's pick_simulator takes a booted simulator, then the newest iPhone. The toolbar now applies the same rule, and pick_simulator ranks over simulator::parse_list so both sides agree on ties.

Fixes #7354

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 12:35:54 +08:00
tongkangwangтаchiyanking 71d88d0b55 fix(code-insight): allow dragging the Show Usages popup by its title bar (#7370)
The Show Usages popup could be resized but not moved: its header had no move handler, so it could not be dragged off the code it covers. Popup gains an opt-in `draggable` mode that moves it by descendants marked `data-popup-drag` (the same pattern Dialog uses with `data-dialog-drag`), skipping interactive controls; once moved the popup is positioned at its new place without flipping back to the anchor and stays 6 px inside the viewport. Show Usages marks its header as the drag handle.

Covered by e2e/usagesPopupLayout.spec.ts.

Co-authored-by: chiyanking <[email protected]>
2026-12-02 12:32:30 +08:00
angelf015таangelf015 c6faf280db fix(vim): support <C-g>u undo breaks in Insert mode (#7364)
An Insert-mode mapping such as `inoremap . .<C-g>u` typed the literal text ".<C-g>u": codemirror-vim has no <C-g>u command and writes unknown <...> keys of a mapping's right-hand side into the document. inoremap only searches the engine's built-in keymap, so the key is added there through a patch to @replit/codemirror-vim-core, bound to an action that isolates the next history event so the text after it starts a new undo group.

Covered by a Vim engine unit test and e2e/vimUndoBreak.spec.ts.

Co-authored-by: angelf015 <[email protected]>
2026-12-02 12:29:12 +08:00
王斌 fba7705acf feat(docker): run containers detached and open their log in Services (#7345)
Dockerfile and Docker Image runs start the container detached by default. The Run console keeps the build output; once the command line returns, a new exited hook on the run type reveals the container in the Services tool window with its Log tab (or a log editor tab for the CLI's default daemon). Closing the Run window or the IDE leaves the container running; an attached run still stops it with docker stop.

Co-authored-by: kitter960324 <[email protected]>
2026-12-02 11:48:52 +08:00
Alexanderтаstalexxx f87fb35be5 fix(libraries): don't list in-project Cargo path dependencies as External Libraries (#7316)
cargo metadata in a sub-crate's own workspace reported the project root (a path dependency such as vpn-core = { path = ".." }) as an external package, so the whole project became a read-only library root. Cargo library roots now drop path dependencies inside the open project, reusing is_project_source as Go modules do, so vendor copies stay libraries.

Co-authored-by: stalexxx <[email protected]>
2026-12-02 11:46:56 +08:00
Mansur Akhmadiтаmansur-akhmadi f4236a0ea1 feat(problems): Expand All / Collapse All in the Problems tool window toolbar (#7325)
The Problems toolbar gets Expand All and Collapse All; they touch only the files the current tab shows.

Closes #7324

Co-authored-by: mansur-akhmadi <[email protected]>
2026-12-02 11:20:51 +08:00
LU XIANGRUIтаwildcatDownstairs 1eece0ae51 fix(editor): scale gutter icons with the editor font zoom (#7352)
Gutter icons kept a fixed 14px while the editor font zoomed. They now follow the font size through --openidea-gutter-icon-size (14px at the default size, within 10-32px), applied to the icon area, the http/GraphQL/database run gutters and the feature icon wrappers.

Closes #7332

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 11:20:42 +08:00
LU XIANGRUIтаwildcatDownstairs 7361707b63 fix(astro): keep tag expressions with quoted strings as one attribute (#7331)
Quoted strings inside an Astro tag expression split the expression into several attributes. The tokenizer now skips string literals inside braces.

Closes #7330

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 11:20:30 +08:00
audichuang 8e56d3b73e fix(lsp): keep a newer Parameter Info reply when an older one arrives late (#7322)
fetchSignature applied every reply as it arrived, so a late reply for a call the caret had left replaced the newer signature. A reply is now skipped while a newer request's tooltip is still shown for the current document and caret.

Co-authored-by: audichuang <[email protected]>
2026-12-02 11:20:22 +08:00
audichuang e5453a8a97 fix(search): keep pinned Find results when the tab limit drops one (#7323)
Over the tab limit the Find tool window always dropped the first tab, even when pinned. With a pinned first tab it now drops the earliest unpinned search instead (the selected one only when it is the last unpinned).

Co-authored-by: audichuang <[email protected]>
2026-12-02 11:20:13 +08:00
audichuang 27689f09d3 fix(project): close the window on File → Close Project when another project is open (#7320)
File → Close Project always switched the window to Welcome. Like the native close button, it now closes the emptied window when another project window is open, and shows Welcome only for the last one.

Closes #7312

Co-authored-by: audichuang <[email protected]>
2026-12-02 11:20:06 +08:00
audichuang 9b468b0873 fix(vcs): keep the Git Log commit list a single Tab stop (#7321)
Every actionable graph edge and node had tabIndex 0, so Tab from the Commits list stopped on each graph segment of every row. They now use tabIndex -1 and stay clickable; the keyboard route is Collapse/Expand Linear Branches.

Closes #7311

Co-authored-by: audichuang <[email protected]>
2026-12-02 11:19:58 +08:00
audichuang cb887dad80 fix(search): report Replace All files left unsaved by a disk conflict (#7309)
Replace in Files saves clean open tabs through Documents::autosave, which keeps an external change and returns false when the file changed on disk first. That result was dropped, so the notification claimed every file was written. ReplaceHost::edit_file now also returns whether the edits were left unsaved, ReplaceSummary gains an unsaved count, and the summary reports it as a warning.

Closes #7273

Co-authored-by: audichuang <[email protected]>
2026-12-02 10:35:56 +08:00
audichuang 3cfbf80e26 fix(todo): drop the previous project's scan results after switching projects (#7318)
A scan of the old project still running after a project switch kept writing its files into the new project's TODO index. On a project change the index now bumps the scan counters (plus a new projectGen for file rescans), drops refreshes queued for the old project and resets the spinners.

Co-authored-by: audichuang <[email protected]>
2026-12-02 10:35:47 +08:00
audichuang 97add1f448 fix(coverage): show whole percentages like 29/100 as 29%, not 28% (#7317)
percent() divided before multiplying, so (29 / 100) * 100 was 28.999999999999996 and the whole-percent floor showed 28%. It now multiplies first, which is exact for integer counts.

Co-authored-by: audichuang <[email protected]>
2026-12-02 10:35:37 +08:00
Deng Liuтаdengliu 35a6bec1c2 feat(agents): implement unified Agent Plugins Hub across harnesses (#6877)
Adds a Plugins page under Settings > Agents for the plugin bundles each agent harness installs natively (Claude Code, GitHub Copilot, Codex, Gemini CLI).

- Rows are grouped by harness and scope with counts and paths. Toggles change only the harness's own enablement record, and row ids are stable and owner-qualified, so a toggle never reaches another project's row.
- Enabled plugins project their skills, MCP servers and memory files into Skills, MCP Connections and Memory; a workspace override decides what a globally enabled plugin projects in that workspace.
- Marketplaces can be browsed, previewed and installed from, with pinned git installs. Installs are written into each harness's native store without following symlinks, including at the store root.
- Plugins that run local MCP processes or lifecycle hooks need capability consent. Previews and installed folders resolve capabilities the same way, and consent is tied to the capability hash the user was shown: an install or enable whose capabilities differ is refused.

Closes #6872

Co-authored-by: dengliu <[email protected]>
2026-12-02 09:32:33 +08:00
Deng Liuтаdengliu f8ba067e1d feat(agents): add host-owned local and remote agent automations (#7084)
Adds agent automations owned by the host rather than a window: scheduled, one-shot and manual automations, in-session /loop and Send Later, and .automation.md import/export.

- Schedules run while OpenIDEA or openidea-server --daemon is running. An optional login service (LaunchAgent, systemd --user unit or Windows Startup entry), off by default, keeps them running when OpenIDEA is closed; a schedule that came due while nothing was running follows the missed-run policy.
- Every automated turn is capped at the interactive approval setting. A run fails and its schedule pauses unless the provider confirms the required ceiling, including for turns that waited in the queue.
- Scheduled turns re-check project and repository trust at dispatch; Restricted Mode pauses them.
- Worktree runs use new agent/* branches, keep the working directory confined to the worktree, and cleanup never deletes branches. Imported .automation.md files only create disabled copies.
- Automation state is shared across processes with one lock order, and in-memory claims roll back when persisting fails. Windows and peers can only act on tasks of projects they own.

Closes #6942

Co-authored-by: dengliu <[email protected]>
2026-12-02 09:19:54 +08:00
Deng Liuтаdengliu 85cbc6bacd feat(mdx): add side-by-side MDX preview with opt-in sandboxed JSX execution (#6881)
Adds Editor Only / Editor and Preview / Preview Only layouts for .mdx files.

- Safe Static Mode on open: frontmatter, GFM, math, Mermaid, MDX comments and documentation tags (Steps, CardGroup, Note, Tabs, Accordion) render through the sanitized Markdown pipeline with scroll sync and no script execution.
- Run JSX (or Trust Project in Restricted Mode) lazy-loads @mdx-js/mdx and sucrase and evaluates JSX, workspace/tsconfig/node_modules imports, .mdx transclusions, stylesheets, assets and custom layouts inside an opaque-origin sandboxed iframe with its own CSP, no network and no IPC.
- The host-guest bridge is a per-document MessagePort; image, media, module and link resolution stay inside the window's project roots, checked lexically and after canonicalization (new fs_canonicalize command, which rejects parent traversal).
- Execution requires a current, affirmative trust result for the file's owning project, including attached workspace members, whose trust changes now emit ProjectTrustChanged.
- External links open only from a real click on an anchor in the frame and always go through a confirmation dialog showing the parsed destination.
- Settings > Languages & Frameworks > Markdown adds MDX component execution (Ask before running / Run automatically in trusted projects / Disabled), a user-only setting that project settings cannot enable.

Closes #6876

Co-authored-by: dengliu <[email protected]>
2026-12-02 08:39:22 +08:00
199 змінених файлів з 36588 додано та 626 видалено

No files matched your search

Створено
+2
Переглянути файл
@@ -4179,6 +4179,7 @@ dependencies = [
"ide-tools",
"ide-vcs",
"ide-vfs",
"jiff",
"parking_lot 0.12.5",
"rustix",
"semver",
@@ -4190,6 +4191,7 @@ dependencies = [
"tempfile",
"tokio",
"toml 0.9.12+spec-1.1.0",
"toml_edit 0.25.17+spec-1.1.0",
"tracing",
"uuid",
]
+1
Переглянути файл
@@ -91,6 +91,7 @@ trash = "5"
blake3 = "1"
dunce = "1"
dirs = "6"
jiff = "0.2"
memmap2 = "0.9"
zip = { version = "9.2.3", default-features = false, features = ["deflate"] }
flate2 = "1"
+2
Переглянути файл
@@ -21,9 +21,11 @@ specta.workspace = true
sqlx.workspace = true
tokio.workspace = true
toml.workspace = true
toml_edit.workspace = true
tracing.workspace = true
parking_lot.workspace = true
dunce.workspace = true
jiff.workspace = true
uuid.workspace = true
tempfile.workspace = true
semver = "1"
File diff suppressed because it is too large. Load diff
+338 -1
Переглянути файл
@@ -131,7 +131,263 @@ fn is_bypass_mode(mode: &str) -> bool {
let lower = mode.to_lowercase();
let m: String =
lower.rsplit(['#', '/']).next().unwrap_or_default().chars().filter(char::is_ascii_lowercase).collect();
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous"
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous" || m == "autopilot"
}
fn upsert_choice(wanted: &mut Vec<crate::model::AgentConfigChoice>, id: &str, value: &str) {
if let Some(existing) = wanted.iter_mut().find(|c| c.id == id) {
existing.value = value.to_owned();
} else {
wanted.push(crate::model::AgentConfigChoice { id: id.to_owned(), value: value.to_owned() });
}
}
pub(crate) fn is_approval_option(opt: &AgentConfigOption) -> bool {
opt.id == CURSOR_APPROVAL || matches!(opt.category.as_deref(), Some("mode" | "permissions" | "approval"))
}
fn wanted_val(wanted: &[crate::model::AgentConfigChoice], id: &str) -> Option<String> {
wanted.iter().find(|c| c.id == id).map(|c| c.value.clone())
}
/// Applies an automation's permission policy (`mode`) to `config` and `wanted`, enforcing the
/// user's interactive approval setting (`interactive`) as a strict ceiling. When `mode` is `None`
/// (an in-session `/loop` or `Send Later` turn), clamps any bypass options down when `interactive`
/// is [`ide_core::settings::NewTaskApprovals::Ask`].
pub(crate) fn clamp_automation_permissions(
provider: &str,
mode: Option<crate::automation::AutomationPermissionMode>,
interactive: ide_core::settings::NewTaskApprovals,
config: &mut [AgentConfigOption],
wanted: &mut Vec<crate::model::AgentConfigChoice>,
) {
use crate::automation::AutomationPermissionMode;
use ide_core::settings::NewTaskApprovals;
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
return;
}
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
if !allow_bypass {
// Strip any explicit bypass choices from `wanted` first so they cannot re-elevate later.
wanted.retain(|c| match c.id.as_str() {
"mode" => !is_bypass_mode(&c.value),
"allow_all" | "permissions" => !matches!(c.value.to_ascii_lowercase().as_str(), "on" | "true"),
"approval" | CURSOR_APPROVAL => !c.value.eq_ignore_ascii_case("bypass"),
"approval_policy" => !c.value.eq_ignore_ascii_case("never"),
_ => true,
});
ask_for_approvals(config);
}
match provider {
"claude" | "claude-acp" => {
let cur_wanted = wanted_val(wanted, "mode");
let target = if allow_bypass {
match cur_wanted.as_deref() {
Some("default" | "plan" | "acceptEdits") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "bypassPermissions".to_owned(),
}
} else if interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::Assisted) {
match cur_wanted.as_deref() {
Some("default" | "plan") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "acceptEdits".to_owned(),
}
} else {
// Either Default mode or interactive policy is Ask (where interactive Claude starts in `default`).
match cur_wanted.as_deref() {
Some("plan") => "plan".to_owned(),
_ => "default".to_owned(),
}
};
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
&& opt.values.iter().any(|v| v.value == target)
{
let id = opt.id.clone();
opt.current = Some(target.clone());
upsert_choice(wanted, &id, &target);
} else if mode.is_some() || cur_wanted.is_some() {
upsert_choice(wanted, "mode", &target);
}
}
"codex" | "codex-acp" => {
let cur_wanted = wanted_val(wanted, "mode");
let target = if allow_bypass {
match cur_wanted.as_deref() {
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "full-access".to_owned(),
}
} else if mode == Some(AutomationPermissionMode::Default) {
"read-only".to_owned()
} else if mode.is_some() {
// Assisted, or AllowAll clamped by interactive Ask (`ask_for_approvals` maps full-access -> ask).
match cur_wanted.as_deref() {
Some("read-only") => "read-only".to_owned(),
_ => "ask".to_owned(),
}
} else {
// Scheduled /loop or Send Later under interactive Ask: never full-access.
match cur_wanted.as_deref() {
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "ask".to_owned(),
}
};
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
&& opt.values.iter().any(|v| v.value == target)
{
let id = opt.id.clone();
opt.current = Some(target.clone());
upsert_choice(wanted, &id, &target);
} else if mode.is_some() || cur_wanted.is_some() {
upsert_choice(wanted, "mode", &target);
}
}
"copilot" => {
if allow_bypass {
if !matches!(wanted_val(wanted, "allow_all").as_deref(), Some("off" | "false")) {
upsert_choice(wanted, "allow_all", "on");
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
opt.current = Some("on".into());
}
}
} else {
upsert_choice(wanted, "allow_all", "off");
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
opt.current = Some("off".into());
}
let non_auto = match wanted_val(wanted, "mode").as_deref() {
Some("plan") => "plan",
_ => "agent",
};
if mode.is_some() || config.iter().any(|o| o.id == "mode" && o.current.as_deref() == Some("autopilot"))
{
upsert_choice(wanted, "mode", non_auto);
}
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode")
&& (mode.is_some() || opt.current.as_deref() == Some("autopilot"))
&& opt.values.iter().any(|v| v.value == non_auto)
{
opt.current = Some(non_auto.into());
}
}
}
"cursor" => {
let target = if allow_bypass && wanted_val(wanted, CURSOR_APPROVAL).as_deref() != Some("ask") {
"bypass"
} else {
"ask"
};
upsert_choice(wanted, CURSOR_APPROVAL, target);
if let Some(opt) = config.iter_mut().find(|o| o.id == CURSOR_APPROVAL) {
opt.current = Some(target.into());
}
}
_ => {
if allow_bypass {
let user_chose_non_bypass = config.iter().any(|o| {
is_approval_option(o)
&& wanted.iter().any(|c| {
c.id == o.id && o.category.as_deref().and_then(bypass_value).is_some_and(|b| !b(&c.value))
})
});
if !user_chose_non_bypass {
apply_bypass_approvals(config);
}
}
}
}
// Ensure every approval-bearing option in `config` has its enforced value mirrored in `wanted`
// so `open_session` actively configures the live session even if the CLI's own config differs.
for opt in config.iter().filter(|o| is_approval_option(o)) {
if let Some(cur) = opt.current.as_deref() {
upsert_choice(wanted, &opt.id, cur);
}
}
}
/// Verifies that the session's reported `config` options do not exceed the required automation
/// permission ceiling (`min(mode, interactive)`). Returns `Err(reason)` if the provider remained
/// in a more permissive mode than allowed.
pub(crate) fn verify_automation_ceiling(
provider: &str,
mode: Option<crate::automation::AutomationPermissionMode>,
interactive: ide_core::settings::NewTaskApprovals,
config: &[AgentConfigOption],
) -> Result<(), String> {
use crate::automation::AutomationPermissionMode;
use ide_core::settings::NewTaskApprovals;
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
return Ok(());
}
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
if !allow_bypass && bypass_approvals(config) {
return Err("Agent did not confirm the required approval ceiling (session remained in bypass mode).".into());
}
let cur_of = |id: &str| config.iter().find(|o| o.id == id).and_then(|o| o.current.as_deref());
let mode_cur = config
.iter()
.find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
.and_then(|o| o.current.as_deref());
if !allow_bypass {
match provider {
"claude" | "claude-acp" => {
if let Some(cur) = mode_cur {
let allowed = if interactive == NewTaskApprovals::Bypass
&& mode == Some(AutomationPermissionMode::Assisted)
{
matches!(cur, "default" | "plan" | "acceptEdits")
} else {
matches!(cur, "default" | "plan")
};
if !allowed {
return Err(format!(
"Claude session remained in mode '{cur}', exceeding the required approval ceiling."
));
}
}
}
"codex" | "codex-acp" => {
if let Some(cur) = mode_cur {
let allowed = if mode == Some(AutomationPermissionMode::Default) {
cur == "read-only"
} else if mode.is_some() {
matches!(cur, "read-only" | "ask")
} else {
matches!(cur, "read-only" | "ask" | "auto")
};
if !allowed {
return Err(format!(
"Codex session remained in mode '{cur}', exceeding the required approval ceiling."
));
}
}
}
"copilot" => {
if let Some(cur) = cur_of("allow_all")
&& matches!(cur.to_ascii_lowercase().as_str(), "on" | "true")
{
return Err("Copilot session kept allow_all enabled above the approval ceiling.".into());
}
if let Some(cur) = mode_cur
&& cur.eq_ignore_ascii_case("autopilot")
{
return Err("Copilot session remained in autopilot mode above the approval ceiling.".into());
}
}
"cursor" if cur_of(CURSOR_APPROVAL).is_some_and(|cur| cur.eq_ignore_ascii_case("bypass")) => {
return Err("Cursor session remained in bypass mode above the approval ceiling.".into());
}
_ => {}
}
}
Ok(())
}
/// The settings in a `session/new` or `session/load` result: its select `configOptions`,
@@ -669,6 +925,87 @@ mod tests {
);
}
#[test]
fn automation_permissions_respect_interactive_approval_ceiling() {
use crate::automation::AutomationPermissionMode;
use crate::model::AgentConfigChoice;
use ide_core::settings::NewTaskApprovals;
let claude_opts = || {
options_of(&json!({"configOptions": [{
"id": "mode", "category": "mode", "type": "select", "currentValue": "bypassPermissions",
"defaultValue": "default",
"options": [
{"value": "default"}, {"value": "acceptEdits"}, {"value": "plan"}, {"value": "bypassPermissions"}
]
}]}))
};
// Claude Assisted under interactive Bypass -> acceptEdits; under interactive Ask -> default!
let mut c = claude_opts();
let mut wanted = Vec::new();
clamp_automation_permissions(
"claude",
Some(AutomationPermissionMode::Assisted),
NewTaskApprovals::Bypass,
&mut c,
&mut wanted,
);
assert_eq!(c[0].current.as_deref(), Some("acceptEdits"));
assert!(wanted.iter().any(|w| w.id == "mode" && w.value == "acceptEdits"));
let mut c_ask = claude_opts();
let mut wanted_ask = vec![AgentConfigChoice { id: "mode".into(), value: "bypassPermissions".into() }];
clamp_automation_permissions(
"claude",
Some(AutomationPermissionMode::AllowAll),
NewTaskApprovals::Ask,
&mut c_ask,
&mut wanted_ask,
);
assert_eq!(c_ask[0].current.as_deref(), Some("default"));
assert_eq!(wanted_ask, vec![AgentConfigChoice { id: "mode".into(), value: "default".into() }]);
// Copilot AllowAll under interactive Ask clamps allow_all -> off and autopilot -> agent.
let mut copilot = options_of(&json!({"configOptions": [
{"id": "mode", "category": "mode", "type": "select", "currentValue": "autopilot",
"options": [{"value": "agent"}, {"value": "plan"}, {"value": "autopilot"}]},
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "on",
"options": [{"value": "off"}, {"value": "on"}]}
]}));
let mut copilot_wanted = vec![AgentConfigChoice { id: "allow_all".into(), value: "on".into() }];
clamp_automation_permissions(
"copilot",
Some(AutomationPermissionMode::AllowAll),
NewTaskApprovals::Ask,
&mut copilot,
&mut copilot_wanted,
);
assert_eq!(ids(&copilot), [("mode", Some("agent")), ("allow_all", Some("off"))]);
assert!(!bypass_approvals(&copilot));
// Codex Default -> read-only, Assisted -> ask, AllowAll + Ask -> ask, AllowAll + Bypass -> full-access.
let codex_opts = || {
options_of(&json!({"configOptions": [{
"id": "mode", "category": "mode", "type": "select", "currentValue": "full-access",
"defaultValue": "ask",
"options": [{"value": "read-only"}, {"value": "ask"}, {"value": "auto"}, {"value": "full-access"}]
}]}))
};
for (perm, interactive, expected) in [
(AutomationPermissionMode::Default, NewTaskApprovals::Bypass, "read-only"),
(AutomationPermissionMode::Assisted, NewTaskApprovals::Bypass, "ask"),
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Ask, "ask"),
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Bypass, "full-access"),
] {
let mut opts = codex_opts();
let mut w = Vec::new();
clamp_automation_permissions("codex", Some(perm), interactive, &mut opts, &mut w);
assert_eq!(opts[0].current.as_deref(), Some(expected), "{perm:?} + {interactive:?}");
assert!(w.iter().any(|c| c.id == "mode" && c.value == expected));
}
}
#[test]
fn command_sources_in_updates_and_stored_tasks() {
let update = json!({"availableCommands": [
+548 -51
Переглянути файл
@@ -9,6 +9,7 @@
mod acp;
mod async_questions;
pub mod automation;
mod catalogs;
mod cli_update;
mod config;
@@ -21,6 +22,7 @@ pub mod mcp;
pub mod memory;
mod model;
mod native;
pub mod plugins;
mod provider;
pub mod registry;
pub mod security;
@@ -30,6 +32,7 @@ pub mod skills;
mod timeline;
mod worktree;
pub use automation::*;
pub use catalogs::AgentCatalogs;
pub use cli_update::{AgentCliOffer, AgentCliUpdateResult};
pub use external::ExternalSession;
@@ -39,6 +42,7 @@ pub use skill_installer::{
InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview,
SkillScanWarning, SkillScanWarningKind,
};
pub use worktree::canonical_repo_root;
use conversation::{Conversation, SavedSubagent, Session};
use ide_core::{IdeError, IdeResult, IpcPath, error::ErrorKind};
@@ -107,6 +111,17 @@ pub type SecurityHook = Arc<dyn Fn() -> ide_core::settings::AgentSecuritySetting
/// Returns the user's choice of the approvals new tasks start with.
pub type NewTaskApprovalsHook = Arc<dyn Fn() -> ide_core::settings::NewTaskApprovals + Send + Sync>;
/// Checks whether a canonical Git repository root is trusted before creating a worktree in it.
pub type RepoTrustHook = Arc<dyn Fn(&Path) -> bool + Send + Sync>;
/// Re-checks persisted workspace/repo trust right before a scheduled turn dispatches (including
/// when popped from `AgentTask::queue` after waiting behind an active turn).
pub type DispatchTrustHook = Arc<dyn Fn(&Path, Isolation) -> Result<(), String> + Send + Sync>;
/// Notified when a queued scheduled turn is blocked at dispatch time (e.g. Restricted Mode or
/// unconfirmed approval ceiling) so the host can pause the owning schedule and surface why.
pub type ScheduledBlockedHook = Arc<dyn Fn(&ScheduledTurnMeta, &str) + Send + Sync>;
/// Returns the roots of the project's workspace an agent may work in: the project and the
/// attached projects the user trusts.
pub type WorkspaceRootsHook = Arc<dyn Fn() -> Vec<PathBuf> + Send + Sync>;
@@ -243,6 +258,9 @@ pub type SkillsPolicyFn = dyn Fn() -> SkillsPolicy + Send + Sync;
/// Returns the memory policies for this project.
pub type MemoryPolicyFn = dyn Fn() -> memory::MemoryPolicy + Send + Sync;
/// Returns the agent plugin policies for this project.
pub type PluginsPolicyFn = dyn Fn() -> plugins::PluginsPolicy + Send + Sync;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct CopilotBinaryKey {
command: String,
@@ -258,6 +276,10 @@ struct Shared {
sinks: RwLock<HashMap<String, AgentSink>>,
security: RwLock<Option<SecurityHook>>,
new_task_approvals: RwLock<Option<NewTaskApprovalsHook>>,
repo_trust: RwLock<Option<RepoTrustHook>>,
dispatch_trust: RwLock<Option<DispatchTrustHook>>,
scheduled_blocked: RwLock<Option<ScheduledBlockedHook>>,
externally_live_tasks: Mutex<HashSet<String>>,
recovery_settings: RwLock<Option<RecoverySettingsHook>>,
network_probe_hook: RwLock<Option<Arc<NetworkProbeFn>>>,
network_probe_initial_ms: AtomicU64,
@@ -282,6 +304,7 @@ struct Shared {
mcp_executable_hook: RwLock<Option<Arc<McpExecutableFn>>>,
skills_policy_hook: RwLock<Option<Arc<SkillsPolicyFn>>>,
memory_policy_hook: RwLock<Option<Arc<MemoryPolicyFn>>>,
plugins_policy_hook: RwLock<Option<Arc<PluginsPolicyFn>>>,
/// Monotonic id for [`AgentEvent::Attention`] episodes.
attention_seq: AtomicU64,
/// Bumped on every [`AgentManager::shutdown`]: in-flight turns, session opens,
@@ -404,17 +427,21 @@ impl Shared {
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();
let configured = self.effective_mcp_servers();
servers.extend(mcp::acp_mcp_servers(&configured, provider, init, overrides));
let off = Self::mcp_off(&configured, provider, overrides);
McpForSession { servers, off }
}
fn mcp_servers_off_for_session(&self, provider: &str, overrides: &BTreeMap<String, bool>) -> Vec<String> {
let configured = self.mcp_servers_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
let configured = self.effective_mcp_servers();
Self::mcp_off(&configured, provider, overrides)
}
fn effective_mcp_servers(&self) -> Vec<McpServer> {
self.mcp_servers_hook.read().as_ref().map(|hook| hook()).unwrap_or_default()
}
fn mcp_off(configured: &[McpServer], provider: &str, overrides: &BTreeMap<String, bool>) -> Vec<String> {
let mut off = mcp::servers_off(configured, provider, overrides);
if overrides.get(mcp::BUILTIN_MCP_NAME) == Some(&false) {
@@ -817,6 +844,8 @@ struct TaskState {
/// Prompt handed to a spawned `run()` before `show_prompt` has appended it to `entries`,
/// so a shutdown landing in between still preserves it.
pending_prompt: Option<AgentPrompt>,
/// Scheduled-turn provenance active during the current turn (checked on `open_session` too).
active_scheduled_turn: Option<ScheduledTurnMeta>,
/// Background tasks the agent reported as running (`run_in_background` commands and
/// the like), as it sent them: unlike a turn they outlive it, so an idle release
/// waits for the last one. A (re)started process runs nothing yet.
@@ -992,6 +1021,16 @@ impl AgentManager {
/// Loads the project's saved tasks. Spawned work runs on `runtime`.
pub fn new(paths: AgentPaths, runtime: tokio::runtime::Handle) -> Self {
Self::new_with_live_tasks(paths, runtime, &HashSet::new())
}
/// Loads the project's saved tasks, leaving `externally_live` tasks (currently running in
/// another OpenIDEA worker process) untouched instead of marking them interrupted.
pub fn new_with_live_tasks(
paths: AgentPaths,
runtime: tokio::runtime::Handle,
externally_live: &HashSet<String>,
) -> Self {
let connector: Connector = Arc::new(|spec, cwd, client, on_stderr| match spec.driver {
provider::Driver::Acp => {
Peer::spawn_framed(&spec.command, &spec.args, cwd, &spec.env, client, on_stderr, Framing::Lines)
@@ -1000,10 +1039,20 @@ impl AgentManager {
provider::Driver::Claude => native::claude::connect(spec, cwd, client, on_stderr),
provider::Driver::Copilot => native::copilot::connect(spec, cwd, client, on_stderr),
});
Self::with_connector(paths, runtime, connector)
Self::with_connector_and_live(paths, runtime, connector, externally_live)
}
#[cfg(test)]
fn with_connector(paths: AgentPaths, runtime: tokio::runtime::Handle, connector: Connector) -> Self {
Self::with_connector_and_live(paths, runtime, connector, &HashSet::new())
}
fn with_connector_and_live(
paths: AgentPaths,
runtime: tokio::runtime::Handle,
connector: Connector,
externally_live: &HashSet<String>,
) -> Self {
let known = paths.catalogs.store(&paths.models_file);
let providers = RwLock::new(provider::load(paths.custom_agents_dir.as_deref(), paths.env_secrets.as_deref()));
let shared = Arc::new(Shared {
@@ -1013,6 +1062,10 @@ impl AgentManager {
sinks: RwLock::new(HashMap::new()),
security: RwLock::new(None),
new_task_approvals: RwLock::new(None),
repo_trust: RwLock::new(None),
dispatch_trust: RwLock::new(None),
scheduled_blocked: RwLock::new(None),
externally_live_tasks: Mutex::new(externally_live.clone()),
recovery_settings: RwLock::new(None),
network_probe_hook: RwLock::new(None),
network_probe_initial_ms: AtomicU64::new(NETWORK_PROBE_INITIAL_MS),
@@ -1033,6 +1086,7 @@ impl AgentManager {
mcp_executable_hook: RwLock::new(None),
skills_policy_hook: RwLock::new(None),
memory_policy_hook: RwLock::new(None),
plugins_policy_hook: RwLock::new(None),
attention_seq: AtomicU64::new(0),
shutdown_epoch: AtomicU64::new(0),
});
@@ -1046,8 +1100,14 @@ impl AgentManager {
// Only the task's own fields: its conversation is read when something needs it.
match std::fs::read(&path).map_err(|e| e.to_string()).and_then(|b| read_head(&b)) {
Ok((mut f, entries)) => {
// The agent process did not survive the restart: whatever was in flight is over.
if matches!(f.task.status, AgentStatus::Running | AgentStatus::NeedsInput | AgentStatus::Starting) {
let is_remote_live = externally_live.contains(&f.task.id);
// The agent process did not survive the restart unless another live worker owns it.
if !is_remote_live
&& matches!(
f.task.status,
AgentStatus::Running | AgentStatus::NeedsInput | AgentStatus::Starting
)
{
let was_waiting_for_input = f.task.status == AgentStatus::NeedsInput;
let approval_mode = config::approval_fingerprint(&f.task.config);
f.task.status = AgentStatus::Ready;
@@ -1061,8 +1121,10 @@ impl AgentManager {
auto_resume_once: false,
}));
}
f.task.retry = None;
f.task.background.clear();
if !is_remote_live {
f.task.retry = None;
f.task.background.clear();
}
// What an archived task's agent offered is only a cache, and a long list
// repeated in every archived task: its next session reports its own.
if f.task.status == AgentStatus::Archived {
@@ -1110,6 +1172,22 @@ impl AgentManager {
*self.shared.new_task_approvals.write() = Some(hook);
}
/// Sets the callback that verifies whether a canonical Git repository root is trusted
/// before creating a worktree in it.
pub fn set_repo_trust_hook(&self, hook: RepoTrustHook) {
*self.shared.repo_trust.write() = Some(hook);
}
/// Sets the callback that re-checks persisted trust right before dispatching a scheduled turn.
pub fn set_dispatch_trust_hook(&self, hook: DispatchTrustHook) {
*self.shared.dispatch_trust.write() = Some(hook);
}
/// Sets the callback invoked when a queued scheduled turn is blocked at dispatch time.
pub fn set_scheduled_blocked_hook(&self, hook: ScheduledBlockedHook) {
*self.shared.scheduled_blocked.write() = Some(hook);
}
/// Sets the callback that reads session recovery and transient network retry settings.
pub fn set_recovery_settings_hook(&self, hook: RecoverySettingsHook) {
*self.shared.recovery_settings.write() = Some(hook);
@@ -1283,6 +1361,11 @@ impl AgentManager {
*self.shared.memory_policy_hook.write() = Some(Arc::from(hook));
}
/// Provides the user and workspace agent plugin policies and the workspace's trust.
pub fn set_plugins_policy_hook(&self, hook: Box<PluginsPolicyFn>) {
*self.shared.plugins_policy_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,
/// for Claude Code the skills and custom commands on disk it has not listed (for
@@ -1349,17 +1432,26 @@ impl AgentManager {
let states = match holder {
Some(holder) => holder.skill_states().await,
None => {
let (policy, root) = {
let (policy, root, plug_policy) = {
let shared = &self.shared;
let policy = shared.skills_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
(policy, shared.paths.project_root.clone())
let plug_policy = shared.plugins_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
(policy, shared.paths.project_root.clone(), plug_policy)
};
let roots = if policy.workspace_roots.is_empty() { vec![root] } else { policy.workspace_roots };
let plugin_dirs = policy.plugin_dirs;
let home = self.shared.paths.home_dir.clone();
let cmd_provider = provider.clone();
blocking(move || {
let mut p_pol = plug_policy;
if p_pol.workspace_roots.is_empty() {
p_pol.workspace_roots = roots.clone();
}
let p_states =
plugins::resolve_plugins(plugins::discover_plugins(&roots, home.as_deref()), &p_pol, None);
let projected = plugins::projected_skill_roots(&p_states, Some(&cmd_provider));
Ok(skills::resolve(
skills::discover_skills_with_plugins(&roots, home.as_deref(), &plugin_dirs),
skills::discover_skills_with_agent_plugins(&roots, home.as_deref(), &plugin_dirs, &projected),
None,
&policy.workspace,
&policy.user,
@@ -1472,6 +1564,7 @@ impl AgentManager {
interrupted: None,
unread: false,
recovery_window_mins: None,
automation: None,
};
let file = TaskFile {
task: task.clone(),
@@ -1574,6 +1667,7 @@ impl AgentManager {
interrupted: None,
unread: false,
recovery_window_mins: None,
automation: None,
};
let file = TaskFile {
task: task.clone(),
@@ -1615,14 +1709,36 @@ impl AgentManager {
/// Creates the task (and its worktree) and sends `req.prompt` as its first message, unless
/// `req.idle`.
pub async fn create(&self, req: NewAgentTask) -> IdeResult<AgentTask> {
self.create_with_meta(req, None, None).await
}
/// Creates an automated task with an explicit display title and [`automation::AgentTaskAutomation`] provenance.
pub async fn create_automated(
&self,
req: NewAgentTask,
title: String,
automation: automation::AgentTaskAutomation,
) -> IdeResult<AgentTask> {
self.create_with_meta(req, Some(title), Some(automation)).await
}
async fn create_with_meta(
&self,
req: NewAgentTask,
explicit_title: Option<String>,
automation_meta: Option<automation::AgentTaskAutomation>,
) -> IdeResult<AgentTask> {
let spec = self
.shared
.spec(&req.provider)
.ok_or_else(|| IdeError::invalid(format!("unknown agent {}", req.provider)))?;
let prompt = clean(req.prompt).ok_or_else(|| IdeError::invalid("describe the task first"))?;
let title = title_of(&prompt);
let custom_title = explicit_title.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);
let title_renamed = custom_title.is_some();
let title = custom_title.unwrap_or_else(|| title_of(&prompt));
let root = req.project_root.clone().map(|p| p.0).unwrap_or_else(|| self.shared.paths.project_root.clone());
let project_root = Some(IpcPath(root.clone()));
let id = uuid::Uuid::new_v4().simple().to_string();
let (cwd, branch, base, base_commit, before) = match req.isolation {
Isolation::Worktree => {
if !git_enabled(&self.shared) {
@@ -1631,15 +1747,25 @@ impl AgentManager {
));
}
// The UI offers worktrees for git projects only; state it when it isn't one.
if Repo::discover(&root)?.is_none() {
let Some(repo) = Repo::discover(&root)? else {
return Err(IdeError::invalid(
"worktrees need a git repository: run the task in the local checkout",
));
};
let canon_repo = dunce::canonicalize(repo.root())?;
if let Some(check) = self.shared.repo_trust.read().clone()
&& !check(&canon_repo)
{
return Err(IdeError::invalid(format!(
"Git repository {} is not trusted: trust the repository root before creating a worktree",
canon_repo.display()
)));
}
let dir = self.shared.paths.worktrees_dir.clone();
let (t, b) = (title.clone(), req.base.clone());
let c = vcs(&self.shared, move || worktree::create(&root, &dir, &t, b.as_deref())).await?;
(c.path, Some(c.branch), Some(c.base), Some(c.base_commit), BTreeMap::new())
let (t, b, task_id) = (title.clone(), req.base.clone(), id.clone());
let c = vcs(&self.shared, move || worktree::create_for_task(&root, &dir, &task_id, &t, b.as_deref()))
.await?;
(c.cwd, Some(c.branch), Some(c.base), Some(c.base_commit), BTreeMap::new())
}
Isolation::Local => {
let r = root.clone();
@@ -1659,7 +1785,8 @@ impl AgentManager {
let catalog = self.shared.paths.catalogs.cached(&self.shared, &spec.id);
let mut levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &spec.id);
let mut config = self.shared.config_for_new_task(catalog.config, &spec.id);
for choice in &req.config {
let mut wanted = req.config;
for choice in &wanted {
if let Some(o) = config.iter_mut().find(|o| o.id == choice.id) {
o.current = Some(choice.value.clone());
}
@@ -1669,15 +1796,25 @@ impl AgentManager {
{
config.extend(levels.into_iter().map(|mut o| {
if let Some(choice) =
req.config.iter().find(|c| c.id == o.id && o.values.iter().any(|v| v.value == c.value))
wanted.iter().find(|c| c.id == o.id && o.values.iter().any(|v| v.value == c.value))
{
o.current = Some(choice.value.clone());
}
o
}));
}
if let Some(meta) = &automation_meta {
let interactive = self
.shared
.new_task_approvals
.read()
.as_ref()
.map(|h| h())
.unwrap_or(ide_core::settings::NewTaskApprovals::Bypass);
let mode = Some(meta.permissions.unwrap_or_default());
config::clamp_automation_permissions(&spec.id, mode, interactive, &mut config, &mut wanted);
}
let now = now_ms();
let id = uuid::Uuid::new_v4().simple().to_string();
// Copies of the files the user had changed already, for rolling back the task's changes to them.
let saved = if before.is_empty() {
None
@@ -1722,12 +1859,19 @@ impl AgentManager {
interrupted: None,
unread: false,
recovery_window_mins: None,
automation: automation_meta.clone().map(Box::new),
};
let initial_scheduled = automation_meta.as_ref().map(|m| ScheduledTurnMeta {
permissions: m.permissions,
extra_choices: wanted.clone(),
automation_id: Some(m.automation_id.clone()),
session_schedule_id: None,
});
let file = TaskFile {
task: task.clone(),
session_id: None,
entries: Vec::new(),
wanted: req.config,
wanted,
pending_model: None,
pending_switch: None,
before,
@@ -1737,7 +1881,7 @@ impl AgentManager {
turns: Vec::new(),
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: false,
title_renamed,
ephemeral: req.ephemeral,
pending_native_fork: None,
};
@@ -1747,6 +1891,7 @@ impl AgentManager {
s.busy = !req.idle;
if !req.idle {
s.pending_prompt = Some(prompt.clone());
s.active_scheduled_turn = initial_scheduled.clone();
}
}
let epoch = {
@@ -1758,7 +1903,7 @@ impl AgentManager {
handle.emit_task();
handle.persist();
if !req.idle {
self.shared.runtime.spawn(async move { handle.run(prompt, epoch).await });
self.shared.runtime.spawn(async move { handle.run_scheduled(prompt, initial_scheduled, epoch).await });
}
Ok(task)
}
@@ -1766,10 +1911,34 @@ impl AgentManager {
/// Sends a message. While the agent works it is queued, or with `now` the current turn
/// is cancelled and the message goes next.
pub async fn prompt(&self, id: &str, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
self.prompt_inner(id, prompt, now, None).await
}
/// Sends or queues a scheduled turn (`SameTask`, `Send Later`, or `/loop`), carrying its
/// provenance through `AgentTask::queue` so trust, worktree confinement, and the interactive
/// approval ceiling are re-verified right before dispatch.
pub async fn prompt_scheduled(&self, id: &str, prompt: AgentPrompt, meta: ScheduledTurnMeta) -> IdeResult<()> {
let task = self.task(id)?;
task.verify_worktree_cwd_confined()?;
if !task.state.lock().busy {
self.enforce_scheduled_turn_permissions(id, meta.permissions, &meta.extra_choices).await?;
}
self.prompt_inner(id, prompt, false, Some(meta)).await
}
async fn prompt_inner(
&self,
id: &str,
prompt: AgentPrompt,
now: bool,
scheduled: Option<ScheduledTurnMeta>,
) -> IdeResult<()> {
let task = self.task(id)?;
task.verify_worktree_cwd_confined()?;
let prompt = clean(prompt).ok_or_else(|| IdeError::invalid("empty message"))?;
// An agent that takes messages mid-turn gets it right away.
let prompt = match now {
// An agent that takes messages mid-turn gets it right away (never for scheduled turns,
// which must run their own dispatch trust and permission checks).
let prompt = match now && scheduled.is_none() {
true => match task.steer(prompt).await {
Ok(()) => return Ok(()),
Err(prompt) => prompt,
@@ -1785,7 +1954,7 @@ impl AgentManager {
return Err(IdeError::unavailable("Model settings are still loading"));
}
if s.busy {
let item = AgentQueued { id: uuid::Uuid::new_v4().simple().to_string(), prompt };
let item = AgentQueued { id: uuid::Uuid::new_v4().simple().to_string(), prompt, scheduled };
if now {
s.task.queue.insert(0, item);
} else {
@@ -1796,12 +1965,13 @@ impl AgentManager {
let epoch = self.shared.shutdown_epoch();
s.busy = true;
s.pending_prompt = Some(prompt.clone());
Some((prompt, epoch))
s.active_scheduled_turn = scheduled.clone();
Some((prompt, scheduled, epoch))
}
};
match start {
Some((prompt, epoch)) => {
self.shared.runtime.spawn(async move { task.run(prompt, epoch).await });
Some((prompt, sched, epoch)) => {
self.shared.runtime.spawn(async move { task.run_scheduled(prompt, sched, epoch).await });
}
None => {
task.persist();
@@ -1845,30 +2015,38 @@ impl AgentManager {
pub async fn send_queued_now(&self, id: &str, queued: &str) -> IdeResult<()> {
let task = self.task(id)?;
let (item, busy, epoch) = task.take_queued(queued, true)?;
let scheduled = item.scheduled;
if !busy {
self.shared.runtime.spawn(async move { task.run(item.prompt, epoch).await });
task.state.lock().active_scheduled_turn = scheduled.clone();
self.shared.runtime.spawn(async move { task.run_scheduled(item.prompt, scheduled, epoch).await });
return Ok(());
}
// Out of the queue while it is steered, so the turn ending meanwhile doesn't send it twice.
let prompt = match task.steer(item.prompt).await {
Ok(()) => return Ok(()),
Err(prompt) => prompt,
// Scheduled items never steer mid-turn so their dispatch trust & ceiling checks run first.
let prompt = if scheduled.is_none() {
match task.steer(item.prompt).await {
Ok(()) => return Ok(()),
Err(prompt) => prompt,
}
} else {
item.prompt
};
let start = {
let mut s = task.state.lock();
if s.busy {
s.task.queue.insert(0, AgentQueued { id: item.id, prompt });
s.task.queue.insert(0, AgentQueued { id: item.id, prompt, scheduled });
None
} else {
// The turn ended while steering was tried: nothing is left to interrupt.
let epoch = self.shared.shutdown_epoch();
s.busy = true;
Some((prompt, epoch))
s.active_scheduled_turn = scheduled.clone();
Some((prompt, scheduled, epoch))
}
};
match start {
Some((prompt, epoch)) => {
self.shared.runtime.spawn(async move { task.run(prompt, epoch).await });
Some((prompt, sched, epoch)) => {
self.shared.runtime.spawn(async move { task.run_scheduled(prompt, sched, epoch).await });
}
None => {
task.persist();
@@ -1992,6 +2170,7 @@ impl AgentManager {
s.task.config.extend(levels);
model_options = true;
}
let mut fresh_reported = false;
if let Some(live) = live.filter(|_| option != config::CURSOR_APPROVAL) {
let (method, mut params) = config::set_request(&target, &value);
params["sessionId"] = json!(live.session);
@@ -2010,6 +2189,7 @@ impl AgentManager {
if let Some(options) = reply.get("configOptions") {
config::merge_update(&mut task.state.lock().task.config, options);
model_options = true;
fresh_reported = true;
} else if target.category.as_deref() == Some("model") {
// Old model controls were removed above, so these came from an update
// that preceded the response.
@@ -2024,7 +2204,7 @@ impl AgentManager {
if !model_options && target.category.as_deref() == Some("model") {
s.task.config.retain(|o| !config::is_per_model_option(o));
}
if let Some(o) = s.task.config.iter_mut().find(|o| o.id == option) {
if !fresh_reported && let Some(o) = s.task.config.iter_mut().find(|o| o.id == option) {
o.current = Some(value);
}
s.task.model = model_of(&s.task.config).or(s.task.model.take());
@@ -2428,7 +2608,7 @@ impl AgentManager {
task.streamed.lock().clear();
self.shared.emit(AgentEvent::Truncated { task: id.to_owned(), length: 0 });
}
self.shared.runtime.spawn(async move { task.run_with_recovery(prompt, recovery, epoch).await });
self.shared.runtime.spawn(async move { task.run_with_recovery(prompt, None, recovery, epoch).await });
}
}
Ok(())
@@ -2808,6 +2988,152 @@ impl AgentManager {
Ok(())
}
/// Returns `true` if task `id` is tracked by this `AgentManager`.
pub fn has_task(&self, id: &str) -> bool {
self.tasks.read().contains_key(id)
}
/// Returns `true` if task `id` has an active in-memory turn, live session peer, or pending
/// permission channel in THIS `AgentManager` process (as opposed to a mirrored external task).
pub fn has_live_session_or_permission(&self, id: &str) -> bool {
let Some(task) = self.tasks.read().get(id).cloned() else {
return false;
};
if !task.permissions.lock().is_empty() {
return true;
}
if task.live.lock().as_ref().is_some_and(|l| !l.peer.is_closed()) {
return true;
}
task.state.lock().busy
}
/// Mirrors a live task snapshot received from an external worker process into this manager
/// without persisting over the worker's own task file.
pub fn sync_external_task(&self, snap: AgentTask) {
self.shared.externally_live_tasks.lock().insert(snap.id.clone());
if let Some(existing) = self.tasks.read().get(&snap.id).cloned() {
existing.state.lock().task = snap;
existing.emit_task();
return;
}
let path = self.shared.paths.store_dir.join(format!("{}.json", snap.id));
if let Ok(bytes) = std::fs::read(&path)
&& let Ok((mut f, entries)) = read_head(&bytes)
{
f.task = snap;
let restored = Task::restore_saved(f, entries, path, self.shared.clone());
let emit = restored.clone();
self.tasks.write().insert(restored.id.clone(), restored);
emit.emit_task();
}
}
/// Reloads task `id`'s persisted `TaskFile` from disk after an external worker run finishes
/// so subsequent interactive turns in this process see the latest `session_id` and history.
pub fn reload_task_from_disk(&self, id: &str) {
self.shared.externally_live_tasks.lock().remove(id);
let path = self.shared.paths.store_dir.join(format!("{id}.json"));
let Ok(bytes) = std::fs::read(&path) else { return };
let Ok((f, entries)) = read_head(&bytes) else { return };
if self.has_live_session_or_permission(id) {
return;
}
let restored = Task::restore_saved(f, entries, path, self.shared.clone());
let emit = restored.clone();
self.tasks.write().insert(id.to_owned(), restored);
emit.emit_task();
}
/// Returns a snapshot of task `id` if it exists.
pub fn task_snapshot(&self, id: &str) -> Option<AgentTask> {
self.tasks.read().get(id).map(|t| t.state.lock().snapshot())
}
/// Re-applies the automation approval policy (`mode`, or interactive ceiling when `None` for
/// `/loop` / `Send Later`) to an existing session before sending a scheduled turn, failing if
/// a live session rejects or fails to confirm the required approval ceiling.
pub async fn enforce_scheduled_turn_permissions(
&self,
id: &str,
mode: Option<automation::AutomationPermissionMode>,
extra_choices: &[AgentConfigChoice],
) -> IdeResult<()> {
let task = self.task(id)?;
task.enforce_scheduled_permissions_inner(mode, extra_choices).await
}
/// Updates the automation provenance recorded on task `id` (e.g. when `SameTask` starts a new scheduled run).
pub fn set_task_automation(&self, id: &str, meta: Option<automation::AgentTaskAutomation>) -> IdeResult<()> {
let task = self.task(id)?;
{
let mut s = task.state.lock();
s.task.automation = meta.map(Box::new);
s.task.updated_ms = now_ms();
}
task.persist();
task.emit_task();
Ok(())
}
/// Removes an idle automation worktree task's temporary Git worktree directory while
/// preserving the task and its conversation history.
///
/// Verifies the worktree's private `git_dir` ownership marker first, checks index + working
/// tree + commit cleanliness right before non-forced `git worktree remove` when `require_clean`
/// is `true`, and keeps the checkout untouched on any ownership or Git error.
pub async fn clean_task_worktree(&self, id: &str, require_clean: bool) -> IdeResult<bool> {
let task = self.task(id)?;
let (isolation, busy, cwd, root, base_commit) = {
let s = task.state.lock();
(
s.task.isolation,
s.busy
|| matches!(s.task.status, AgentStatus::Starting | AgentStatus::Running | AgentStatus::NeedsInput),
s.task.cwd.0.clone(),
s.task.project_root.clone().map(|p| p.0).unwrap_or_else(|| self.shared.paths.project_root.clone()),
s.task.base_commit.clone(),
)
};
if isolation != Isolation::Worktree || busy || !cwd.exists() {
return Ok(false);
}
let shared = self.tasks.read().values().any(|t| t.id != id && t.state.lock().task.cwd.0 == cwd);
if shared {
return Ok(false);
}
let live = task.kill();
if let Some(peer) = live {
let _ = tokio::time::timeout(EXIT_WAIT, peer.exited()).await;
}
let worktrees = self.shared.paths.worktrees_dir.clone();
let root_clone = root.clone();
let cwd_clone = cwd.clone();
let task_id = id.to_owned();
let removed = vcs(&self.shared, move || {
worktree::remove_owned_automation_worktree(
&root_clone,
&worktrees,
&cwd_clone,
&task_id,
base_commit.as_deref(),
require_clean,
)
})
.await?;
if !removed {
return Ok(false);
}
{
let mut s = task.state.lock();
s.task.isolation = Isolation::Local;
s.task.cwd = IpcPath(root);
}
task.persist();
task.emit_task();
Ok(true)
}
/// Forgets the task; with `remove_worktree` also deletes its worktree (the branch stays).
pub async fn delete(&self, id: &str, remove_worktree: bool) -> IdeResult<()> {
let task = self.task(id)?;
@@ -3312,7 +3638,7 @@ impl Task {
};
blocking(move || {
Ok(skills::resolve(
skills::discover_skills_with_plugins(&roots, home.as_deref(), &policy.plugin_dirs),
skills::discover_skills_with_agent_plugins(&roots, home.as_deref(), &policy.plugin_dirs, &[]),
Some(&overrides),
&policy.workspace,
&policy.user,
@@ -3455,6 +3781,7 @@ impl Task {
pending_native_fork: file.pending_native_fork,
busy: false,
pending_prompt: None,
active_scheduled_turn: None,
background_tasks: Vec::new(),
shell_context: Vec::new(),
}),
@@ -3981,15 +4308,127 @@ impl Task {
i
}
/// Verifies that a worktree task's `cwd` still resolves strictly inside its own worktree
/// checkout root under `worktrees_dir`, canonicalizing `s.task.cwd` in place.
fn verify_worktree_cwd_confined(&self) -> IdeResult<PathBuf> {
let (isolation, cwd) = {
let s = self.state.lock();
(s.task.isolation, s.task.cwd.0.clone())
};
if isolation != Isolation::Worktree {
return Ok(cwd);
}
let canon_cwd = worktree::verify_confined_worktree_cwd(&self.shared.paths.worktrees_dir, &cwd)?;
if canon_cwd != cwd {
self.state.lock().task.cwd = IpcPath(canon_cwd.clone());
}
Ok(canon_cwd)
}
async fn enforce_scheduled_permissions_inner(
self: &Arc<Self>,
mode: Option<automation::AutomationPermissionMode>,
extra_choices: &[AgentConfigChoice],
) -> IdeResult<()> {
let interactive = self
.shared
.new_task_approvals
.read()
.as_ref()
.map(|h| h())
.unwrap_or(ide_core::settings::NewTaskApprovals::Bypass);
let (provider, to_apply) = {
let mut s = self.state.lock();
for choice in extra_choices {
if let Some(existing) = s.wanted.iter_mut().find(|c| c.id == choice.id) {
existing.value = choice.value.clone();
} else {
s.wanted.push(choice.clone());
}
}
let provider = s.task.provider.clone();
let mut target_config = s.task.config.clone();
let mut target_wanted = s.wanted.clone();
config::clamp_automation_permissions(&provider, mode, interactive, &mut target_config, &mut target_wanted);
let mut diffs = Vec::new();
for next_opt in &target_config {
let prev_cur = s.task.config.iter().find(|o| o.id == next_opt.id).and_then(|o| o.current.as_deref());
if let Some(next_val) = next_opt.current.as_deref()
&& prev_cur != Some(next_val)
&& next_opt.values.iter().any(|v| v.value == next_val)
{
diffs.push((next_opt.id.clone(), next_val.to_owned()));
}
}
s.wanted = target_wanted;
(provider, diffs)
};
self.persist();
let live = self.live.lock().clone().filter(|l| !l.peer.is_closed());
if let Some(live) = live {
for (opt_id, val) in to_apply {
let Some(target_opt) = self.state.lock().task.config.iter().find(|o| o.id == opt_id).cloned() else {
continue;
};
if opt_id == config::CURSOR_APPROVAL {
if let Some(o) = self.state.lock().task.config.iter_mut().find(|o| o.id == opt_id) {
o.current = Some(val);
}
continue;
}
let (method, mut params) = config::set_request(&target_opt, &val);
params["sessionId"] = json!(live.session);
let reply: Value = live.peer.request(method, params, None).await.map_err(|e| {
IdeError::internal(format!(
"Agent rejected required approval setting ({opt_id}={val}): {}",
self.describe(e)
))
})?;
if let Some(options) = reply.get("configOptions") {
config::merge_update(&mut self.state.lock().task.config, options);
} else if let Some(o) = self.state.lock().task.config.iter_mut().find(|o| o.id == opt_id) {
o.current = Some(val);
}
}
let current_cfg = self.state.lock().task.config.clone();
config::verify_automation_ceiling(&provider, mode, interactive, &current_cfg).map_err(IdeError::invalid)?;
self.approve_pending();
self.persist();
self.emit_task();
}
Ok(())
}
async fn check_scheduled_dispatch_guard(self: &Arc<Self>, meta: &ScheduledTurnMeta) -> Result<(), String> {
self.verify_worktree_cwd_confined().map_err(|e| e.to_string())?;
let (project_root, isolation) = {
let s = self.state.lock();
(
s.task
.project_root
.as_ref()
.map(|p| p.0.clone())
.unwrap_or_else(|| self.shared.paths.project_root.clone()),
s.task.isolation,
)
};
if let Some(check) = self.shared.dispatch_trust.read().clone() {
check(&project_root, isolation)?;
}
self.enforce_scheduled_permissions_inner(meta.permissions, &meta.extra_choices).await.map_err(|e| e.to_string())
}
/// Runs `prompt`, then the queued messages, until the queue is empty, a turn fails, or
/// the user stops one. The caller set `busy`.
async fn run(self: Arc<Self>, prompt: AgentPrompt, epoch: u64) {
self.run_with_recovery(prompt, None, epoch).await;
async fn run_scheduled(self: Arc<Self>, prompt: AgentPrompt, scheduled: Option<ScheduledTurnMeta>, epoch: u64) {
self.run_with_recovery(prompt, scheduled, None, epoch).await;
}
async fn run_with_recovery(
self: Arc<Self>,
mut prompt: AgentPrompt,
mut scheduled: Option<ScheduledTurnMeta>,
mut recovery: Option<InterruptionReason>,
epoch: u64,
) {
@@ -4000,8 +4439,30 @@ impl Task {
if self.shared.shut_down_since(epoch) {
return;
}
self.state.lock().active_scheduled_turn = scheduled.clone();
if recovery.is_none() {
if let Err(err) = self.verify_worktree_cwd_confined() {
self.state.lock().active_scheduled_turn = None;
return self.fail(Failure::from(err.to_string()), epoch);
}
if let Some(ref meta) = scheduled
&& let Err(reason) = self.check_scheduled_dispatch_guard(meta).await
{
if let Some(on_blocked) = self.shared.scheduled_blocked.read().clone() {
on_blocked(meta, &reason);
}
{
let mut s = self.state.lock();
s.active_scheduled_turn = None;
s.pending_prompt = None;
s.task.queue.retain(|q| q.scheduled.is_none());
}
return self.fail(Failure::from(reason), epoch);
}
}
// The message shows before the checkout is recorded, which can take a while in a large repository.
if !self.show_prompt(&prompt, recovery.take(), epoch) {
self.state.lock().active_scheduled_turn = None;
return;
}
self.checkout_before_turn(epoch).await;
@@ -4080,6 +4541,7 @@ impl Task {
let next = (go_on && !s.task.queue.is_empty()).then(|| s.task.queue.remove(0));
if next.is_none() {
s.busy = false;
s.active_scheduled_turn = None;
}
(changed, next, archived)
};
@@ -4104,6 +4566,7 @@ impl Task {
self.emit_task();
network_resumes_this_turn = 0;
prompt = queued.prompt;
scheduled = queued.scheduled;
recovery = None;
}
(None, Ok(stop)) => {
@@ -4790,11 +5253,15 @@ impl Task {
self: &Arc<Self>,
provider_id: &str,
spec: provider::ProviderSpec,
cwd: &Path,
_cwd: &Path,
saved: Option<String>,
pending_model: Option<&PendingModel>,
epoch: u64,
) -> Result<Live, SessionOpenError> {
let verified_cwd = self
.verify_worktree_cwd_confined()
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?;
let cwd = verified_cwd.as_path();
let launch_cwd = cwd.to_path_buf();
let mut spec = tokio::task::spawn_blocking(move || {
spec.resolve_for_launch_with_copilot_env(&launch_cwd, provider::prefer_stored_copilot_auth())
@@ -5062,16 +5529,39 @@ impl Task {
if known {
self.shared.remember(provider_id, Some(&reported), None, model_of(&reported).as_deref());
}
let (mut options, mut wanted) = {
let (mut options, mut wanted, ceiling_active, effective_perm_mode) = {
let s = self.state.lock();
let options = if known { reported } else { s.task.config.clone() };
let mut wanted = s.wanted.clone();
if let Some(pending) = pending_model {
pending.apply(&mut wanted, &s.task.config);
}
(options, wanted)
let auto_perm = s.task.automation.as_ref().map(|a| a.permissions.unwrap_or_default());
let sched_perm = s.active_scheduled_turn.as_ref().map(|m| m.permissions);
let ceiling_active = auto_perm.is_some() || sched_perm.is_some();
let effective_perm_mode = sched_perm.unwrap_or(auto_perm);
(options, wanted, ceiling_active, effective_perm_mode)
};
config::add_client_options(provider_id, &mut options);
let interactive = self
.shared
.new_task_approvals
.read()
.as_ref()
.map(|h| h())
.unwrap_or(ide_core::settings::NewTaskApprovals::Bypass);
if ceiling_active {
// Compute clamped choices on a scratch copy of `options` so `options[i].current` still
// reflects what the CLI reported and the `wanted` loop below sends any needed downgrade!
let mut scratch = options.clone();
config::clamp_automation_permissions(
provider_id,
effective_perm_mode,
interactive,
&mut scratch,
&mut wanted,
);
}
// Changing model can replace the effort / context-tier choices; validate those only afterwards.
wanted.sort_by_key(|c| {
if let Some(pending) = pending_model {
@@ -5135,6 +5625,7 @@ impl Task {
if already || !o.values.iter().any(|v| v.value == choice.value) {
continue;
}
let required_ceiling_opt = ceiling_active && config::is_approval_option(&o);
self.config_sent.lock().insert((choice.id.clone(), choice.value.clone()));
let (method, mut params) = config::set_request(&o, &choice.value);
params["sessionId"] = json!(session_id);
@@ -5165,22 +5656,28 @@ impl Task {
});
}
model_options = true;
} else if o.category.as_deref() == Some("model") {
if o.current.as_deref() != Some(choice.value.as_str()) {
options.retain(|o| !config::is_per_model_option(o));
} else {
if o.category.as_deref() == Some("model") {
if o.current.as_deref() != Some(choice.value.as_str()) {
options.retain(|o| !config::is_per_model_option(o));
}
model_options = false;
}
if let Some(o) = options.iter_mut().find(|o| o.id == choice.id) {
o.current = Some(choice.value.clone());
}
model_options = false;
}
if let Some(o) = options.iter_mut().find(|o| o.id == choice.id) {
o.current = Some(choice.value.clone());
}
}
Err(e) if pending || explicit => {
Err(e) if pending || explicit || required_ceiling_opt => {
return Err(SessionOpenError { message: self.describe(e), allow_acp_fallback: false });
}
Err(e) => tracing::warn!("agent task {}: setting {} to {} failed: {e}", self.id, o.id, choice.value),
}
}
if ceiling_active {
config::verify_automation_ceiling(provider_id, effective_perm_mode, interactive, &options)
.map_err(|message| SessionOpenError { message, allow_acp_fallback: false })?;
}
if self.shared.shut_down_since(epoch) {
return Err(SessionOpenError { message: "The agent manager shut down.".into(), allow_acp_fallback: false });
}
+28 -7
Переглянути файл
@@ -68,9 +68,25 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer
headers: cfg.headers.iter().map(|(k, v)| McpKeyValue { name: k.clone(), value: v.clone() }).collect(),
agents: cfg.agents.clone(),
unapproved: false,
plugin_id: None,
plugin_name: None,
}
}
/// Merges `projected` MCP servers from enabled agent plugins behind `configured` User and
/// Workspace servers so standalone settings entries always take precedence on name clashes.
pub fn merge_projected_servers(mut configured: Vec<McpServer>, projected: Vec<McpServer>) -> Vec<McpServer> {
let existing: HashSet<String> = configured.iter().map(|s| s.name.clone()).collect();
// Same-named servers from different bundles are distinct rows (ids are `plugin:<bundle>:<server>`).
let mut seen_projected: HashSet<String> = HashSet::new();
for srv in projected {
if !existing.contains(&srv.name) && seen_projected.insert(srv.id.clone()) {
configured.push(srv);
}
}
configured
}
fn normalize_provider(id: &str) -> &str {
id.strip_suffix("-acp").unwrap_or(id)
}
@@ -399,13 +415,8 @@ pub fn apply_save_json(
Ok(saved_names)
}
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
".github/plugin/plugin.json",
".plugin/plugin.json",
".claude-plugin/plugin.json",
".cursor-plugin/plugin.json",
"plugin.json",
];
const COPILOT_PLUGIN_MANIFESTS: &[&str] =
&[".github/plugin/plugin.json", ".plugin/plugin.json", ".claude-plugin/plugin.json", "plugin.json"];
#[derive(Clone, PartialEq, Eq)]
enum SourceFormat {
@@ -1051,6 +1062,14 @@ fn extract_servers_from_root(root: &Value, fallback_name: Option<&str>) -> BTree
out
}
pub(crate) fn read_external_mcp_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
read_external_file(path)
}
pub(crate) fn parse_mcp_value(root: &Value) -> Result<BTreeMap<String, AgentMcpServer>, String> {
Ok(extract_servers_from_root(root, None))
}
fn read_external_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
let Ok(text) = std::fs::read_to_string(path) else {
return BTreeMap::new();
@@ -1251,6 +1270,8 @@ mod tests {
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
plugin_id: None,
plugin_name: None,
}
}
+24
Переглянути файл
@@ -453,6 +453,26 @@ pub fn discover_memories(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Age
out
}
/// Discovers all standalone memory entries across `workspaces` and `home`, then appends
/// projected rule/context entries from enabled agent plugins (deduplicated by canonical path).
pub fn discover_memories_with_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
projected: Vec<AgentMemoryEntry>,
) -> Vec<AgentMemoryEntry> {
let mut out = discover_memories(workspaces, home);
let mut seen: HashSet<PathBuf> =
out.iter().map(|e| dunce::canonicalize(&e.path.0).unwrap_or_else(|_| e.path.0.clone())).collect();
for mut entry in projected {
let canon = dunce::canonicalize(&entry.path.0).unwrap_or_else(|_| entry.path.0.clone());
entry.path = canon.clone().into();
if seen.insert(canon) {
out.push(entry);
}
}
out
}
/// Resolves the full [`AgentMemoryCatalog`] (entries + per-provider auto-memory statuses)
/// against `policy` and optional per-session `session_overrides`.
pub fn resolve_catalog(
@@ -1412,6 +1432,8 @@ fn parse_cursor_mdc(path: &Path, rel: &str) -> Option<AgentMemoryEntry> {
writable: false,
valid: true,
warnings,
plugin_id: None,
plugin_name: None,
})
}
@@ -1482,6 +1504,8 @@ fn parse_entry(
writable,
valid: true,
warnings,
plugin_id: None,
plugin_name: None,
})
}
+414 -3
Переглянути файл
@@ -199,6 +199,10 @@ pub struct AgentTask {
/// Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recovery_window_mins: Option<u32>,
/// Provenance metadata when this task was created or continued by an [`crate::automation::AgentAutomation`].
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub automation: Option<Box<crate::automation::AgentTaskAutomation>>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
@@ -454,11 +458,29 @@ pub struct AgentPrompt {
pub images: Vec<AgentImage>,
}
/// Provenance carried with a scheduled turn (`SameTask`, `Send Later`, or `/loop`), including
/// while queued behind a busy turn, so trust and approval ceilings are re-checked at dispatch.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduledTurnMeta {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub permissions: Option<crate::automation::AutomationPermissionMode>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub extra_choices: Vec<AgentConfigChoice>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub automation_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_schedule_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentQueued {
pub id: String,
pub prompt: AgentPrompt,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(skip)]
pub scheduled: Option<ScheduledTurnMeta>,
}
/// A setting chosen for a new task, by [`AgentConfigOption::id`].
@@ -920,7 +942,7 @@ pub struct AgentModelCatalog {
}
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
#[derive(Clone, Debug, Serialize, Type)]
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum AgentEvent {
/// A task was created or its metadata changed.
@@ -1018,6 +1040,14 @@ pub struct McpServer {
/// True when this Workspace server was added outside OpenIDEA and has not been approved yet.
#[serde(default)]
pub unapproved: bool,
/// Parent agent plugin ID when this server is live-projected from an enabled agent plugin bundle.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_id: Option<String>,
/// Display name of the parent agent plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
}
/// Payload for creating or updating a user or workspace MCP server.
@@ -1051,8 +1081,8 @@ fn default_true() -> bool {
}
pub use ide_core::settings::{
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentProviderMemoryPolicy, AgentSkillMode,
AgentSkillPolicy, AutoMemoryMode,
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings,
AgentProviderMemoryPolicy, AgentSkillMode, AgentSkillPolicy, AutoMemoryMode,
};
/// Kind of discovered agent memory entry.
@@ -1165,6 +1195,14 @@ pub struct AgentMemoryEntry {
pub valid: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
/// Parent agent plugin ID when this rule/instruction is live-projected from an enabled agent plugin bundle.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_id: Option<String>,
/// Display name of the parent agent plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
}
/// A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin.
@@ -1337,6 +1375,14 @@ pub struct AgentSkill {
pub valid: bool,
/// What validation found (`name` mismatch, missing or over-long description…).
pub warnings: Vec<String>,
/// Parent agent plugin ID when this skill comes from an agent plugin bundle.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_id: Option<String>,
/// Display name of the parent agent plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
}
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
@@ -1398,6 +1444,371 @@ pub struct McpDiscoveredServer {
pub header_keys: Vec<String>,
}
/// Which workspace, user, or CLI store an agent plugin bundle was discovered in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginSource {
/// `~/.copilot/installed-plugins/{<marketplace>,_direct}/*`.
#[default]
CopilotUser,
/// `~/.claude/plugins/installed_plugins.json` & `~/.claude/plugins/cache/*`.
ClaudeUser,
/// `~/.codex/plugins/cache/*`.
CodexUser,
/// `~/.gemini/extensions/*`.
GeminiUser,
}
/// Manifest format(s) recognized inside an agent plugin directory.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginFormat {
/// Vendor-neutral Agent Plugins 1.0 / 1.1 (`plugin.json` with `$schema`).
#[default]
AgentPluginsV1,
/// `.openidea/plugin.json`.
OpenIdea,
/// `.claude-plugin/plugin.json`.
Claude,
/// `.plugin/plugin.json`, `.github/plugin/plugin.json`, or legacy root `plugin.json`.
Copilot,
/// `.codex-plugin/plugin.json`.
Codex,
/// `gemini-extension.json`.
GeminiExtension,
}
/// Which policy layer decided an [`AgentPluginState::enabled`] status.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginOrigin {
/// Native harness configuration owns the enabled state.
#[default]
None,
/// Locked `Off` because the workspace is untrusted.
Trust,
/// Locked `Off` until executable capabilities (stdio MCP / lifecycle hooks) are approved.
Consent,
}
/// Data type of a plugin `userConfig` / `variables` / `settings` option.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginConfigFieldKind {
#[default]
String,
Number,
Boolean,
Secret,
}
/// One configurable option declared by an agent plugin (`userConfig`, `variables`, or Gemini `settings`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginConfigField {
pub key: String,
pub title: String,
#[serde(default)]
pub description: String,
pub kind: AgentPluginConfigFieldKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub default_value: Option<String>,
#[serde(default)]
pub required: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub env_var: Option<String>,
/// Current non-sensitive value (always empty when `kind == Secret`).
#[serde(default)]
pub value: String,
/// True when a secret is stored in OS Keychain for this field.
#[serde(default)]
pub has_secret: bool,
}
/// Summary of components and executable capabilities bundled inside an agent plugin.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginCapabilities {
pub skill_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub skill_names: Vec<String>,
pub mcp_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub mcp_names: Vec<String>,
pub rule_count: u32,
pub subagent_count: u32,
pub command_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub hook_files: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub stdio_commands: Vec<String>,
#[serde(default)]
pub has_lsp: bool,
#[serde(default)]
pub has_canvas_or_app: bool,
/// Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub native_harnesses: Vec<String>,
/// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub capability_hash: Option<String>,
#[serde(default)]
pub requires_consent: bool,
}
/// One discovered agent plugin bundle on disk (or built-in).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPlugin {
pub id: String,
pub name: String,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub version: Option<String>,
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub author: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub homepage: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub repository: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub license: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace: Option<String>,
pub source: AgentPluginSource,
/// Scope this bundle is installed in. Native plugin folders and enablement config are
/// resolved relative to this scope.
pub scope: McpScope,
/// Workspace whose native configuration owns this row's enablement (workspace scope only).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub workspace_root: Option<IpcPath>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub also_in: Vec<AgentPluginSource>,
pub formats: Vec<AgentPluginFormat>,
pub root_path: IpcPath,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub manifest_path: Option<IpcPath>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub readme_path: Option<IpcPath>,
pub default_enabled: bool,
pub approx_tokens: u32,
pub capabilities: AgentPluginCapabilities,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub config_fields: Vec<AgentPluginConfigField>,
pub valid: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
}
/// Resolved agent plugin state paired with its policy origin and consent status.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginState {
pub plugin: AgentPlugin,
pub enabled: bool,
pub origin: AgentPluginOrigin,
/// True when executable stdio MCP / hook capabilities require user approval before enabling.
pub consent_required: bool,
}
/// Summary of a configured or repository-discovered plugin marketplace.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMarketplaceInfo {
pub id: String,
pub name: String,
pub source: String,
pub scope: McpScope,
/// True when discovered from a harness-native marketplace/configuration file.
pub discovered: bool,
}
/// Full catalog returned to Settings › Agents › Plugins.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginCatalog {
pub plugins: Vec<AgentPluginState>,
pub marketplaces: Vec<AgentMarketplaceInfo>,
pub projected_skills: u32,
pub projected_mcp_servers: u32,
pub projected_rules: u32,
}
/// One installable plugin entry listed inside a marketplace or repository.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMarketplaceCandidate {
pub name: String,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub version: Option<String>,
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub author: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace: Option<String>,
/// Source spec to pass to preview (`"owner/repo[/subpath][@ref]"` or local directory path).
pub source_spec: String,
pub subpath: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub keywords: Vec<String>,
pub already_installed_user: bool,
pub already_installed_workspace: bool,
}
/// Result of browsing a marketplace (`owner/repo`, local marketplace path, or direct plugin repo).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMarketplaceBrowseResult {
pub source: String,
pub marketplace_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub owner: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub repo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub git_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub tree_sha: Option<String>,
pub candidates: Vec<AgentMarketplaceCandidate>,
}
/// Whether a previewed plugin can be installed for one harness, and where it is already installed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginInstallTarget {
pub harness: String,
pub supported: bool,
/// Why the harness cannot install this plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub reason: Option<String>,
/// Whether this harness can enable the plugin for just one workspace.
pub workspace_supported: bool,
/// This harness already records the plugin for the user / for the current workspace.
pub installed_user: bool,
pub installed_workspace: bool,
/// The harness store already holds this plugin version's folder, so installing replaces it.
pub overwrite_required: bool,
}
/// Security and capability preview of an agent plugin bundle before installation.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginPreview {
/// `"github"` or `"local"`.
pub source_kind: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub owner: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub repo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub git_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub tree_sha: Option<String>,
/// Pinned commit SHA from preview when `source_kind == "github"`.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub commit_sha: Option<String>,
#[serde(default)]
pub subpath: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub local_path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace_source: Option<String>,
pub name: String,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub version: Option<String>,
pub description: String,
pub formats: Vec<AgentPluginFormat>,
pub capabilities: AgentPluginCapabilities,
pub files: Vec<crate::skill_installer::RemoteSkillFile>,
pub scan_warnings: Vec<crate::skill_installer::SkillScanWarning>,
/// Per-harness install eligibility and existing installs for this plugin and marketplace.
pub targets: Vec<AgentPluginInstallTarget>,
}
/// Request payload to install a previewed agent plugin into a selected harness's native plugin directory.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct InstallAgentPluginRequest {
/// `"github"` or `"local"`.
pub source_kind: String,
#[serde(default)]
#[specta(optional)]
pub owner: Option<String>,
#[serde(default)]
#[specta(optional)]
pub repo: Option<String>,
#[serde(default)]
#[specta(optional)]
pub git_ref: Option<String>,
/// Pinned root tree SHA from preview when `source_kind == "github"`.
#[serde(default)]
#[specta(optional)]
pub tree_sha: Option<String>,
/// Pinned commit SHA from preview when `source_kind == "github"`.
#[serde(default)]
#[specta(optional)]
pub commit_sha: Option<String>,
#[serde(default)]
pub subpath: String,
#[serde(default)]
#[specta(optional)]
pub local_path: Option<String>,
#[serde(default)]
#[specta(optional)]
pub marketplace: Option<String>,
#[serde(default)]
#[specta(optional)]
pub marketplace_source: Option<String>,
pub scope: McpScope,
/// Native harness the plugin is installed for (`claude`, `copilot`, `codex`, or `gemini`).
pub harness: String,
#[serde(default)]
pub approve_capabilities: bool,
/// The preview's `capabilityHash` the user approved; the install is refused if the installed
/// folder resolves to different executable capabilities.
#[serde(default)]
#[specta(optional)]
pub approved_capability_hash: Option<String>,
#[serde(default)]
pub confirm_warnings: bool,
#[serde(default)]
pub overwrite: bool,
}
/// Selection of one server from an external MCP configuration source to import.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+31
Переглянути файл
@@ -1484,3 +1484,34 @@ async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env()
"claude-md-and-agents-md"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_injection() {
let cli = replay_cli(load_fixture("simple"));
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
let h =
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
let params = json!({
"cwd": h.cwd,
"mcpServers": [],
"_meta": {
"openidea": {
"memory": {
"claudeInstructionFiles": "claude-md-and-agents-md"
},
"plugins": { "activePlugins": ["azure", "linear@mkt"] }
}
}
});
h.request("session/new", params).await.unwrap();
let args = cli.launched.lock()[0].clone();
assert!(!args.iter().any(|a| a == "--plugin-dir"), "{args:?}");
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
assert_eq!(
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
"claude-md-and-agents-md"
);
assert!(parsed["pluginConfigs"]["azure"].is_null());
}
File diff suppressed because it is too large. Load diff
+517 -47
Переглянути файл
@@ -163,6 +163,15 @@ pub struct RepoRef<'a> {
pub trait SkillSourceFetcher: Send + Sync {
fn default_branch(&self, owner: &str, repo: &str, cancel: &CancellationToken) -> IdeResult<String>;
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String>;
/// The root tree SHA recorded in commit `commit_sha`.
fn git_commit_tree_sha(
&self,
owner: &str,
repo: &str,
commit_sha: &str,
cancel: &CancellationToken,
) -> IdeResult<String>;
fn git_tree(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<GitTree>;
fn read_blob(
&self,
@@ -238,6 +247,63 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
.map_err(|e| IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid Git tree: {e}")))
}
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String> {
#[derive(Deserialize)]
struct CommitMeta {
sha: String,
}
let RepoRef { owner, repo, git_ref } = target;
validate_repo_coord(owner, "owner")?;
validate_repo_coord(repo, "repository")?;
validate_git_ref(git_ref)?;
let encoded_ref = encode_url_segment(git_ref);
let url = format!("https://api.github.com/repos/{owner}/{repo}/commits/{encoded_ref}");
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
let meta: CommitMeta = serde_json::from_str(&body).map_err(|e| {
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid GitHub commit: {e}"))
})?;
if !is_git_object_id(&meta.sha) {
return Err(IdeError::new(
ErrorKind::Protocol,
format!("{owner}/{repo}@{git_ref}: invalid GitHub commit SHA"),
));
}
Ok(meta.sha)
}
fn git_commit_tree_sha(
&self,
owner: &str,
repo: &str,
commit_sha: &str,
cancel: &CancellationToken,
) -> IdeResult<String> {
#[derive(Deserialize)]
struct TreeRef {
sha: String,
}
#[derive(Deserialize)]
struct GitCommit {
tree: TreeRef,
}
validate_repo_coord(owner, "owner")?;
validate_repo_coord(repo, "repository")?;
if !is_git_object_id(commit_sha) {
return Err(IdeError::invalid("Invalid commit SHA"));
}
let url = format!("https://api.github.com/repos/{owner}/{repo}/git/commits/{commit_sha}");
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
let commit: GitCommit = serde_json::from_str(&body).map_err(|e| {
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid Git commit: {e}"))
})?;
if !is_git_object_id(&commit.tree.sha) {
return Err(IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid tree SHA")));
}
Ok(commit.tree.sha)
}
fn read_blob(
&self,
target: RepoRef<'_>,
@@ -616,6 +682,17 @@ fn sanitize_repo_as_skill_name(repo: &str) -> String {
out.trim_matches('-').to_owned()
}
pub(crate) struct FetchedSubtree {
pub tree_sha: String,
pub normalized_subpath: String,
pub files: Vec<RemoteSkillFile>,
pub scan_warnings: Vec<SkillScanWarning>,
/// `(relative_path, bytes, executable)` for safe non-symlink files to write on disk.
pub regular_files: Vec<(PathBuf, Vec<u8>, bool)>,
/// `(relative_path, relative_target)` for safe internal symlinks.
pub in_root_symlinks: Vec<(PathBuf, PathBuf)>,
}
struct PreparedSkillBundle {
tree_sha: String,
skill_name: String,
@@ -629,14 +706,19 @@ struct PreparedSkillBundle {
in_root_symlinks: Vec<(PathBuf, PathBuf)>,
}
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
fn fetch_and_scan_bundle(
/// Fetches `target`'s tree (or exactly `pinned_tree_sha` when set) and scans `subpath` with hardened
/// symlink-graph, executable-script, and hidden-Unicode checks.
#[allow(clippy::too_many_arguments)]
pub(crate) fn fetch_and_scan_subtree(
fetcher: &dyn SkillSourceFetcher,
target: RepoRef<'_>,
subpath: &str,
pinned_tree_sha: Option<&str>,
max_files: usize,
max_subtree_bytes: u64,
noun: &str,
cancel: &CancellationToken,
) -> IdeResult<PreparedSkillBundle> {
) -> IdeResult<FetchedSubtree> {
let RepoRef { owner, repo, git_ref } = target;
validate_repo_coord(owner, "owner")?;
validate_repo_coord(repo, "repository")?;
@@ -646,9 +728,8 @@ fn fetch_and_scan_bundle(
let tree = match pinned_tree_sha {
Some(sha) => {
if !is_git_object_id(sha) {
return Err(IdeError::invalid("Preview the skill again before installing it"));
return Err(IdeError::invalid(format!("Preview the {noun} again before installing it")));
}
// The Git trees API accepts a tree SHA in place of a ref.
let tree = fetcher.git_tree(RepoRef { owner, repo, git_ref: sha }, cancel)?;
if !tree.sha.eq_ignore_ascii_case(sha) {
return Err(IdeError::new(
@@ -660,6 +741,14 @@ fn fetch_and_scan_bundle(
}
None => fetcher.git_tree(target, cancel)?,
};
if tree.truncated {
return Err(IdeError::new(
ErrorKind::Protocol,
format!(
"{owner}/{repo}@{git_ref}: GitHub returned a truncated file listing; the {noun} cannot be verified"
),
));
}
let prefix = if normalized_subpath.is_empty() { String::new() } else { format!("{normalized_subpath}/") };
let subtree_entries: Vec<&GitTreeEntry> = tree
@@ -672,27 +761,32 @@ fn fetch_and_scan_bundle(
if subtree_entries.is_empty() {
return Err(IdeError::not_found(format!(
"Skill path {:?} was not found in {owner}/{repo}@{git_ref}",
"{} path {:?} was not found in {owner}/{repo}@{git_ref}",
capitalize(noun),
normalized_subpath
)));
}
if subtree_entries.len() > MAX_SKILL_FILES {
if subtree_entries.len() > max_files {
return Err(IdeError::invalid(format!(
"Skill exceeds maximum of {MAX_SKILL_FILES} files ({} found)",
"{} exceeds maximum of {max_files} files ({} found)",
capitalize(noun),
subtree_entries.len()
)));
}
let declared_total: u64 = subtree_entries.iter().map(|e| e.size.unwrap_or(0)).sum();
if declared_total > MAX_SKILL_SUBTREE_BYTES {
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
if declared_total > max_subtree_bytes {
return Err(IdeError::invalid(format!(
"{} exceeds {} MiB size cap",
capitalize(noun),
max_subtree_bytes >> 20
)));
}
let mut files = Vec::with_capacity(subtree_entries.len());
let mut scan_warnings = Vec::new();
let mut regular_files = Vec::new();
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
let mut skill_markdown: Option<String> = None;
let mut actual_total = 0u64;
for entry in subtree_entries {
@@ -709,12 +803,16 @@ fn fetch_and_scan_bundle(
target,
&entry.path,
&entry.sha,
MAX_SINGLE_BLOB_BYTES.min(MAX_SKILL_SUBTREE_BYTES - actual_total),
MAX_SINGLE_BLOB_BYTES.min(max_subtree_bytes - actual_total),
cancel,
)?;
actual_total = actual_total.saturating_add(bytes.len() as u64);
if actual_total > MAX_SKILL_SUBTREE_BYTES {
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
if actual_total > max_subtree_bytes {
return Err(IdeError::invalid(format!(
"{} exceeds {} MiB size cap",
capitalize(noun),
max_subtree_bytes >> 20
)));
}
if is_symlink {
@@ -748,11 +846,15 @@ fn fetch_and_scan_bundle(
if let Ok(text) = std::str::from_utf8(&bytes) {
scan_hidden_unicode(rel_str, text, &mut scan_warnings);
if rel_str == "SKILL.md" {
skill_markdown = Some(text.to_owned());
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
for tool in frontmatter_shell_tools(text) {
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::AllowedToolsShell,
file: rel_str.to_owned(),
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
});
}
}
} else if rel_str == "SKILL.md" {
return Err(IdeError::invalid("SKILL.md is not valid UTF-8 text"));
}
files.push(RemoteSkillFile {
@@ -767,13 +869,12 @@ fn fetch_and_scan_bundle(
files.sort_by(|a, b| a.path.cmp(&b.path));
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
// Symlinks are judged together: one link may point through another, and an entry placed beneath
// a symlink would be written wherever that link points.
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
if let Some(link) = graph.symlink_ancestor(path) {
return Err(IdeError::invalid(format!(
"Skill entry {:?} is inside symlink {link:?}; the repository tree is malformed",
"{} entry {:?} is inside symlink {link:?}; the repository tree is malformed",
capitalize(noun),
path.display().to_string()
)));
}
@@ -786,26 +887,65 @@ fn fetch_and_scan_bundle(
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::OutOfRootSymlink,
file: rel_str,
message: format!("Symlink target {target_raw:?} leaves the skill folder (omitted on install)"),
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
});
}
}
in_root_symlinks.sort();
let Some(skill_markdown) = skill_markdown else {
return Err(IdeError::invalid("Selected folder does not contain a regular SKILL.md file"));
};
Ok(FetchedSubtree { tree_sha: tree.sha, normalized_subpath, files, scan_warnings, regular_files, in_root_symlinks })
}
let folder_hint = normalized_subpath
fn capitalize(s: &str) -> String {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
}
}
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
fn fetch_and_scan_bundle(
fetcher: &dyn SkillSourceFetcher,
target: RepoRef<'_>,
subpath: &str,
pinned_tree_sha: Option<&str>,
cancel: &CancellationToken,
) -> IdeResult<PreparedSkillBundle> {
let RepoRef { repo, .. } = target;
let mut sub = fetch_and_scan_subtree(
fetcher,
target,
subpath,
pinned_tree_sha,
MAX_SKILL_FILES,
MAX_SKILL_SUBTREE_BYTES,
"skill",
cancel,
)?;
let skill_bytes = sub
.regular_files
.iter()
.find(|(p, _, _)| p == Path::new("SKILL.md"))
.map(|(_, b, _)| b.as_slice())
.ok_or_else(|| IdeError::invalid("Selected folder does not contain a regular SKILL.md file"))?;
let skill_markdown =
std::str::from_utf8(skill_bytes).map_err(|_| IdeError::invalid("SKILL.md is not valid UTF-8 text"))?.to_owned();
let folder_hint = sub
.normalized_subpath
.rsplit('/')
.next()
.filter(|s| !s.is_empty())
.map(str::to_owned)
.unwrap_or_else(|| sanitize_repo_as_skill_name(repo));
// Strip any `SKILL.md` shell-tool warnings already collected so `parse_skill_markdown_metadata` emits them in order.
sub.scan_warnings.retain(|w| !(w.kind == SkillScanWarningKind::AllowedToolsShell && w.file == "SKILL.md"));
let parsed_meta = parse_skill_markdown_metadata(&folder_hint, &skill_markdown)?;
for tool in &parsed_meta.shell_tools {
scan_warnings.push(SkillScanWarning {
sub.scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::AllowedToolsShell,
file: "SKILL.md".into(),
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
@@ -813,14 +953,14 @@ fn fetch_and_scan_bundle(
}
Ok(PreparedSkillBundle {
tree_sha: tree.sha,
tree_sha: sub.tree_sha,
skill_name: parsed_meta.name,
description: parsed_meta.description,
skill_markdown,
files,
scan_warnings,
regular_files,
in_root_symlinks,
files: sub.files,
scan_warnings: sub.scan_warnings,
regular_files: sub.regular_files,
in_root_symlinks: sub.in_root_symlinks,
})
}
@@ -1140,6 +1280,33 @@ fn create_parent_dirs_no_follow(root: &Path, rel: &Path) -> IdeResult<()> {
Ok(())
}
/// Creates `target` below the existing `anchor` (the home or project folder) without following a
/// symlink in any directory between them, the harness store root included.
fn create_dirs_below_anchor(anchor: &Path, target: &Path) -> IdeResult<()> {
if !anchor.is_dir() {
return Err(IdeError::not_found(format!("{} does not exist", anchor.display())));
}
let rel = target
.strip_prefix(anchor)
.map_err(|_| IdeError::invalid(format!("{} is outside {}", target.display(), anchor.display())))?;
let mut dir = anchor.to_path_buf();
for component in rel.components() {
if !matches!(component, Component::Normal(_)) {
return Err(IdeError::invalid(format!("{} is not a plain path below the store", target.display())));
}
dir.push(component);
match std::fs::symlink_metadata(&dir) {
Ok(meta) if meta.is_dir() => {}
Ok(_) => {
return Err(IdeError::invalid(format!("{} passes through a symlink or file", dir.display())));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => std::fs::create_dir(&dir)?,
Err(e) => return Err(e.into()),
}
}
Ok(())
}
/// Whether the symlink at `link` resolves strictly inside `root` (canonical), following links on disk.
/// Components that do not exist are resolved lexically.
#[cfg(unix)]
@@ -1220,15 +1387,16 @@ pub fn install_skill(
workspace_root: Option<&Path>,
cancel: &CancellationToken,
) -> IdeResult<PathBuf> {
let target_root = match req.scope {
// Anchored at the home or project folder: nothing below it may be a symlink, store included.
let (anchor, target_root) = match req.scope {
McpScope::User => {
let home = user_home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?;
home.join(".agents").join("skills")
(home.to_path_buf(), home.join(".agents").join("skills"))
}
McpScope::Workspace => {
let ws = workspace_root
.ok_or_else(|| IdeError::invalid("Open a trusted project to install workspace skills"))?;
ws.join(".agents").join("skills")
(ws.to_path_buf(), ws.join(".agents").join("skills"))
}
};
@@ -1245,20 +1413,60 @@ pub fn install_skill(
));
}
std::fs::create_dir_all(&target_root)?;
let final_dir = target_root.join(&bundle.skill_name);
if final_dir.exists() && !req.overwrite {
write_staged_subtree(
&anchor,
&target_root,
&bundle.skill_name,
req.overwrite,
"Skill",
&bundle.regular_files,
&bundle.in_root_symlinks,
&[],
)
}
/// Atomically writes `regular_files`, `in_root_symlinks`, and `extra_files` into a staging folder
/// under `target_root`, verifies created symlinks stay inside the folder, and swaps into `<target_root>/<folder_name>`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn write_staged_subtree(
anchor: &Path,
target_root: &Path,
folder_name: &str,
overwrite: bool,
noun_cap: &str,
regular_files: &[(PathBuf, Vec<u8>, bool)],
in_root_symlinks: &[(PathBuf, PathBuf)],
extra_files: &[(&str, &[u8])],
) -> IdeResult<PathBuf> {
create_dirs_below_anchor(anchor, target_root)?;
if folder_name.is_empty() || !Path::new(folder_name).components().all(|c| matches!(c, Component::Normal(_))) {
return Err(IdeError::invalid(format!("Invalid {} folder name", noun_cap.to_ascii_lowercase())));
}
let final_dir = target_root.join(folder_name);
let existing = match std::fs::symlink_metadata(&final_dir) {
Ok(meta) if meta.is_dir() => true,
Ok(_) => {
return Err(IdeError::invalid(format!(
"{} is a symlink or file, not a {} folder",
final_dir.display(),
noun_cap.to_ascii_lowercase()
)));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
Err(e) => return Err(e.into()),
};
if existing && !overwrite {
return Err(IdeError::new(
ErrorKind::AlreadyExists,
format!("Skill `{}` is already installed in {}", bundle.skill_name, target_root.display()),
format!("{noun_cap} `{folder_name}` is already installed in {}", target_root.display()),
));
}
let nonce = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
let staging = target_root.join(format!(".staging-{}-{nonce}-{}", bundle.skill_name, std::process::id()));
let staging = target_root.join(format!(".staging-{folder_name}-{nonce}-{}", std::process::id()));
let write_res = (|| -> IdeResult<()> {
std::fs::create_dir_all(&staging)?;
for (rel_path, bytes, is_exec) in &bundle.regular_files {
for (rel_path, bytes, is_exec) in regular_files {
create_parent_dirs_no_follow(&staging, rel_path)?;
let dest = staging.join(rel_path);
std::fs::write(&dest, bytes)?;
@@ -1270,7 +1478,12 @@ pub fn install_skill(
#[cfg(not(unix))]
let _ = is_exec;
}
for (rel_link, target) in &bundle.in_root_symlinks {
for (rel_str, bytes) in extra_files {
let rel_path = validate_rel_skill_file(rel_str)?;
create_parent_dirs_no_follow(&staging, &rel_path)?;
std::fs::write(staging.join(&rel_path), bytes)?;
}
for (rel_link, target) in in_root_symlinks {
create_parent_dirs_no_follow(&staging, rel_link)?;
let dest = staging.join(rel_link);
#[cfg(unix)]
@@ -1288,17 +1501,18 @@ pub fn install_skill(
#[cfg(unix)]
{
let root = std::fs::canonicalize(&staging)?;
for (rel_link, _) in &bundle.in_root_symlinks {
for (rel_link, _) in in_root_symlinks {
if !link_resolves_inside(&root, &staging.join(rel_link)) {
return Err(IdeError::invalid(format!(
"Symlink {:?} leaves the skill folder",
rel_link.display().to_string()
"Symlink {:?} leaves the {} folder",
rel_link.display().to_string(),
noun_cap.to_ascii_lowercase()
)));
}
}
}
let backup = if final_dir.exists() {
let bak = target_root.join(format!(".old-{}-{nonce}", bundle.skill_name));
let backup = if existing {
let bak = target_root.join(format!(".old-{folder_name}-{nonce}"));
std::fs::rename(&final_dir, &bak)?;
Some(bak)
} else {
@@ -1323,6 +1537,179 @@ pub fn install_skill(
Ok(final_dir)
}
/// Scans a local directory on disk with the same symlink-graph, executable-script, and hidden-Unicode
/// checks used for remote GitHub subtrees.
/// Content digest of a scanned local folder, used to pin a local preview to its install.
fn local_subtree_digest(regular_files: &[(PathBuf, Vec<u8>, bool)], symlinks: &[(PathBuf, PathBuf)]) -> String {
let mut hasher = blake3::Hasher::new();
hasher.update(b"openidea-local-subtree-v1\0");
for (path, bytes, executable) in regular_files {
hasher.update(b"f\0");
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
hasher.update(&[0, u8::from(*executable)]);
hasher.update(&(bytes.len() as u64).to_le_bytes());
hasher.update(bytes);
}
for (path, target) in symlinks {
hasher.update(b"l\0");
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
hasher.update(b"\0");
hasher.update(target.to_string_lossy().replace('\\', "/").as_bytes());
hasher.update(b"\0");
}
format!("local-blake3:{}", hasher.finalize().to_hex())
}
pub(crate) fn scan_local_subtree(
dir: &Path,
max_files: usize,
max_subtree_bytes: u64,
noun: &str,
) -> IdeResult<FetchedSubtree> {
if !dir.is_dir() {
return Err(IdeError::not_found(format!("Directory {} does not exist", dir.display())));
}
let mut files = Vec::new();
let mut scan_warnings = Vec::new();
let mut regular_files = Vec::new();
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
let mut actual_total = 0u64;
let mut stack = vec![(dir.to_path_buf(), String::new())];
while let Some((cur_dir, rel_prefix)) = stack.pop() {
let mut entries: Vec<_> = std::fs::read_dir(&cur_dir)?.filter_map(Result::ok).collect();
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let name = entry.file_name();
let Some(name_str) = name.to_str() else {
return Err(IdeError::invalid(format!(
"{} contains a file name that is not valid UTF-8: {}",
capitalize(noun),
entry.path().display()
)));
};
if name_str == ".git" || name_str == "node_modules" || name_str == "target" {
continue;
}
let rel_str = if rel_prefix.is_empty() { name_str.to_owned() } else { format!("{rel_prefix}/{name_str}") };
let rel_path = validate_rel_skill_file(&rel_str)?;
let full = entry.path();
let meta = std::fs::symlink_metadata(&full)?;
if (meta.file_type().is_symlink() || meta.file_type().is_file())
&& regular_files.len() + symlinks.len() >= max_files
{
return Err(IdeError::invalid(format!("{} exceeds maximum of {max_files} files", capitalize(noun))));
}
if meta.file_type().is_symlink() {
let target_raw = std::fs::read_link(&full)?.to_string_lossy().replace('\\', "/");
symlinks.push((rel_path, rel_str.clone(), target_raw));
files.push(RemoteSkillFile { path: rel_str, size: 0, executable: false, symlink: true });
continue;
}
if meta.file_type().is_dir() {
stack.push((full, rel_str));
continue;
}
if !meta.file_type().is_file() {
continue;
}
if meta.len() > MAX_SINGLE_BLOB_BYTES {
return Err(IdeError::invalid(format!(
"File {rel_str:?} exceeds {} MiB size cap",
MAX_SINGLE_BLOB_BYTES >> 20
)));
}
let bytes = std::fs::read(&full)?;
actual_total = actual_total.saturating_add(bytes.len() as u64);
if actual_total > max_subtree_bytes {
return Err(IdeError::invalid(format!(
"{} exceeds {} MiB size cap",
capitalize(noun),
max_subtree_bytes >> 20
)));
}
#[cfg(unix)]
let is_exec_mode = {
use std::os::unix::fs::PermissionsExt;
meta.permissions().mode() & 0o111 != 0
};
#[cfg(not(unix))]
let is_exec_mode = false;
let has_shebang = bytes.starts_with(b"#!");
let is_script_path = is_executable_or_script_path(&rel_path);
if is_exec_mode || has_shebang || is_script_path {
let reason = if is_exec_mode {
"executable file mode"
} else if has_shebang {
"script with `#!` interpreter header"
} else {
"bundled script or native binary"
};
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::ExecutableScript,
file: rel_str.clone(),
message: format!("Contains {reason}"),
});
}
if let Ok(text) = std::str::from_utf8(&bytes) {
scan_hidden_unicode(&rel_str, text, &mut scan_warnings);
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
for tool in frontmatter_shell_tools(text) {
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::AllowedToolsShell,
file: rel_str.clone(),
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
});
}
}
}
files.push(RemoteSkillFile {
path: rel_str,
size: bytes.len() as u64,
executable: is_exec_mode || has_shebang,
symlink: false,
});
regular_files.push((rel_path, bytes, is_exec_mode));
}
}
files.sort_by(|a, b| a.path.cmp(&b.path));
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
if let Some(link) = graph.symlink_ancestor(path) {
return Err(IdeError::invalid(format!(
"{} entry {:?} is inside symlink {link:?}",
capitalize(noun),
path.display().to_string()
)));
}
}
let mut in_root_symlinks = Vec::new();
for (rel_path, rel_str, target_raw) in symlinks {
if graph.stays_inside(&rel_path, &target_raw) {
in_root_symlinks.push((rel_path, PathBuf::from(target_raw)));
} else {
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::OutOfRootSymlink,
file: rel_str,
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
});
}
}
in_root_symlinks.sort();
Ok(FetchedSubtree {
tree_sha: local_subtree_digest(&regular_files, &in_root_symlinks),
normalized_subpath: String::new(),
files,
scan_warnings,
regular_files,
in_root_symlinks,
})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1374,6 +1761,25 @@ mod tests {
.cloned()
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
}
fn git_commit_sha(&self, target: RepoRef<'_>, _cancel: &CancellationToken) -> IdeResult<String> {
self.trees
.get(target.git_ref)
.map(|_| git_blob_id(format!("commit:{}", target.git_ref).as_bytes()))
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
}
fn git_commit_tree_sha(
&self,
_owner: &str,
_repo: &str,
commit_sha: &str,
_cancel: &CancellationToken,
) -> IdeResult<String> {
self.trees
.iter()
.find(|(git_ref, _)| git_blob_id(format!("commit:{git_ref}").as_bytes()) == commit_sha)
.map(|(_, tree)| tree.sha.clone())
.ok_or_else(|| IdeError::not_found(format!("unknown commit {commit_sha}")))
}
fn read_blob(
&self,
@@ -1440,7 +1846,9 @@ mod tests {
let cancel = CancellationToken::new();
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
std::fs::create_dir_all(&home).unwrap();
let ws = tmp.path().join("ws");
std::fs::create_dir_all(&ws).unwrap();
// Bare `owner/repo` lists both skills; `owner/repo@clean-skill` falls back from ref lookup to skill filter!
let all = browse_skills(&fetcher, "acme/skills", &cancel).unwrap();
@@ -1796,4 +2204,66 @@ mod tests {
.unwrap();
assert!(dest.join("SKILL.md").is_file());
}
#[cfg(unix)]
#[test]
fn local_scan_counts_symlinks_toward_the_file_cap() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("SKILL.md"), "x").unwrap();
for i in 0..3 {
std::os::unix::fs::symlink("SKILL.md", tmp.path().join(format!("link-{i}"))).unwrap();
}
let Err(err) = scan_local_subtree(tmp.path(), 3, 1 << 20, "plugin") else { panic!("symlinks must count") };
assert!(err.to_string().contains("maximum of 3 files"), "{err}");
}
#[test]
fn truncated_tree_listings_are_rejected() {
let mut fetcher = FakeFetcher::new();
fetcher.add_tree("main", vec![("skills/a/SKILL.md", "100644", b"---\nname: a\ndescription: a\n---\n")]);
fetcher.trees.get_mut("main").unwrap().truncated = true;
let cancel = CancellationToken::new();
let target = RepoRef { owner: "o", repo: "r", git_ref: "main" };
let Err(err) = fetch_and_scan_subtree(&fetcher, target, "skills/a", None, 10, 1 << 20, "skill", &cancel) else {
panic!("a truncated listing cannot be verified")
};
assert!(err.to_string().contains("truncated"), "{err}");
}
#[cfg(unix)]
#[test]
fn staged_installs_do_not_follow_symlinks_below_the_store() {
let tmp = tempfile::tempdir().unwrap();
let store = tmp.path().join("store");
let outside = tmp.path().join("outside");
std::fs::create_dir_all(&store).unwrap();
std::fs::create_dir_all(&outside).unwrap();
std::os::unix::fs::symlink(&outside, store.join("mkt")).unwrap();
let files = vec![(PathBuf::from("plugin.json"), b"{}".to_vec(), false)];
let Err(err) = write_staged_subtree(&store, &store.join("mkt"), "plugin", false, "Plugin", &files, &[], &[])
else {
panic!("a symlinked marketplace folder must not be written through")
};
assert!(err.to_string().contains("symlink"), "{err}");
assert!(std::fs::read_dir(&outside).unwrap().next().is_none(), "nothing was written outside the store");
// The store root itself (`<home>/.claude/plugins` → elsewhere) is checked as well.
let home = tmp.path().join("home");
std::fs::create_dir_all(home.join(".claude")).unwrap();
std::os::unix::fs::symlink(&outside, home.join(".claude/plugins")).unwrap();
let store_root = home.join(".claude/plugins/cache/mkt");
let Err(err) = write_staged_subtree(&home, &store_root, "plugin", false, "Plugin", &files, &[], &[]) else {
panic!("a symlinked store root must not be written through")
};
assert!(err.to_string().contains("symlink"), "{err}");
assert!(std::fs::read_dir(&outside).unwrap().next().is_none());
std::fs::create_dir_all(store.join("real")).unwrap();
std::os::unix::fs::symlink(&outside, store.join("real/plugin")).unwrap();
let Err(err) = write_staged_subtree(&store, &store.join("real"), "plugin", true, "Plugin", &files, &[], &[])
else {
panic!("an existing symlinked plugin folder must not be replaced through")
};
assert!(err.to_string().contains("symlink"), "{err}");
}
}
+34 -82
Переглянути файл
@@ -275,12 +275,27 @@ pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Ag
}
/// [`discover_skills_in`] plus the `<dir>` skill folders contributed by enabled OpenIDEA
/// plugins (`[[contributes.skills]]`). Workspace and user skills take precedence on a name
/// clash; a plugin skill is never silently renamed.
/// plugins (`[[contributes.skills]]`) and unified agent plugin bundles (`plugins.rs`).
/// Workspace and user skills take precedence on a name clash; a plugin skill is never silently renamed.
pub fn discover_skills_with_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
plugin_skill_dirs: &[PathBuf],
) -> Vec<AgentSkill> {
let default_policy = crate::plugins::PluginsPolicy { workspace_roots: workspaces.to_vec(), ..Default::default() };
let states =
crate::plugins::resolve_plugins(crate::plugins::discover_plugins(workspaces, home), &default_policy, None);
let projected = crate::plugins::projected_skill_roots(&states, None);
discover_skills_with_agent_plugins(workspaces, home, plugin_skill_dirs, &projected)
}
/// Discovers skills across `workspaces`, `home`, OpenIDEA IDE-plugin skill folders (`plugin_skill_dirs`),
/// and resolved agent plugin bundle roots (`agent_plugin_roots`).
pub fn discover_skills_with_agent_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
plugin_skill_dirs: &[PathBuf],
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
) -> Vec<AgentSkill> {
let mut out: Vec<AgentSkill> = Vec::new();
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
@@ -338,9 +353,19 @@ pub fn discover_skills_with_plugins(
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
push_skill(parse_skill_file(dir, &folder, &text, AgentSkillSource::Plugin));
}
if let Some(home) = home {
for (root, source) in copilot_installed_plugin_roots(&home.join(".copilot")) {
for skill in skills_of(&root, source) {
for proj in agent_plugin_roots {
if proj.dir.join("SKILL.md").is_file() && proj.dir.file_name().and_then(|s| s.to_str()) != Some("skills") {
let Some(folder) = file_name(&proj.dir) else { continue };
if let Ok(text) = std::fs::read_to_string(proj.dir.join("SKILL.md")) {
let mut skill = parse_skill_file(&proj.dir, &folder, &text, proj.source);
skill.plugin_id = Some(proj.plugin_id.clone());
skill.plugin_name = Some(proj.plugin_name.clone());
push_skill(skill);
}
} else {
for mut skill in skills_of(&proj.dir, proj.source) {
skill.plugin_id = Some(proj.plugin_id.clone());
skill.plugin_name = Some(proj.plugin_name.clone());
push_skill(skill);
}
}
@@ -388,83 +413,6 @@ fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
out
}
/// Discovers skill roots inside `~/.copilot/installed-plugins`, supporting both Copilot CLI's
/// 2-level `<marketplace-or-_direct>/<plugin>` layout (and `config.json` `installedPlugins`
/// enablement) and flat 1-level `<plugin>` folders.
fn copilot_installed_plugin_roots(copilot_dir: &Path) -> Vec<(PathBuf, AgentSkillSource)> {
let mut disabled_paths: HashSet<PathBuf> = HashSet::new();
let mut plugin_dirs: Vec<PathBuf> = Vec::new();
let mut seen_dirs: HashSet<PathBuf> = HashSet::new();
let mut push_plugin = |dir: PathBuf, disabled: &HashSet<PathBuf>| {
if !dir.is_dir() {
return;
}
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
if disabled.contains(&canon) || !seen_dirs.insert(canon) {
return;
}
plugin_dirs.push(dir);
};
if let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json"))
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
&& let Some(installed) = root.get("installedPlugins").and_then(serde_json::Value::as_array)
{
for entry in installed {
let Some(raw_cache) = entry.get("cache_path").and_then(serde_json::Value::as_str).map(str::trim) else {
continue;
};
if raw_cache.is_empty() {
continue;
}
let dir =
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
if entry.get("enabled").and_then(serde_json::Value::as_bool) == Some(false) {
disabled_paths.insert(dunce::canonicalize(&dir).unwrap_or(dir));
} else {
push_plugin(dir, &disabled_paths);
}
}
}
let plugins_root = copilot_dir.join("installed-plugins");
for entry in sorted(&plugins_root) {
if !entry.is_dir() {
continue;
}
if looks_like_plugin_dir(&entry) {
push_plugin(entry, &disabled_paths);
} else {
// 2-level `<marketplace>/<plugin>` or `_direct/<plugin>`.
for sub in sorted(&entry) {
if sub.is_dir() {
push_plugin(sub, &disabled_paths);
}
}
}
}
let mut roots = Vec::new();
for plugin in plugin_dirs {
let skills_sub = plugin.join("skills");
if skills_sub.is_dir() {
roots.push((skills_sub, AgentSkillSource::CopilotUser));
} else {
roots.push((plugin, AgentSkillSource::CopilotUser));
}
}
roots
}
fn looks_like_plugin_dir(dir: &Path) -> bool {
dir.join("skills").is_dir()
|| dir.join("plugin.json").is_file()
|| dir.join(".plugin").is_dir()
|| dir.join(".claude-plugin").is_dir()
|| dir.join(".cursor-plugin").is_dir()
|| dir.join("SKILL.md").is_file()
}
/// The skills of one root: `<name>/SKILL.md` folders and `<category>/<name>/SKILL.md`
/// category folders, validated.
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
@@ -544,6 +492,8 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour
paths,
valid: warnings.is_empty(),
warnings,
plugin_id: None,
plugin_name: None,
}
}
@@ -1070,6 +1020,8 @@ mod tests {
paths: Vec::new(),
valid: true,
warnings: Vec::new(),
plugin_id: None,
plugin_name: None,
}
}
+4
Переглянути файл
@@ -6056,6 +6056,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
plugin_id: None,
plugin_name: None,
},
McpServer {
id: "user::slack".into(),
@@ -6070,6 +6072,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
plugin_id: None,
plugin_name: None,
},
]
}));
+377 -7
Переглянути файл
@@ -9,12 +9,34 @@ use std::path::{Path, PathBuf};
use std::time::{Duration, UNIX_EPOCH};
pub(crate) struct Created {
#[cfg_attr(not(test), allow(dead_code))]
pub path: PathBuf,
pub cwd: PathBuf,
pub branch: String,
pub base: String,
pub base_commit: String,
}
const OWNERSHIP_MARKER: &str = "openidea-worktree.json";
const OWNERSHIP_TAG: &str = "openidea-agent";
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct WorktreeOwnership {
owner: String,
task_id: String,
worktree_root: PathBuf,
repo_root: PathBuf,
}
/// Returns the canonical root of the Git repository containing `project_root`, if any.
pub fn canonical_repo_root(project_root: &Path) -> IdeResult<Option<PathBuf>> {
match Repo::discover(project_root)? {
Some(repo) => Ok(Some(dunce::canonicalize(repo.root())?)),
None => Ok(None),
}
}
/// The repository of `path`, free to execute: the host runs every agent command that
/// reaches a repository only in a trusted project.
fn discover(path: &Path) -> IdeResult<Option<Repo>> {
@@ -157,9 +179,38 @@ pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
}
}
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
#[cfg(test)]
pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, base: Option<&str>) -> IdeResult<Created> {
create_for_task(project_root, worktrees_dir, "", title, base)
}
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
/// Records an ownership marker in the linked worktree's private `git_dir` and preserves any
/// project-relative subdirectory inside `project_root` when `project_root` is below `repo.root()`.
pub(crate) fn create_for_task(
project_root: &Path,
worktrees_dir: &Path,
task_id: &str,
title: &str,
base: Option<&str>,
) -> IdeResult<Created> {
let repo = repo_at(project_root)?;
let canon_repo = dunce::canonicalize(repo.root())?;
let canon_proj = dunce::canonicalize(project_root)?;
let rel_subdir = if canon_proj != canon_repo {
canon_proj
.strip_prefix(&canon_repo)
.map_err(|_| {
IdeError::invalid(format!(
"{} is outside git repository {}",
canon_proj.display(),
canon_repo.display()
))
})?
.to_path_buf()
} else {
PathBuf::new()
};
let (base, base_commit) = match base.map(str::trim).filter(|b| !b.is_empty()) {
Some(b) => {
let commit =
@@ -177,7 +228,125 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
let path = worktrees_dir.join(&slug);
let branch = format!("agent/{slug}");
repo.add_worktree(&path, &base_commit, Some(&branch))?;
Ok(Created { path, branch, base, base_commit })
let canon_wt = match dunce::canonicalize(&path) {
Ok(p) => p,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e.into());
}
};
let wt_repo = match repo_at(&canon_wt) {
Ok(r) => r,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
};
let [git_dir, common_dir] = match wt_repo.metadata_dirs() {
Ok(dirs) => dirs,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
};
if dunce::canonicalize(&git_dir).ok() == dunce::canonicalize(&common_dir).ok() {
let _ = repo.remove_worktree(&path, false);
return Err(IdeError::internal("linked worktree did not receive a separate git metadata directory"));
}
let marker = WorktreeOwnership {
owner: OWNERSHIP_TAG.to_owned(),
task_id: task_id.to_owned(),
worktree_root: canon_wt.clone(),
repo_root: canon_repo,
};
if let Err(e) = serde_json::to_vec_pretty(&marker)
.map_err(|e| IdeError::internal(e.to_string()))
.and_then(|bytes| ide_vfs::write_atomic(&git_dir.join(OWNERSHIP_MARKER), &bytes))
{
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
let raw_cwd = if rel_subdir.as_os_str().is_empty() { canon_wt.clone() } else { canon_wt.join(&rel_subdir) };
if !raw_cwd.is_dir() {
let _ = repo.remove_worktree(&path, false);
return Err(IdeError::invalid(format!(
"project folder {} does not exist in base revision {}",
rel_subdir.display(),
base
)));
}
let canon_cwd = match verify_confined_worktree_subdir(&canon_wt, &raw_cwd) {
Ok(c) => c,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
};
Ok(Created { path, cwd: canon_cwd, branch, base, base_commit })
}
fn verify_confined_worktree_subdir(canon_wt_root: &Path, target_cwd: &Path) -> IdeResult<PathBuf> {
let canon_cwd = dunce::canonicalize(target_cwd)?;
let real_wt = ide_core::real_path::resolve_real(canon_wt_root);
let real_cwd = ide_core::real_path::resolve_real(target_cwd);
if !canon_cwd.starts_with(canon_wt_root)
|| !real_cwd.starts_with(&real_wt)
|| ide_core::real_path::reaches_git_dir(&real_wt, &real_cwd)
{
return Err(IdeError::invalid(format!(
"worktree working directory {} resolves outside worktree {}",
target_cwd.display(),
canon_wt_root.display()
)));
}
Ok(canon_cwd)
}
/// Canonicalizes `cwd` of an existing `Isolation::Worktree` task and verifies that it still
/// resolves strictly inside its own worktree checkout root under `worktrees_dir` (preventing
/// symlink escapes on reused sessions/turns).
pub(crate) fn verify_confined_worktree_cwd(worktrees_dir: &Path, cwd: &Path) -> IdeResult<PathBuf> {
let (wt_root, wt_base) = worktree_checkout_root(worktrees_dir, cwd);
if !wt_root.starts_with(&wt_base) || wt_root == wt_base {
return Err(IdeError::invalid(format!(
"worktree working directory {} is outside managed worktrees directory {}",
cwd.display(),
worktrees_dir.display()
)));
}
let canon_wt_root = dunce::canonicalize(&wt_root)?;
let canon_wt_dir = dunce::canonicalize(worktrees_dir)?;
if !canon_wt_root.starts_with(&canon_wt_dir)
|| canon_wt_root == canon_wt_dir
|| canon_wt_root.parent() != Some(canon_wt_dir.as_path())
{
return Err(IdeError::invalid("worktree checkout root escaped managed worktrees directory"));
}
verify_confined_worktree_subdir(&canon_wt_root, cwd)
}
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
if let Ok(rel) = path.strip_prefix(worktrees_dir)
&& let Some(first) = rel.components().next()
{
return (worktrees_dir.join(first), worktrees_dir.to_path_buf());
}
if let Ok(canon_wt_dir) = dunce::canonicalize(worktrees_dir) {
if let Ok(rel) = path.strip_prefix(&canon_wt_dir)
&& let Some(first) = rel.components().next()
{
return (canon_wt_dir.join(first), canon_wt_dir);
}
if let Ok(canon_path) = dunce::canonicalize(path)
&& let Ok(rel) = canon_path.strip_prefix(&canon_wt_dir)
&& let Some(first) = rel.components().next()
{
return (canon_wt_dir.join(first), canon_wt_dir);
}
}
(path.to_path_buf(), worktrees_dir.to_path_buf())
}
/// `git worktree remove --force -- <path>`. When git no longer recognizes the
@@ -186,19 +355,94 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
/// ours, so it is removed directly to keep the task deletable (a stale
/// registration prunes later); anything else keeps git's error.
pub(crate) fn remove(project_root: &Path, worktrees_dir: &Path, path: &Path) -> IdeResult<()> {
let (target, wt_base) = worktree_checkout_root(worktrees_dir, path);
let repo = repo_at(project_root)?;
let err = match repo.remove_worktree(path, true) {
let err = match repo.remove_worktree(&target, true) {
Ok(()) => return Ok(()),
Err(e) => e,
};
if !path.exists() {
if !target.exists() {
return Ok(());
}
if !path.starts_with(worktrees_dir) || path == worktrees_dir {
if !target.starts_with(&wt_base) || target == wt_base {
return Err(err);
}
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(path))
.map_err(|e| IdeError::internal(format!("{}: {e}", path.display())))
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(&target))
.map_err(|e| IdeError::internal(format!("{}: {e}", target.display())))
}
/// Safely removes an automation worktree ONLY after verifying its private `git_dir` ownership
/// marker (`openidea-worktree.json`) matches `task_id` and `worktrees_dir`.
///
/// - When `require_clean` is `true` (zero-diff GC): verifies `HEAD == base_commit` and both the
/// Git index (staged) and working tree (unstaged + untracked) are completely clean right before
/// running **non-forced** `git worktree remove` (`force = false`). Returns `Ok(false)` without
/// modifying disk if the worktree has any commits, staged changes, unstaged edits, or untracked
/// files.
/// - Never falls back to `remove_dir_all` on any ownership or Git error: any error keeps the
/// checkout intact.
pub(crate) fn remove_owned_automation_worktree(
project_root: &Path,
worktrees_dir: &Path,
cwd: &Path,
task_id: &str,
base_commit: Option<&str>,
require_clean: bool,
) -> IdeResult<bool> {
if !cwd.exists() || !worktrees_dir.exists() {
return Ok(false);
}
let canon_worktrees = dunce::canonicalize(worktrees_dir)?;
let canon_cwd = dunce::canonicalize(cwd)?;
if !canon_cwd.starts_with(&canon_worktrees) || canon_cwd == canon_worktrees {
return Err(IdeError::invalid("refusing to clean worktree outside managed worktrees directory"));
}
let main_repo = repo_at(project_root)?;
let wt_repo = repo_at(&canon_cwd)?;
let canon_wt_root = dunce::canonicalize(wt_repo.root())?;
if !canon_wt_root.starts_with(&canon_worktrees)
|| canon_wt_root == canon_worktrees
|| canon_wt_root.parent() != Some(canon_worktrees.as_path())
{
return Err(IdeError::invalid("worktree root does not match managed worktrees directory"));
}
let [git_dir, wt_common] = wt_repo.metadata_dirs()?;
let [_, main_common] = main_repo.metadata_dirs()?;
let canon_git_dir = dunce::canonicalize(&git_dir)?;
let canon_wt_common = dunce::canonicalize(&wt_common)?;
let canon_main_common = dunce::canonicalize(&main_common)?;
if canon_git_dir == canon_wt_common || canon_wt_common != canon_main_common {
return Err(IdeError::invalid("target checkout is not a linked worktree of this repository"));
}
let marker_bytes = std::fs::read(canon_git_dir.join(OWNERSHIP_MARKER))
.map_err(|_| IdeError::invalid("refusing to remove worktree without OpenIDEA ownership marker"))?;
let marker: WorktreeOwnership = serde_json::from_slice(&marker_bytes)
.map_err(|_| IdeError::invalid("corrupt OpenIDEA worktree ownership marker"))?;
let marker_root = dunce::canonicalize(&marker.worktree_root).unwrap_or(marker.worktree_root);
if marker.owner != OWNERSHIP_TAG || marker.task_id != task_id || marker_root != canon_wt_root {
return Err(IdeError::invalid("worktree ownership marker does not match task"));
}
if require_clean {
let Some(base) = base_commit else {
return Ok(false);
};
if wt_repo.head()?.1.as_deref() != Some(base) {
return Ok(false);
}
// `status()` checks BOTH HEAD↔index (staged) and index↔worktree (unstaged + untracked).
if !wt_repo.status()?.is_empty() {
return Ok(false);
}
if !wt_repo.diff_with_worktree(base)?.is_empty() {
return Ok(false);
}
main_repo.remove_worktree(&canon_wt_root, false)?;
return Ok(true);
}
main_repo.remove_worktree(&canon_wt_root, true)?;
Ok(true)
}
/// On Windows a folder can't be deleted while a process still has a file in it open
@@ -1944,4 +2188,130 @@ mod tests {
changed.sort();
assert_eq!(changed, ["edited", "new", "reverted"]);
}
#[test]
fn owned_worktree_cleanup_preserves_subproject_cwd_catches_staged_changes_and_verifies_ownership() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
let sub = repo.join("packages").join("subapp");
std::fs::create_dir_all(&sub).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
git(&repo, &["config", "core.autocrlf", "false"]);
std::fs::write(repo.join("root.txt"), "root\n").unwrap();
std::fs::write(sub.join("index.ts"), "export const x = 1;\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let wt_dir = tmp.path().join("wt");
let created = create_for_task(&sub, &wt_dir, "task-1", "Sub Audit", None).unwrap();
assert_eq!(
dunce::canonicalize(&created.cwd).unwrap(),
dunce::canonicalize(&created.path).unwrap().join("packages").join("subapp"),
"project-relative cwd inside parent repo must be preserved inside worktree"
);
// Wrong task_id is refused and keeps the checkout untouched.
assert!(
remove_owned_automation_worktree(
&sub,
&wt_dir,
&created.cwd,
"wrong-task",
Some(&created.base_commit),
true,
)
.is_err()
);
assert!(created.path.exists());
// Staged-only change (index differs from HEAD while working tree matches HEAD!) is NOT clean!
std::fs::write(created.cwd.join("index.ts"), "export const x = 2;\n").unwrap();
git(&created.path, &["add", "packages/subapp/index.ts"]);
std::fs::write(created.cwd.join("index.ts"), "export const x = 1;\n").unwrap();
let removed_staged =
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
.unwrap();
assert!(!removed_staged, "staged-only index change must prevent zero-diff worktree GC");
assert!(created.path.exists());
// Reset index back to HEAD -> zero-diff GC removes the worktree via non-forced `git worktree remove`.
git(&created.path, &["reset", "-q", "HEAD", "--", "packages/subapp/index.ts"]);
let removed_clean =
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
.unwrap();
assert!(removed_clean);
assert!(!created.path.exists());
// Foreign / manually created git worktree inside `wt_dir` without ownership marker is NEVER deleted.
let manual_wt = wt_dir.join("foreign");
git(&repo, &["worktree", "add", "-q", "-b", "manual-branch", manual_wt.to_str().unwrap(), "HEAD"]);
assert!(
remove_owned_automation_worktree(&repo, &wt_dir, &manual_wt, "task-2", Some(&created.base_commit), false,)
.is_err()
);
assert!(manual_wt.exists(), "worktree without OpenIDEA ownership marker must never be deleted");
}
#[cfg(unix)]
#[test]
fn symlinked_subproject_cwd_escaping_worktree_is_rejected_on_create_and_reuse() {
let tmp = tempfile::tempdir().unwrap();
let outside = tmp.path().join("outside");
std::fs::create_dir_all(&outside).unwrap();
std::fs::write(outside.join("secret.txt"), "nope\n").unwrap();
let repo = tmp.path().join("repo");
let packages = repo.join("packages");
std::fs::create_dir_all(&packages).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
git(&repo, &["config", "core.autocrlf", "false"]);
// 1a. Direct symlink pointing outside git is rejected immediately.
let escape_link = packages.join("escape");
std::os::unix::fs::symlink(&outside, &escape_link).unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "symlink escape"]);
let wt_dir = tmp.path().join("wt");
assert!(create_for_task(&escape_link, &wt_dir, "task-escape-direct", "Escape", None).is_err());
// 1b. Committed symlink in `HEAD` (`packages/tricky -> ../../outside`) while the main
// checkout temporarily has a real directory at `packages/tricky`: `git worktree add`
// checks out `HEAD`'s symlink inside the worktree, and `verify_confined_worktree_subdir`
// must catch the escape and clean up the worktree!
let tricky = packages.join("tricky");
std::os::unix::fs::symlink(&outside, &tricky).unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "committed tricky symlink"]);
std::fs::remove_file(&tricky).unwrap();
std::fs::create_dir_all(&tricky).unwrap();
let Err(err) = create_for_task(&tricky, &wt_dir, "task-escape-head", "Tricky", None) else {
panic!("expected committed symlink escaping worktree root to be rejected");
};
assert!(
err.to_string().contains("outside worktree") || err.to_string().contains("escapes worktree root"),
"unexpected error for committed symlink cwd: {err}"
);
// 2. Normal directory at creation time, later replaced with an escaping symlink before reuse,
// must be rejected by `verify_confined_worktree_cwd`!
let legit_sub = packages.join("legit");
std::fs::create_dir_all(&legit_sub).unwrap();
std::fs::write(legit_sub.join("ok.txt"), "ok\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "legit sub"]);
let created = create_for_task(&legit_sub, &wt_dir, "task-reuse", "Legit", None).unwrap();
let verified = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap();
assert!(verified.starts_with(dunce::canonicalize(&created.path).unwrap()));
std::fs::remove_dir_all(&created.cwd).unwrap();
std::os::unix::fs::symlink(&outside, &created.cwd).unwrap();
let reuse_err = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap_err();
assert!(
reuse_err.to_string().contains("outside worktree") || reuse_err.to_string().contains("escapes"),
"symlink swap on worktree reuse must be rejected: {reuse_err}"
);
}
}
+24
Переглянути файл
@@ -0,0 +1,24 @@
{
"version": 2,
"plugins": {
"evidence-plugin@evidence-mkt": [
{
"scope": "user",
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
"version": "1.2.3",
"installedAt": "2026-11-30T21:50:25.665Z",
"lastUpdated": "2026-11-30T21:50:25.665Z",
"gitCommitSha": "1111111111111111111111111111111111111111"
},
{
"scope": "project",
"projectPath": "$WORKSPACE",
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
"version": "1.2.3",
"installedAt": "2026-11-30T21:50:25.665Z",
"lastUpdated": "2026-11-30T21:50:25.665Z",
"gitCommitSha": "1111111111111111111111111111111111111111"
}
]
}
}
+6
Переглянути файл
@@ -0,0 +1,6 @@
[marketplaces.evidence-mkt]
source_type = "local"
source = "$HOME/.codex/.tmp/marketplaces/evidence-mkt"
[plugins."evidence-plugin@evidence-mkt"]
enabled = false
+19
Переглянути файл
@@ -0,0 +1,19 @@
// This file is managed automatically.
{
"installedPlugins": [
{
"name": "evidence-plugin",
"marketplace": "evidence-mkt",
"installed_at": "2026-11-30T21:50:25.665Z",
"enabled": true,
"version": "1.2.3",
"cache_path": "$HOME/.copilot/installed-plugins/evidence-mkt/evidence-plugin",
"source": {
"source": "github",
"repo": "acme/plugins",
"sha": "1111111111111111111111111111111111111111",
"path": "plugins/evidence-plugin"
}
}
]
}
+8
Переглянути файл
@@ -0,0 +1,8 @@
{
"evidence-extension": {
"overrides": [
"$HOME/*",
"!$WORKSPACE/*"
]
}
}
+2
Переглянути файл
@@ -99,6 +99,8 @@ pub enum IdeEvent {
WindowGroupsChanged,
/// A project was loaded or unloaded for the MCP server without a window of its own.
McpBackgroundProjectsChanged,
/// Agent automations, run history, or session schedules changed on the host.
AutomationsChanged,
/// A window entered or left full screen, itself or as a member of a full-screen window group.
WindowFullscreenChanged,
/// This remote window's connection ended or another window took over the session.
+114
Переглянути файл
@@ -170,6 +170,15 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentMemorySettings)]
pub memory: AgentMemorySettings,
/// Agent plugin bundle policies (`[agents.plugins]`): registered marketplaces and non-sensitive
/// config. Enablement lives in each harness's native config; capability consent is stored per machine.
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentPluginSettings)]
pub plugins: AgentPluginSettings,
/// Scheduled agent automations and headless scheduler host policies (`[agents.automations]`).
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentAutomationSettings)]
pub automations: AgentAutomationSettings,
}
impl Default for AgentSettings {
@@ -202,6 +211,8 @@ impl Default for AgentSettings {
mcp_servers: BTreeMap::new(),
skills: BTreeMap::new(),
memory: AgentMemorySettings::default(),
plugins: AgentPluginSettings::default(),
automations: AgentAutomationSettings::default(),
}
}
}
@@ -358,6 +369,96 @@ pub struct AgentMemorySettings {
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
}
/// One agent plugin bundle's policy in Settings › Agents › Plugins
/// (`[agents.plugins.entries."<harness>:<plugin>@<marketplace>"]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentPluginEntryPolicy {
/// Non-sensitive `userConfig` / `variables` key-value pairs; sensitive values live in OS Keychain.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub config: BTreeMap<String, String>,
}
/// Agent plugin bundle settings (`[agents.plugins]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentPluginSettings {
/// Registered plugin marketplaces (`owner/repo[#ref]`, GitHub URL, or local directory/manifest path).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub marketplaces: Vec<String>,
/// Per-plugin non-sensitive native option hints, keyed by `<harness>:<plugin>@<marketplace>`.
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
#[specta(type = BTreeMap<String, AgentPluginEntryPolicy>)]
pub entries: BTreeMap<String, AgentPluginEntryPolicy>,
}
/// When OpenIDEA holds an OS idle-sleep assertion during active automation turns.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AutomationPreventSleep {
/// Prevent idle sleep while plugged into AC power.
#[default]
Ac,
/// Prevent idle sleep whenever an automated turn is running.
Always,
/// Never hold an idle-sleep assertion.
Never,
}
/// What the scheduler does when one or more scheduled occurrences fell due while asleep or offline.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AutomationMisfirePolicy {
/// Coalesce all missed occurrences into at most one catch-up run once awake and online.
#[default]
RunOnce,
/// Skip missed occurrences and advance to the next future slot.
Skip,
}
/// Agent automation and headless scheduler settings (`[agents.automations]`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentAutomationSettings {
/// Automatically register the headless login/boot scheduler service while at least one
/// automation is enabled, and unregister it when none remain enabled.
pub auto_start_service: bool,
/// Keep the local OpenIDEA host alive in the background when windows close while local
/// automations are enabled.
pub keep_alive_in_background: bool,
/// Prevent system idle sleep while an automated turn is running.
#[serde(deserialize_with = "or_default")]
#[specta(type = AutomationPreventSleep)]
pub prevent_sleep: AutomationPreventSleep,
/// Default policy for scheduled occurrences missed during sleep, offline downtime, or reboot.
#[serde(deserialize_with = "or_default")]
#[specta(type = AutomationMisfirePolicy)]
pub misfire_policy: AutomationMisfirePolicy,
/// Keep `openidea-server --daemon` alive across disconnects while the remote host has
/// enabled scheduled automations.
pub keep_remote_daemon_alive: bool,
/// Automatically remove temporary automation worktrees when a run finishes with zero diff
/// and zero commits.
pub auto_clean_worktrees: bool,
/// Maximum retained non-clean automation worktrees per automation before pruning oldest
/// finished ones.
pub max_dirty_worktrees: u32,
}
impl Default for AgentAutomationSettings {
fn default() -> Self {
Self {
auto_start_service: false,
keep_alive_in_background: true,
prevent_sleep: AutomationPreventSleep::Ac,
misfire_policy: AutomationMisfirePolicy::RunOnce,
keep_remote_daemon_alive: true,
auto_clean_worktrees: true,
max_dirty_worktrees: 5,
}
}
}
/// A hand-edited value these settings don't know reads as the default, rather than
/// failing the whole settings file.
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
@@ -1509,6 +1610,9 @@ pub struct MarkdownSettings {
pub preview_layout: MarkdownPreviewLayout,
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
pub preview_font_size: Option<u32>,
/// Whether `.mdx` previews ask before running JSX components/imports, run automatically in
/// trusted projects, or stay in static safe mode.
pub mdx_execution: MdxExecutionPolicy,
/// "Detect commands that can be run right from Markdown files": gutter run icons on
/// shell code blocks and on command lines in code blocks.
pub run_commands: bool,
@@ -1521,12 +1625,22 @@ impl Default for MarkdownSettings {
Self {
preview_layout: MarkdownPreviewLayout::default(),
preview_font_size: None,
mdx_execution: MdxExecutionPolicy::default(),
run_commands: true,
command_directory: None,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MdxExecutionPolicy {
#[default]
Ask,
Trusted,
Off,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MarkdownPreviewLayout {
+2 -1
Переглянути файл
@@ -1796,7 +1796,8 @@ impl DebugManager {
let mut states = self.states.lock();
let Some(slot) = states.get_mut(path).and_then(|v| v.get_mut(index)) else { return false };
let next = session::state_from(bp, slot.line);
let next = BreakpointState { message: next.message.or_else(|| slot.message.clone()), ..next };
let kept = slot.message.clone().filter(|m| !(next.verified && m == session::UNBOUND_NATIVE));
let next = BreakpointState { message: next.message.or(kept), ..next };
let changed = *slot != next;
*slot = next;
changed
+8
Переглянути файл
@@ -293,6 +293,11 @@ impl Suspension {
/// symlinked path (`/tmp/game` while the editor has `/private/tmp/game`).
const RESOLVES_PATHS: &[&str] = &["godot"];
/// LLDB answers a breakpoint it can't bind yet with no reason: the code may simply not be loaded.
const NATIVE_ADAPTERS: &[&str] = &["lldb-dap", "codelldb"];
/// One literal: the UI looks it up in the text catalogs to translate it.
pub(crate) const UNBOUND_NATIVE: &str = "No loaded code at this line yet. If it stays unbound after its module loads, the debug info may record this file under another path (through a symlink, or /tmp for /private/tmp): set a source map from that path to this one";
impl Session {
#[allow(clippy::too_many_arguments)]
pub fn new(
@@ -514,6 +519,9 @@ impl Session {
ids.insert(id, (path.to_path_buf(), i));
}
states[i] = state_from(r, breakpoints[i].line);
if !states[i].verified && states[i].message.is_none() && NATIVE_ADAPTERS.contains(&self.adapter.as_str()) {
states[i].message = Some(UNBOUND_NATIVE.to_owned());
}
}
Ok(states)
}
+26 -1
Переглянути файл
@@ -138,6 +138,8 @@ struct Script {
output_after_terminate: bool,
/// Advertise `supportsTerminateRequest` (java-debug does not, so Stop signals the program).
supports_terminate: bool,
/// Answer `setBreakpoints` with unverified breakpoints and no reason (LLDB before the code loads).
unbound_breakpoints: bool,
/// Answer `setBreakpoints` only once this many are waiting (a client that waits for each never gets one).
hold_set_breakpoints: usize,
/// Send a `continued` event right after the first `stopped` one.
@@ -220,6 +222,7 @@ impl Default for Script {
fn default() -> Self {
Self {
run_in_terminal: None,
unbound_breakpoints: false,
start_debugging: false,
child_request: None,
ignore_configuration_done: false,
@@ -414,7 +417,7 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
.unwrap()
.iter()
.enumerate()
.map(|(i, b)| json!({"id": i + 1, "verified": true, "line": b["line"]}))
.map(|(i, b)| json!({"id": i + 1, "verified": !script.unbound_breakpoints, "line": b["line"]}))
.collect();
ok!(msg, json!({"breakpoints": bps}));
}
@@ -4041,6 +4044,28 @@ async fn stop_ends_a_native_program_a_run_started_for_the_debugger() {
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
}
/// LLDB leaves a breakpoint it can't bind unverified without a reason: say what may be wrong
/// (#6665 E1b: Xcode's debug info had `/tmp/…` for a project under `/private/tmp`).
#[tokio::test]
async fn an_unbound_native_breakpoint_says_why() {
for (adapter, hint) in [("lldb-dap", true), ("codelldb", true), ("debugpy", false)] {
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
h.start(LaunchConfig { adapter: adapter.into(), ..config() }).await.unwrap();
let path = PathBuf::from("/private/tmp/app/Counter.swift");
let states = h.manager.set_breakpoints(&h.owner.key, path, vec![bp(6)]).await.unwrap();
assert!(!states[0].verified);
assert_eq!(states[0].message.as_deref() == Some(crate::session::UNBOUND_NATIVE), hint, "{adapter}");
}
// Bound once the module loads (lldb-dap's `breakpoint` event has no message): the hint goes.
let path = PathBuf::from("/private/tmp/app/Counter.swift");
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
h.start(LaunchConfig { adapter: "lldb-dap".into(), ..config() }).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(6)]).await.unwrap();
assert!(h.manager.update_breakpoint_state(&path, 0, &json!({"id": 1, "verified": true, "line": 7})));
assert_eq!(h.manager.breakpoint_states(&path)[0].message, None);
}
#[tokio::test]
async fn cell_breakpoints_go_only_to_their_notebooks_kernel_session() {
use crate::jvm_memory::test_support::bare_session_of;
+18
Переглянути файл
@@ -111,6 +111,24 @@ impl AgentSecrets {
}
}
impl ide_agent::EnvSecrets for AgentSecrets {
fn get(&self, key: &str) -> Option<String> {
AgentSecrets::get(self, key)
}
fn set(&self, key: &str, value: &str) -> IdeResult<()> {
AgentSecrets::set(self, key, value).map(|_| ())
}
fn delete(&self, key: &str) {
AgentSecrets::delete(self, key);
}
fn keys(&self, prefix: &str) -> Vec<String> {
AgentSecrets::keys(self, prefix)
}
}
#[cfg(test)]
mod tests {
use super::*;
+775
Переглянути файл
@@ -0,0 +1,775 @@
//! Per-user OS login / boot service registration for `openidea-server --scheduler`
//! (or `<desktop-exe> --scheduler`).
//!
//! Off by default (`agents.automations.autoStartService = false`). When the user enables it
//! and at least one scheduled automation is active, registers the user login service; when
//! disabled or when zero scheduled automations remain (after any in-flight claimed runs finish),
//! stops and unregisters the service.
use ide_core::{IdeError, IdeResult, IpcPath};
use parking_lot::{Mutex, RwLock};
use std::path::{Path, PathBuf};
use std::sync::Arc;
pub const SERVICE_LABEL: &str = "ai.l0ng.openidea.scheduler";
pub const SYSTEMD_UNIT_NAME: &str = "openidea-scheduler.service";
const WINDOWS_SCRIPT_NAME: &str = "openidea-scheduler.cmd";
const OVERRIDE_ENV: &str = "OPENIDEA_BOOT_SERVICE_DIR";
const DISABLE_OS_CALLS_ENV: &str = "OPENIDEA_DISABLE_OS_SERVICE_CALLS";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ServicePlatform {
Macos,
Linux,
Windows,
Other,
}
impl ServicePlatform {
pub fn host() -> Self {
if cfg!(target_os = "macos") {
Self::Macos
} else if cfg!(target_os = "linux") {
Self::Linux
} else if cfg!(target_os = "windows") {
Self::Windows
} else {
Self::Other
}
}
}
pub type CommandRunner = Arc<dyn Fn(&str, &[&str]) -> std::io::Result<(i32, String, String)> + Send + Sync>;
#[derive(Default)]
pub struct BootServiceManager {
sync_lock: Mutex<()>,
override_dir: RwLock<Option<PathBuf>>,
executable_override: RwLock<Option<PathBuf>>,
platform_override: RwLock<Option<ServicePlatform>>,
command_runner: RwLock<Option<CommandRunner>>,
last_error: Mutex<Option<String>>,
}
#[derive(Clone, Debug)]
pub struct BootServiceState {
pub kind: String,
pub registered: bool,
pub path: Option<IpcPath>,
pub error: Option<String>,
pub linux_linger_enabled: Option<bool>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum OsServicePresence {
RegisteredAndActive,
RegisteredIdle,
ActiveUnregistered,
Absent,
}
impl OsServicePresence {
fn is_registered(self) -> bool {
matches!(self, Self::RegisteredAndActive | Self::RegisteredIdle)
}
fn is_loaded_or_active(self) -> bool {
!matches!(self, Self::Absent)
}
}
impl BootServiceManager {
pub fn with_override_dir(dir: Option<PathBuf>) -> Self {
Self {
sync_lock: Mutex::new(()),
override_dir: RwLock::new(dir),
executable_override: RwLock::new(None),
platform_override: RwLock::new(None),
command_runner: RwLock::new(None),
last_error: Mutex::new(None),
}
}
pub fn set_override_dir(&self, dir: Option<PathBuf>) {
*self.override_dir.write() = dir;
}
pub fn set_executable_override(&self, exe: Option<PathBuf>) {
*self.executable_override.write() = exe;
}
pub fn set_command_runner_for_test(&self, platform: ServicePlatform, runner: Option<CommandRunner>) {
*self.platform_override.write() = runner.as_ref().map(|_| platform);
*self.command_runner.write() = runner;
}
fn effective_platform(&self) -> ServicePlatform {
self.platform_override.read().unwrap_or_else(ServicePlatform::host)
}
fn effective_override_dir(&self) -> Option<PathBuf> {
self.override_dir
.read()
.clone()
.or_else(|| std::env::var_os(OVERRIDE_ENV).filter(|v| !v.is_empty()).map(PathBuf::from))
}
fn uses_os_commands(&self) -> bool {
if self.command_runner.read().is_some() {
return true;
}
self.effective_override_dir().is_none() && std::env::var_os(DISABLE_OS_CALLS_ENV).is_none_or(|v| v != "1")
}
fn run_command(&self, program: &str, args: &[&str]) -> IdeResult<(i32, String, String)> {
if let Some(runner) = self.command_runner.read().clone() {
return runner(program, args).map_err(|e| IdeError::internal(format!("{program} failed to spawn: {e}")));
}
let out = std::process::Command::new(program)
.args(args)
.output()
.map_err(|e| IdeError::internal(format!("{program} failed to spawn: {e}")))?;
let code = out.status.code().unwrap_or(-1);
let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
Ok((code, stdout, stderr))
}
fn run_checked(&self, program: &str, args: &[&str]) -> IdeResult<String> {
let (code, stdout, stderr) = self.run_command(program, args)?;
if code == 0 {
return Ok(stdout);
}
let detail = stderr.trim();
let msg = if detail.is_empty() { stdout.trim() } else { detail };
Err(IdeError::internal(format!("{program} {} exited with {code}: {msg}", args.join(" "))))
}
fn scheduler_executable(&self) -> Option<PathBuf> {
self.executable_override.read().clone().or_else(|| std::env::current_exe().ok())
}
pub fn service_kind_for(platform: ServicePlatform, remote: bool) -> &'static str {
if remote && platform == ServicePlatform::Linux {
"systemdUser"
} else {
match platform {
ServicePlatform::Macos => "launchAgent",
ServicePlatform::Linux => "systemdUser",
ServicePlatform::Windows => "windowsStartup",
ServicePlatform::Other => "backgroundHost",
}
}
}
pub fn service_kind(remote: bool) -> &'static str {
Self::service_kind_for(ServicePlatform::host(), remote)
}
pub fn service_file_path(&self, home_dir: Option<&Path>) -> Option<PathBuf> {
let platform = self.effective_platform();
if let Some(dir) = self.effective_override_dir() {
let filename = match platform {
ServicePlatform::Macos => format!("{SERVICE_LABEL}.plist"),
ServicePlatform::Windows => WINDOWS_SCRIPT_NAME.to_owned(),
ServicePlatform::Linux | ServicePlatform::Other => SYSTEMD_UNIT_NAME.to_owned(),
};
return Some(dir.join(filename));
}
let home = home_dir?;
match platform {
ServicePlatform::Macos => {
Some(home.join("Library").join("LaunchAgents").join(format!("{SERVICE_LABEL}.plist")))
}
ServicePlatform::Linux => Some(home.join(".config").join("systemd").join("user").join(SYSTEMD_UNIT_NAME)),
ServicePlatform::Windows => {
let appdata = std::env::var_os("APPDATA")
.map(PathBuf::from)
.unwrap_or_else(|| home.join("AppData").join("Roaming"));
Some(
appdata
.join("Microsoft")
.join("Windows")
.join("Start Menu")
.join("Programs")
.join("Startup")
.join(WINDOWS_SCRIPT_NAME),
)
}
ServicePlatform::Other => None,
}
}
fn macos_domain() -> String {
#[cfg(target_os = "macos")]
{
format!("gui/{}", rustix::process::getuid().as_raw())
}
#[cfg(not(target_os = "macos"))]
{
"gui/501".to_owned()
}
}
/// Queries the OS service manager, distinguishing confirmed `Absent` from `Err(...)` (unknown
/// status, e.g. D-Bus / launchd unreachable) so `sync(..., false)` never deletes the service
/// file when status cannot be determined.
fn query_os_presence(&self, platform: ServicePlatform) -> IdeResult<OsServicePresence> {
if !self.uses_os_commands() {
return Ok(OsServicePresence::Absent);
}
match platform {
ServicePlatform::Macos => {
let job = format!("{}/{SERVICE_LABEL}", Self::macos_domain());
let (code, stdout, stderr) = self.run_command("launchctl", &["print", &job])?;
if code == 0 {
return Ok(OsServicePresence::RegisteredAndActive);
}
let combined = format!("{stdout}\n{stderr}");
if code == 113 || combined.contains("Could not find service") {
return Ok(OsServicePresence::Absent);
}
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
Err(IdeError::internal(format!("launchctl print {job} returned unknown status {code}: {detail}")))
}
ServicePlatform::Linux => {
let (en_code, en_out, en_err) =
self.run_command("systemctl", &["--user", "is-enabled", SYSTEMD_UNIT_NAME])?;
let en_state = en_out.trim();
let enabled = if en_code == 0 && matches!(en_state, "enabled" | "enabled-runtime") {
true
} else if matches!(
en_state,
"disabled" | "not-found" | "static" | "indirect" | "masked" | "linked" | "generated"
) {
false
} else {
let detail = if en_err.trim().is_empty() { en_state } else { en_err.trim() };
return Err(IdeError::internal(format!(
"systemctl --user is-enabled {SYSTEMD_UNIT_NAME} returned unknown status {en_code}: {detail}"
)));
};
let (ac_code, ac_out, ac_err) =
self.run_command("systemctl", &["--user", "is-active", SYSTEMD_UNIT_NAME])?;
let ac_state = ac_out.trim();
let active = if ac_code == 0 && matches!(ac_state, "active" | "activating" | "reloading") {
true
} else if matches!(ac_state, "inactive" | "failed" | "deactivating") {
false
} else {
let detail = if ac_err.trim().is_empty() { ac_state } else { ac_err.trim() };
return Err(IdeError::internal(format!(
"systemctl --user is-active {SYSTEMD_UNIT_NAME} returned unknown status {ac_code}: {detail}"
)));
};
Ok(match (enabled, active) {
(true, true) => OsServicePresence::RegisteredAndActive,
(true, false) => OsServicePresence::RegisteredIdle,
(false, true) => OsServicePresence::ActiveUnregistered,
(false, false) => OsServicePresence::Absent,
})
}
ServicePlatform::Windows | ServicePlatform::Other => Ok(OsServicePresence::Absent),
}
}
fn is_os_registered(&self, platform: ServicePlatform, path: &Path) -> bool {
if !path.is_file() {
return false;
}
if !self.uses_os_commands() {
return true;
}
match platform {
ServicePlatform::Macos | ServicePlatform::Linux => {
self.query_os_presence(platform).is_ok_and(OsServicePresence::is_registered)
}
ServicePlatform::Windows => std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() > 0),
ServicePlatform::Other => false,
}
}
pub fn status(&self, home_dir: Option<&Path>, remote: bool) -> BootServiceState {
let platform = self.effective_platform();
let path = self.service_file_path(home_dir);
let registered = path.as_ref().is_some_and(|p| self.is_os_registered(platform, p));
let linux_linger_enabled = if platform == ServicePlatform::Linux { Some(check_linux_linger()) } else { None };
BootServiceState {
kind: Self::service_kind_for(platform, remote).to_owned(),
registered,
path: path.map(IpcPath),
error: self.last_error.lock().clone(),
linux_linger_enabled,
}
}
/// Synchronizes the OS user service file and service manager state to match
/// `(should_register, base_dir)`. Checks command results, retries activation even when the
/// unit/plist file on disk is unchanged, and stops + unloads the worker BEFORE deleting the
/// unit/plist file (keeping the file when status is unknown) so failed unregistrations retry.
pub fn sync(&self, home_dir: Option<&Path>, base_dir: &Path, should_register: bool) -> IdeResult<BootServiceState> {
let _guard = self.sync_lock.lock();
let result = self.sync_locked(home_dir, base_dir, should_register);
match &result {
Ok(_) => *self.last_error.lock() = None,
Err(err) => *self.last_error.lock() = Some(err.to_string()),
}
result
}
fn sync_locked(
&self,
home_dir: Option<&Path>,
base_dir: &Path,
should_register: bool,
) -> IdeResult<BootServiceState> {
let platform = self.effective_platform();
let Some(target) = self.service_file_path(home_dir) else {
return Ok(self.status(home_dir, false));
};
let use_os = self.uses_os_commands();
if should_register {
let exe = self
.scheduler_executable()
.ok_or_else(|| IdeError::unavailable("cannot locate OpenIDEA executable for --scheduler"))?;
let content = render_service_file_for(platform, &exe, base_dir)?;
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent)?;
}
let file_changed = std::fs::read_to_string(&target).ok().as_deref() != Some(content.as_str());
if file_changed {
ide_vfs::write_atomic(&target, content.as_bytes())?;
}
if use_os {
let already_registered = self.is_os_registered(platform, &target);
if file_changed || !already_registered {
self.activate_os_service(platform, &target)?;
}
}
} else {
if use_os {
// Propagate unknown status BEFORE touching `target` so the file stays for retry!
let presence = self.query_os_presence(platform)?;
if presence.is_loaded_or_active() || target.exists() {
self.deactivate_os_service(platform, presence)?;
}
}
if target.exists() {
match std::fs::remove_file(&target) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
}
}
Ok(BootServiceState {
kind: Self::service_kind_for(platform, false).to_owned(),
registered: self.is_os_registered(platform, &target),
path: Some(IpcPath(target)),
error: None,
linux_linger_enabled: if platform == ServicePlatform::Linux { Some(check_linux_linger()) } else { None },
})
}
fn activate_os_service(&self, platform: ServicePlatform, path: &Path) -> IdeResult<()> {
let path_str = path
.to_str()
.ok_or_else(|| IdeError::invalid(format!("service file path is not valid UTF-8: {}", path.display())))?;
match platform {
ServicePlatform::Macos => {
let domain = Self::macos_domain();
let job = format!("{domain}/{SERVICE_LABEL}");
if self.query_os_presence(platform).is_ok_and(OsServicePresence::is_loaded_or_active) {
let _ = self.run_command("launchctl", &["bootout", &job]);
}
self.run_checked("launchctl", &["bootstrap", &domain, path_str])?;
Ok(())
}
ServicePlatform::Linux => {
self.run_checked("systemctl", &["--user", "daemon-reload"])?;
self.run_checked("systemctl", &["--user", "enable", SYSTEMD_UNIT_NAME])?;
Ok(())
}
ServicePlatform::Windows | ServicePlatform::Other => Ok(()),
}
}
fn deactivate_os_service(&self, platform: ServicePlatform, presence: OsServicePresence) -> IdeResult<()> {
match platform {
ServicePlatform::Macos => {
let domain = Self::macos_domain();
let job = format!("{domain}/{SERVICE_LABEL}");
if presence.is_loaded_or_active() {
let (code, stdout, stderr) = self.run_command("launchctl", &["bootout", &job])?;
let after = self.query_os_presence(platform)?;
if code != 0 && after.is_loaded_or_active() {
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
return Err(IdeError::internal(format!(
"launchctl bootout {job} exited with {code}: {detail}"
)));
}
}
Ok(())
}
ServicePlatform::Linux => {
match presence {
OsServicePresence::RegisteredAndActive | OsServicePresence::RegisteredIdle => {
self.run_checked("systemctl", &["--user", "disable", "--now", SYSTEMD_UNIT_NAME])?;
}
OsServicePresence::ActiveUnregistered => {
self.run_checked("systemctl", &["--user", "stop", SYSTEMD_UNIT_NAME])?;
}
OsServicePresence::Absent => {}
}
self.run_checked("systemctl", &["--user", "daemon-reload"])?;
Ok(())
}
ServicePlatform::Windows | ServicePlatform::Other => Ok(()),
}
}
}
pub fn render_service_file(exe: &Path, base_dir: &Path) -> IdeResult<String> {
render_service_file_for(ServicePlatform::host(), exe, base_dir)
}
pub fn render_service_file_for(platform: ServicePlatform, exe: &Path, base_dir: &Path) -> IdeResult<String> {
match platform {
ServicePlatform::Macos => render_macos_plist(exe, base_dir),
ServicePlatform::Windows => render_windows_cmd(exe, base_dir),
ServicePlatform::Linux | ServicePlatform::Other => render_systemd_unit(exe, base_dir),
}
}
fn validate_roundtrip_path<'a>(path: &'a Path, label: &str) -> IdeResult<&'a str> {
let s = path.to_str().ok_or_else(|| IdeError::invalid(format!("{label} path is not valid UTF-8")))?;
if s.is_empty() {
return Err(IdeError::invalid(format!("{label} path cannot be empty")));
}
let has_root = path.is_absolute() || s.starts_with('/') || (s.len() >= 3 && s.as_bytes()[1] == b':');
if !has_root {
return Err(IdeError::invalid(format!("{label} path must be absolute: {s}")));
}
if s.chars().any(char::is_control) {
return Err(IdeError::invalid(format!(
"{label} path contains control characters or line breaks that cannot round-trip in a service file"
)));
}
Ok(s)
}
pub fn render_macos_plist(exe: &Path, base_dir: &Path) -> IdeResult<String> {
let exe_str = validate_roundtrip_path(exe, "scheduler executable")?;
let home_str = validate_roundtrip_path(base_dir, "scheduler data")?;
let log_path = base_dir.join("logs").join("scheduler.log");
let log_str = validate_roundtrip_path(&log_path, "scheduler log")?;
let exe_esc = xml_escape(exe_str);
let home_esc = xml_escape(home_str);
let log_esc = xml_escape(log_str);
Ok(format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>{SERVICE_LABEL}</string>
<key>AssociatedBundleIdentifiers</key>
<array>
<string>ai.l0ng.openidea</string>
</array>
<key>LimitLoadToSessionType</key>
<string>Aqua</string>
<key>ProgramArguments</key>
<array>
<string>{exe_esc}</string>
<string>--scheduler</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>OPENIDEA_SERVER_HOME</key>
<string>{home_esc}</string>
</dict>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>{log_esc}</string>
</dict>
</plist>
"#
))
}
pub fn render_systemd_unit(exe: &Path, base_dir: &Path) -> IdeResult<String> {
let exe_raw = validate_roundtrip_path(exe, "scheduler executable")?;
let home_raw = validate_roundtrip_path(base_dir, "scheduler data")?;
// Both `Environment=` and the executable path (`argv[0]`) of `ExecStart=` are resolved before
// `$` variable expansion (`systemd.exec(5)`, `systemd.service(5)`), so `$` stays literal!
let exe_str = systemd_escape_literal_quoted(exe_raw);
let home_str = systemd_escape_literal_quoted(home_raw);
Ok(format!(
"[Unit]\n\
Description=OpenIDEA Headless Agent Automation Scheduler\n\
After=network-online.target\n\
\n\
[Service]\n\
Type=simple\n\
Environment=\"OPENIDEA_SERVER_HOME={home_str}\"\n\
ExecStart=\"{exe_str}\" --scheduler\n\
Restart=on-failure\n\
RestartSec=10\n\
\n\
[Install]\n\
WantedBy=default.target\n"
))
}
pub fn render_windows_cmd(exe: &Path, base_dir: &Path) -> IdeResult<String> {
let exe_raw = validate_roundtrip_path(exe, "scheduler executable")?;
let home_raw = validate_roundtrip_path(base_dir, "scheduler data")?;
if exe_raw.contains('"') || home_raw.contains('"') {
return Err(IdeError::invalid("Windows Startup script path cannot contain '\"'"));
}
let home_esc = cmd_escape(home_raw);
let exe_esc = cmd_escape(exe_raw);
Ok(format!("@echo off\r\nset \"OPENIDEA_SERVER_HOME={home_esc}\"\r\nstart \"\" /B \"{exe_esc}\" --scheduler\r\n"))
}
/// Escapes a double-quoted systemd value where `$` is literal (`Environment="KEY=VALUE"` and
/// `ExecStart="EXECUTABLE"` `argv[0]`): specifiers (`%` -> `%%`) and C escapes (`\` -> `\\`,
/// `"` -> `\"`) are interpreted, while `$` must remain literal.
fn systemd_escape_literal_quoted(s: &str) -> String {
s.replace('\\', "\\\\").replace('"', "\\\"").replace('%', "%%")
}
fn cmd_escape(s: &str) -> String {
s.replace('%', "%%")
}
fn xml_escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace('\'', "&apos;")
}
fn check_linux_linger() -> bool {
if let Ok(user) = std::env::var("USER").or_else(|_| std::env::var("LOGNAME"))
&& !user.is_empty()
&& Path::new("/var/lib/systemd/linger").join(user).exists()
{
return true;
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
fn unescape_systemd_quoted(s: &str, expand_dollars: bool) -> String {
let after_specifiers = s.replace("%%", "%");
let after_dollars = if expand_dollars { after_specifiers.replace("$$", "$") } else { after_specifiers };
let mut out = String::new();
let mut chars = after_dollars.chars();
while let Some(c) = chars.next() {
if c == '\\' {
if let Some(next) = chars.next() {
out.push(next);
}
} else {
out.push(c);
}
}
out
}
#[test]
fn systemd_unit_encodes_environment_and_exec_start_with_distinct_rules_and_rejects_bad_paths() {
let exe = Path::new("/opt/openidea$bin/with \"quotes\"\\slash/open%idea");
let home = Path::new("/home/dev&co/100%data$dir/\"sub\"\\path");
let plist = render_macos_plist(exe, home).unwrap();
assert!(plist.contains("dev&amp;co"));
let unit = render_systemd_unit(exe, home).unwrap();
let env_line = unit.lines().find(|l| l.starts_with("Environment=")).unwrap();
let exec_line = unit.lines().find(|l| l.starts_with("ExecStart=")).unwrap();
// Both Environment= and ExecStart= argv[0] keep `$` literal while escaping `\`, `"`, and `%`.
assert!(env_line.contains("100%%data$dir"));
assert!(!env_line.contains("data$$dir"));
let env_inner =
env_line.strip_prefix("Environment=\"OPENIDEA_SERVER_HOME=").unwrap().strip_suffix('"').unwrap();
assert_eq!(unescape_systemd_quoted(env_inner, false), home.to_str().unwrap());
assert!(exec_line.contains("openidea$bin"));
assert!(!exec_line.contains("openidea$$bin"));
assert!(exec_line.contains("open%%idea"));
let exec_inner = exec_line.strip_prefix("ExecStart=\"").unwrap().strip_suffix("\" --scheduler").unwrap();
assert_eq!(unescape_systemd_quoted(exec_inner, false), exe.to_str().unwrap());
// Windows .cmd rejects embedded quotes and round-trips `%` and `$`.
assert!(render_windows_cmd(exe, home).is_err());
let win_ok = render_windows_cmd(
Path::new(r"C:\Program Files\OpenIDEA\open%idea$1.exe"),
Path::new(r"C:\Users\dev&co\100%data$dir"),
)
.unwrap();
assert!(win_ok.contains("100%%data$dir"));
assert!(win_ok.contains("open%%idea$1.exe"));
// Line breaks, NULs, and relative paths are rejected across all platforms.
assert!(render_systemd_unit(Path::new("/opt/openidea\nExecStart=/bin/sh"), home).is_err());
assert!(render_systemd_unit(exe, Path::new("/home/user\r\nBad=1")).is_err());
assert!(render_systemd_unit(Path::new("relative/openidea"), home).is_err());
assert!(render_macos_plist(Path::new("/Applications/OpenIDEA\nBad"), home).is_err());
}
#[cfg(unix)]
#[test]
fn systemd_unit_rejects_non_utf8_paths() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let bad = Path::new(OsStr::from_bytes(b"/tmp/openidea-\xff"));
assert!(render_systemd_unit(bad, Path::new("/tmp/home")).is_err());
}
#[test]
fn boot_service_checks_real_registration_retries_unchanged_file_and_stops_on_disable() {
let tmp = tempfile::tempdir().unwrap();
let mgr = BootServiceManager::with_override_dir(Some(tmp.path().join("units")));
mgr.set_executable_override(Some(PathBuf::from("/usr/local/bin/openidea-server")));
let enabled = Arc::new(AtomicBool::new(false));
let active = Arc::new(AtomicBool::new(false));
let fail_next_enable = Arc::new(AtomicBool::new(true));
let fail_next_disable = Arc::new(AtomicBool::new(true));
let disable_now_calls = Arc::new(AtomicUsize::new(0));
let enabled_c = enabled.clone();
let active_c = active.clone();
let fail_en_c = fail_next_enable.clone();
let fail_dis_c = fail_next_disable.clone();
let dis_calls_c = disable_now_calls.clone();
mgr.set_command_runner_for_test(
ServicePlatform::Linux,
Some(Arc::new(move |prog, args| {
assert_eq!(prog, "systemctl");
match args {
["--user", "is-enabled", u] if *u == SYSTEMD_UNIT_NAME => {
if enabled_c.load(Ordering::Acquire) {
Ok((0, "enabled\n".into(), String::new()))
} else {
Ok((1, "disabled\n".into(), String::new()))
}
}
["--user", "is-active", u] if *u == SYSTEMD_UNIT_NAME => {
if active_c.load(Ordering::Acquire) {
Ok((0, "active\n".into(), String::new()))
} else {
Ok((3, "inactive\n".into(), String::new()))
}
}
["--user", "daemon-reload"] => Ok((0, String::new(), String::new())),
["--user", "enable", u] if *u == SYSTEMD_UNIT_NAME => {
if fail_en_c.swap(false, Ordering::AcqRel) {
Ok((1, String::new(), "dbus unavailable".into()))
} else {
enabled_c.store(true, Ordering::Release);
active_c.store(true, Ordering::Release);
Ok((0, String::new(), String::new()))
}
}
["--user", "disable", "--now", u] if *u == SYSTEMD_UNIT_NAME => {
dis_calls_c.fetch_add(1, Ordering::AcqRel);
if fail_dis_c.swap(false, Ordering::AcqRel) {
Ok((1, String::new(), "unit busy".into()))
} else {
enabled_c.store(false, Ordering::Release);
active_c.store(false, Ordering::Release);
Ok((0, String::new(), String::new()))
}
}
other => panic!("unexpected systemctl args: {other:?}"),
}
})),
);
let home = tmp.path();
let data = tmp.path().join("data");
std::fs::create_dir_all(&data).unwrap();
// 1. First sync writes the unit file, `systemctl enable` fails -> returns Err and status is NOT registered
// even though the unit file already exists on disk!
assert!(mgr.sync(Some(home), &data, true).is_err());
let st_failed = mgr.status(Some(home), true);
assert!(!st_failed.registered, "file exists alone must not report registered when systemctl failed");
assert!(st_failed.error.as_deref().unwrap_or_default().contains("dbus unavailable"));
// 2. Second sync with identical parameters (unchanged file on disk!) retries `systemctl enable` and succeeds.
let st_ok = mgr.sync(Some(home), &data, true).unwrap();
assert!(st_ok.registered);
assert!(st_ok.error.is_none());
// 3. Disabling when `systemctl disable --now` fails preserves the unit file and retryability.
assert!(mgr.sync(Some(home), &data, false).is_err());
assert!(mgr.service_file_path(Some(home)).unwrap().is_file(), "unit file kept so unregister can retry");
assert!(mgr.status(Some(home), true).registered);
// 4. Retrying disable runs `systemctl --user disable --now` (stopping the worker), removes the file, and clears status.
let st_off = mgr.sync(Some(home), &data, false).unwrap();
assert!(!st_off.registered);
assert!(!active.load(Ordering::Acquire), "running worker stopped on disable");
assert_eq!(disable_now_calls.load(Ordering::Acquire), 2);
assert!(!mgr.service_file_path(Some(home)).unwrap().exists());
// 5. Unknown OS query status (e.g. D-Bus unreachable) MUST NOT treat worker as absent or delete unit file!
let status_unknown = Arc::new(AtomicBool::new(false));
let status_unknown_c = status_unknown.clone();
let macos_loaded = Arc::new(AtomicBool::new(false));
let macos_loaded_c = macos_loaded.clone();
mgr.set_command_runner_for_test(
ServicePlatform::Macos,
Some(Arc::new(move |prog, args| {
assert_eq!(prog, "launchctl");
match args {
["print", _] => {
if status_unknown_c.load(Ordering::Acquire) {
Ok((1, String::new(), "IPC transport error".into()))
} else if macos_loaded_c.load(Ordering::Acquire) {
Ok((0, "state = running\n".into(), String::new()))
} else {
Ok((113, String::new(), "Could not find service\n".into()))
}
}
["bootstrap", _, _] => {
macos_loaded_c.store(true, Ordering::Release);
Ok((0, String::new(), String::new()))
}
["bootout", _] => {
macos_loaded_c.store(false, Ordering::Release);
Ok((0, String::new(), String::new()))
}
other => panic!("unexpected launchctl args: {other:?}"),
}
})),
);
mgr.sync(Some(home), &data, true).unwrap();
let plist_path = mgr.service_file_path(Some(home)).unwrap();
assert!(plist_path.is_file());
// Simulate transient launchd query failure on disable -> keeps plist file on disk for retry!
status_unknown.store(true, Ordering::Release);
assert!(mgr.sync(Some(home), &data, false).is_err());
assert!(plist_path.is_file(), "plist must be preserved when OS status is unknown");
assert!(macos_loaded.load(Ordering::Acquire));
// Restore launchd query -> retry succeeds, unloads worker, and deletes plist!
status_unknown.store(false, Ordering::Release);
mgr.sync(Some(home), &data, false).unwrap();
assert!(!macos_loaded.load(Ordering::Acquire));
assert!(!plist_path.exists());
}
}
File diff suppressed because it is too large. Load diff
+577
Переглянути файл
@@ -0,0 +1,577 @@
//! Cross-process owner locks, abandonment detection, and authenticated loopback RPC bridge
//! so live runs owned by `openidea --scheduler` (or `ChatOnly` / headless `AgentManager`s)
//! stream `AgentEvent`s to open windows and accept permission approvals (`agent_respond`,
//! `agent_answer_question`, `agent_cancel`, `agent_entries`, etc.).
use ide_agent::{AgentEntry, AgentEvent, AgentManager, AgentPrompt, AgentTask};
use ide_core::{CancellationToken, IdeError, IdeResult};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::broadcast;
const OWNERS_DIR: &str = "owners";
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OwnerEndpoint {
pub instance_id: String,
pub pid: u32,
pub addr: String,
pub token: String,
}
#[derive(Clone, Debug)]
pub struct RoutedAgentEvent {
pub project_root: Option<PathBuf>,
pub event: AgentEvent,
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "camelCase", rename_all_fields = "camelCase")]
enum PeerRequest {
Subscribe { token: String, allowed_roots: Vec<PathBuf>, include_chat_only: bool },
Entries { token: String, task: String, subagent: Option<String> },
Respond { token: String, task: String, permission: u32, option: Option<String> },
AnswerQuestion { token: String, task: String, question: String, answer: Option<String> },
Cancel { token: String, task: String, subagent: Option<String> },
StopBackground { token: String, task: String, background: String },
Prompt { token: String, task: String, prompt: AgentPrompt, now: bool },
StopIdleWorker { token: String },
}
pub type ResolveManagerFn = Arc<dyn Fn(&str) -> Option<Arc<AgentManager>> + Send + Sync>;
pub type ListLiveTasksFn = Arc<dyn Fn(&[PathBuf], bool) -> Vec<AgentTask> + Send + Sync>;
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
enum PeerStreamItem {
Snapshot { tasks: Vec<AgentTask> },
Event { event: Box<AgentEvent> },
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "camelCase")]
enum PeerReply<T> {
Ok { value: T },
Err { error: String },
}
pub fn owners_dir(automations_dir: &Path) -> PathBuf {
automations_dir.join(OWNERS_DIR)
}
/// Checks whether `owner_id` holds an active OS lock in `automations_dir/owners/`.
/// If the lock can be acquired immediately, that process has exited/crashed and its stale
/// lock/endpoint files are cleaned up.
pub fn is_owner_alive(automations_dir: &Path, self_instance_id: &str, owner_id: &str) -> bool {
if owner_id.is_empty() {
return false;
}
if owner_id == self_instance_id {
return true;
}
let dir = owners_dir(automations_dir);
let lock_path = dir.join(format!("{owner_id}.lock"));
let Ok(file) = std::fs::OpenOptions::new().read(true).write(true).open(&lock_path) else {
return false;
};
if file.try_lock().is_ok() {
let _ = file.unlock();
drop(file);
let _ = std::fs::remove_file(&lock_path);
let _ = std::fs::remove_file(dir.join(format!("{owner_id}.json")));
false
} else {
true
}
}
pub fn read_live_endpoint(automations_dir: &Path, self_instance_id: &str, owner_id: &str) -> Option<OwnerEndpoint> {
if !is_owner_alive(automations_dir, self_instance_id, owner_id) {
return None;
}
let path = owners_dir(automations_dir).join(format!("{owner_id}.json"));
let bytes = std::fs::read(path).ok()?;
serde_json::from_slice(&bytes).ok()
}
pub fn list_live_peer_endpoints(automations_dir: &Path, self_instance_id: &str) -> Vec<OwnerEndpoint> {
let dir = owners_dir(automations_dir);
let Ok(entries) = std::fs::read_dir(&dir) else {
return Vec::new();
};
let mut out = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
if path.extension().is_none_or(|e| e != "json") {
continue;
}
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
if stem == self_instance_id {
continue;
}
if let Some(ep) = read_live_endpoint(automations_dir, self_instance_id, stem) {
out.push(ep);
}
}
out
}
pub struct OwnerNode {
pub instance_id: String,
lock_file: Mutex<Option<std::fs::File>>,
endpoint_path: Mutex<Option<PathBuf>>,
pub events_tx: broadcast::Sender<RoutedAgentEvent>,
worker_stop_requested: std::sync::atomic::AtomicBool,
subscriptions: Mutex<HashMap<String, CancellationToken>>,
}
impl OwnerNode {
pub fn new(instance_id: String) -> Self {
let (events_tx, _) = broadcast::channel(512);
Self {
instance_id,
lock_file: Mutex::new(None),
endpoint_path: Mutex::new(None),
events_tx,
worker_stop_requested: std::sync::atomic::AtomicBool::new(false),
subscriptions: Mutex::new(HashMap::new()),
}
}
pub fn worker_stop_requested(&self) -> bool {
self.worker_stop_requested.load(std::sync::atomic::Ordering::Acquire)
}
/// Acquires `owners/<instance_id>.lock` (idempotent) so any peer can tell this process is alive.
pub fn ensure_lock(&self, automations_dir: &Path) -> IdeResult<()> {
let mut guard = self.lock_file.lock();
if guard.is_some() {
return Ok(());
}
let dir = owners_dir(automations_dir);
std::fs::create_dir_all(&dir)?;
let lock_path = dir.join(format!("{}.lock", self.instance_id));
let file = std::fs::OpenOptions::new().create(true).read(true).write(true).truncate(false).open(&lock_path)?;
file.try_lock()
.map_err(|e| IdeError::internal(format!("cannot acquire owner lock {}: {e}", lock_path.display())))?;
*guard = Some(file);
Ok(())
}
/// Starts the authenticated loopback RPC server for live run events and approvals.
pub fn start_server(
&self,
automations_dir: &Path,
runtime: &tokio::runtime::Handle,
shutdown: CancellationToken,
resolve_mgr: ResolveManagerFn,
list_live_tasks: ListLiveTasksFn,
node_ref: Arc<OwnerNode>,
) {
if self.ensure_lock(automations_dir).is_err() {
return;
}
if self.endpoint_path.lock().is_some() {
return;
}
let dir = owners_dir(automations_dir);
let token = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
let Ok(std_listener) = std::net::TcpListener::bind("127.0.0.1:0") else {
return;
};
if std_listener.set_nonblocking(true).is_err() {
return;
}
let Ok(local_addr) = std_listener.local_addr() else {
return;
};
let instance_id = self.instance_id.clone();
let json_path = dir.join(format!("{instance_id}.json"));
let ep = OwnerEndpoint {
instance_id: instance_id.clone(),
pid: std::process::id(),
addr: local_addr.to_string(),
token: token.clone(),
};
if let Ok(bytes) = serde_json::to_vec_pretty(&ep) {
let _ = write_private_file(&json_path, &bytes);
}
*self.endpoint_path.lock() = Some(json_path.clone());
runtime.spawn(async move {
let Ok(listener) = TcpListener::from_std(std_listener) else {
let _ = std::fs::remove_file(&json_path);
return;
};
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
accepted = listener.accept() => {
let Ok((stream, _)) = accepted else { continue };
let token_c = token.clone();
let resolve_c = resolve_mgr.clone();
let list_c = list_live_tasks.clone();
let shutdown_c = shutdown.clone();
let node_c = node_ref.clone();
tokio::spawn(async move {
handle_peer_conn(stream, token_c, resolve_c, list_c, shutdown_c, node_c).await;
});
}
}
}
let _ = std::fs::remove_file(&json_path);
});
}
pub fn stop(&self, automations_dir: &Path) {
for (_, cancel) in self.subscriptions.lock().drain() {
cancel.cancel();
}
if let Some(ep_path) = self.endpoint_path.lock().take() {
let _ = std::fs::remove_file(ep_path);
}
if let Some(file) = self.lock_file.lock().take() {
let _ = file.unlock();
}
let _ = std::fs::remove_file(owners_dir(automations_dir).join(format!("{}.lock", self.instance_id)));
}
pub fn replace_subscriber(&self, subscriber: &str) -> CancellationToken {
let token = CancellationToken::new();
if let Some(prev) = self.subscriptions.lock().insert(subscriber.to_owned(), token.clone()) {
prev.cancel();
}
token
}
pub fn unsubscribe(&self, subscriber: &str) {
if let Some(prev) = self.subscriptions.lock().remove(subscriber) {
prev.cancel();
}
}
}
fn write_private_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
#[cfg(unix)]
{
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let mut f = std::fs::OpenOptions::new().create(true).write(true).truncate(true).mode(0o600).open(path)?;
f.write_all(bytes)?;
f.sync_all()
}
#[cfg(not(unix))]
{
std::fs::write(path, bytes)
}
}
async fn handle_peer_conn(
stream: TcpStream,
expected_token: String,
resolve_mgr: ResolveManagerFn,
list_live_tasks: ListLiveTasksFn,
shutdown: CancellationToken,
node: Arc<OwnerNode>,
) {
let (reader, mut writer) = stream.into_split();
let mut lines = BufReader::new(reader).lines();
let Ok(Some(first_line)) = lines.next_line().await else {
return;
};
let Ok(req) = serde_json::from_str::<PeerRequest>(&first_line) else {
return;
};
let req_token = match &req {
PeerRequest::Subscribe { token, .. }
| PeerRequest::Entries { token, .. }
| PeerRequest::Respond { token, .. }
| PeerRequest::AnswerQuestion { token, .. }
| PeerRequest::Cancel { token, .. }
| PeerRequest::StopBackground { token, .. }
| PeerRequest::Prompt { token, .. }
| PeerRequest::StopIdleWorker { token } => token,
};
if req_token != &expected_token {
let _ = write_json_line(&mut writer, &PeerReply::<()>::err("unauthorized")).await;
return;
}
match req {
PeerRequest::Subscribe { allowed_roots, include_chat_only, .. } => {
let mut rx = node.events_tx.subscribe();
let canon_allowed: Vec<PathBuf> =
allowed_roots.into_iter().map(|p| dunce::canonicalize(&p).unwrap_or(p)).collect();
let initial = list_live_tasks(&canon_allowed, include_chat_only);
if write_json_line(&mut writer, &PeerStreamItem::Snapshot { tasks: initial }).await.is_err() {
return;
}
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
recv = rx.recv() => {
match recv {
Ok(routed) => {
let matches = match &routed.project_root {
None => include_chat_only,
Some(actual) => {
let cand = dunce::canonicalize(actual).unwrap_or_else(|_| actual.clone());
canon_allowed.iter().any(|w| w == &cand)
}
};
if matches
&& write_json_line(
&mut writer,
&PeerStreamItem::Event { event: Box::new(routed.event) },
)
.await
.is_err()
{
break;
}
}
Err(broadcast::error::RecvError::Lagged(_)) => continue,
Err(broadcast::error::RecvError::Closed) => break,
}
}
}
}
}
PeerRequest::Entries { task, subagent, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => tokio::task::spawn_blocking(move || mgr.entries(&task, subagent))
.await
.map_err(|e| IdeError::internal(e.to_string()))
.and_then(|r| r),
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::Respond { task, permission, option, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.respond(&task, permission, option),
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::AnswerQuestion { task, question, answer, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.answer_question(&task, &question, answer).await,
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::Cancel { task, subagent, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.cancel(&task, subagent),
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::StopBackground { task, background, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.stop_background(&task, &background).await,
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::Prompt { task, prompt, now, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.prompt(&task, prompt, now).await,
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::StopIdleWorker { .. } => {
node.worker_stop_requested.store(true, std::sync::atomic::Ordering::Release);
let _ = write_json_line(&mut writer, &PeerReply::from_res(Ok(()))).await;
}
}
}
impl<T> PeerReply<T> {
fn from_res(res: IdeResult<T>) -> Self {
match res {
Ok(value) => Self::Ok { value },
Err(e) => Self::Err { error: e.to_string() },
}
}
fn err(msg: &str) -> Self {
Self::Err { error: msg.to_owned() }
}
}
async fn write_json_line<W: AsyncWriteExt + Unpin, T: Serialize>(writer: &mut W, msg: &T) -> std::io::Result<()> {
let mut line = serde_json::to_vec(msg).map_err(std::io::Error::other)?;
line.push(b'\n');
writer.write_all(&line).await?;
writer.flush().await
}
async fn call_peer<T: for<'de> Deserialize<'de>>(ep: &OwnerEndpoint, req: &PeerRequest) -> IdeResult<T> {
let mut stream = TcpStream::connect(&ep.addr)
.await
.map_err(|e| IdeError::unavailable(format!("cannot reach live automation worker at {}: {e}", ep.addr)))?;
write_json_line(&mut stream, req)
.await
.map_err(|e| IdeError::unavailable(format!("failed sending request to automation worker: {e}")))?;
let mut lines = BufReader::new(stream).lines();
let raw = lines
.next_line()
.await
.map_err(|e| IdeError::unavailable(format!("failed reading automation worker reply: {e}")))?
.ok_or_else(|| IdeError::unavailable("automation worker closed connection without replying"))?;
match serde_json::from_str::<PeerReply<T>>(&raw).map_err(|e| IdeError::internal(e.to_string()))? {
PeerReply::Ok { value } => Ok(value),
PeerReply::Err { error } => Err(IdeError::internal(error)),
}
}
fn call_peer_sync<T: for<'de> Deserialize<'de>>(ep: &OwnerEndpoint, req: &PeerRequest) -> IdeResult<T> {
use std::io::{BufRead, Write};
let addr: std::net::SocketAddr = ep
.addr
.parse()
.map_err(|e| IdeError::internal(format!("invalid automation worker address {}: {e}", ep.addr)))?;
let mut stream = std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_secs(3))
.map_err(|e| IdeError::unavailable(format!("cannot reach live automation worker at {}: {e}", ep.addr)))?;
let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(5)));
let _ = stream.set_write_timeout(Some(std::time::Duration::from_secs(5)));
let mut line = serde_json::to_vec(req).map_err(|e| IdeError::internal(e.to_string()))?;
line.push(b'\n');
stream
.write_all(&line)
.and_then(|()| stream.flush())
.map_err(|e| IdeError::unavailable(format!("failed sending request to automation worker: {e}")))?;
let mut reader = std::io::BufReader::new(stream);
let mut raw = String::new();
reader
.read_line(&mut raw)
.map_err(|e| IdeError::unavailable(format!("failed reading automation worker reply: {e}")))?;
if raw.trim().is_empty() {
return Err(IdeError::unavailable("automation worker closed connection without replying"));
}
match serde_json::from_str::<PeerReply<T>>(&raw).map_err(|e| IdeError::internal(e.to_string()))? {
PeerReply::Ok { value } => Ok(value),
PeerReply::Err { error } => Err(IdeError::internal(error)),
}
}
pub async fn peer_entries(ep: &OwnerEndpoint, task: String, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
call_peer(ep, &PeerRequest::Entries { token: ep.token.clone(), task, subagent }).await
}
pub fn peer_respond(
_runtime: &tokio::runtime::Handle,
ep: OwnerEndpoint,
task: String,
permission: u32,
option: Option<String>,
) -> IdeResult<()> {
let token = ep.token.clone();
call_peer_sync(&ep, &PeerRequest::Respond { token, task, permission, option })
}
pub async fn peer_answer_question(
ep: &OwnerEndpoint,
task: String,
question: String,
answer: Option<String>,
) -> IdeResult<()> {
call_peer(ep, &PeerRequest::AnswerQuestion { token: ep.token.clone(), task, question, answer }).await
}
pub fn peer_cancel(
_runtime: &tokio::runtime::Handle,
ep: OwnerEndpoint,
task: String,
subagent: Option<String>,
) -> IdeResult<()> {
let token = ep.token.clone();
call_peer_sync(&ep, &PeerRequest::Cancel { token, task, subagent })
}
pub async fn peer_stop_background(ep: &OwnerEndpoint, task: String, background: String) -> IdeResult<()> {
call_peer(ep, &PeerRequest::StopBackground { token: ep.token.clone(), task, background }).await
}
pub async fn peer_prompt(ep: &OwnerEndpoint, task: String, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
call_peer(ep, &PeerRequest::Prompt { token: ep.token.clone(), task, prompt, now }).await
}
pub fn notify_peers_stop_if_headless(runtime: &tokio::runtime::Handle, endpoints: Vec<OwnerEndpoint>) {
for ep in endpoints {
runtime.spawn(async move {
let token = ep.token.clone();
let _: IdeResult<()> = call_peer(&ep, &PeerRequest::StopIdleWorker { token }).await;
});
}
}
/// Connects to `ep`, fetches its initial live task snapshot synchronously (with a short timeout),
/// and spawns an async forwarder streaming subsequent `AgentEvent`s until `cancel` triggers.
pub fn attach_peer_stream(
runtime: &tokio::runtime::Handle,
ep: OwnerEndpoint,
allowed_roots: Vec<PathBuf>,
include_chat_only: bool,
cancel: CancellationToken,
on_event: Arc<dyn Fn(AgentEvent) + Send + Sync>,
) -> Vec<AgentTask> {
let (snap_tx, snap_rx) = std::sync::mpsc::channel();
runtime.spawn(async move {
let connect_fut = TcpStream::connect(&ep.addr);
let Ok(Ok(mut stream)) = tokio::time::timeout(std::time::Duration::from_secs(2), connect_fut).await else {
let _ = snap_tx.send(Vec::new());
return;
};
let req = PeerRequest::Subscribe { token: ep.token.clone(), allowed_roots, include_chat_only };
if write_json_line(&mut stream, &req).await.is_err() {
let _ = snap_tx.send(Vec::new());
return;
}
let mut lines = BufReader::new(stream).lines();
match tokio::time::timeout(std::time::Duration::from_secs(2), lines.next_line()).await {
Ok(Ok(Some(first))) => match serde_json::from_str::<PeerStreamItem>(&first) {
Ok(PeerStreamItem::Snapshot { tasks }) => {
let _ = snap_tx.send(tasks);
}
_ => {
let _ = snap_tx.send(Vec::new());
return;
}
},
_ => {
let _ = snap_tx.send(Vec::new());
return;
}
}
loop {
tokio::select! {
_ = cancel.cancelled() => break,
next = lines.next_line() => {
match next {
Ok(Some(line)) => {
if let Ok(PeerStreamItem::Event { event }) = serde_json::from_str::<PeerStreamItem>(&line) {
on_event(*event);
}
}
_ => break,
}
}
}
}
});
snap_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap_or_default()
}
+61
Переглянути файл
@@ -18,6 +18,7 @@ use std::sync::{Arc, OnceLock};
enum Mode {
Stdio,
Scheduler,
#[cfg(unix)]
Daemon(PathBuf, ide_host::daemon::BuildId),
}
@@ -29,6 +30,7 @@ usage:
openidea-server --web [options] [<project>]
openidea-server --stdio
openidea-server --attach <project-path>
openidea-server --scheduler
openidea-server --mcp-stdio [--project <path>]
openidea-server --connect <host> <port>
openidea-server --version
@@ -233,6 +235,7 @@ fn main() {
}
#[cfg(not(unix))]
[flag, _] if flag == "--attach" => Mode::Stdio,
_ if args.iter().any(|a| a == "--scheduler") => Mode::Scheduler,
_ if args.iter().any(|a| a == "--stdio") => Mode::Stdio,
_ => {
print_usage();
@@ -316,6 +319,64 @@ async fn run(base: PathBuf, mode: Mode) -> i32 {
shutdown_all(&host, plugins.as_ref()).await;
0
}
Mode::Scheduler => {
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
start_mcp(&host, &base);
inherit_trust(&host);
host.automations.set_headless_worker_mode(true);
host.automations.start(&host);
tracing::info!("openidea-server {} headless scheduler started", env!("CARGO_PKG_VERSION"));
let mut idle_ticks = 0u32;
let mut check = tokio::time::interval(std::time::Duration::from_secs(5));
#[cfg(unix)]
let mut terminate =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).expect("SIGTERM listener");
loop {
#[cfg(unix)]
tokio::select! {
_ = tokio::signal::ctrl_c() => break,
_ = terminate.recv() => break,
_ = check.tick() => {}
}
#[cfg(not(unix))]
tokio::select! {
_ = tokio::signal::ctrl_c() => break,
_ = check.tick() => {}
}
let service_enabled = ide_workspace::SettingsStore::load(&host.config_dir, None)
.effective()
.agents
.automations
.auto_start_service;
let running = host.automations.has_running_runs();
if host.automations.worker_stop_requested() || !service_enabled {
if !running {
tracing::info!("headless scheduler login service disabled; exiting");
break;
}
} else if host.automations.has_enabled_schedules() || running {
idle_ticks = 0;
} else {
idle_ticks += 1;
if idle_ticks >= 3 {
tracing::info!("no enabled automations remain; headless scheduler exiting");
break;
}
}
}
shutdown_all(&host, None).await;
0
}
#[cfg(unix)]
Mode::Daemon(socket, build) => {
let peer = Arc::new(rpc::PeerSlot::default());
+2
Переглянути файл
@@ -398,6 +398,7 @@ pub async fn serve(
};
let shutdown = CancellationToken::new();
host.automations.start(&host);
let idle_policy = RemoteIdlePolicy { override_seconds: idle_override() };
let mut check = tokio::time::interval(Duration::from_secs(idle_policy.override_seconds.unwrap_or(5).min(5)));
let mut idle = None;
@@ -541,6 +542,7 @@ fn has_live_work(host: &Host) -> bool {
!host.terminals.list().is_empty()
|| host.processes.has_live_runs()
|| !host.debugger.sessions(None).is_empty()
|| host.automations.keeps_remote_daemon_alive(host)
|| host
.projects()
.iter()
+17 -1
Переглянути файл
@@ -4,6 +4,7 @@
//! runs one on a remote machine and serves it over JSON-RPC ([`rpc`]).
pub mod agent_secrets;
pub mod automations;
pub mod catalogue;
#[cfg(unix)]
pub mod daemon;
@@ -107,9 +108,12 @@ pub struct Host {
pub mcp_agent_runs: mcp::AgentRuns,
/// Projects the MCP server serves without a window.
pub mcp_background: mcp::BackgroundProjects,
/// Host-owned scheduled agent automations and in-session follow-up timers.
pub automations: Arc<automations::AutomationService>,
pub(crate) agent_catalogs: Arc<ide_agent::AgentCatalogs>,
pub trust: std::sync::Arc<trust::TrustStore>,
pub(crate) mcp_approvals: Arc<trust::McpServerApprovals>,
pub(crate) plugin_approvals: Arc<trust::PluginCapabilityApprovals>,
pub config_dir: PathBuf,
/// Persistent user state, including credentials and recovery history.
pub data_dir: PathBuf,
@@ -254,6 +258,8 @@ impl Host {
let migration = ssh.clone();
runtime.spawn_blocking(move || migration.start_password_migration());
ssh.set_configs(global_settings.effective().ssh.configs);
let boot_override = if cfg!(test) { Some(data_dir.join("boot-services-test")) } else { None };
let automations = automations::AutomationService::new(&data_dir, boot_override);
let host = Self {
plugin_host: RwLock::default(),
local_database_tunnels: false,
@@ -266,9 +272,11 @@ impl Host {
mcp_requests: Default::default(),
mcp_agent_runs: Default::default(),
mcp_background: Default::default(),
automations,
agent_catalogs: Arc::default(),
trust: std::sync::Arc::new(trust::TrustStore::load(&config_dir, &data_dir)),
mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)),
plugin_approvals: Arc::new(trust::PluginCapabilityApprovals::load(&data_dir)),
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
jupyter_tokens: ide_ssh::secrets::SecretFile::new(data_dir.join("jupyter-tokens.json")),
proxy_session_password: Mutex::default(),
@@ -504,13 +512,20 @@ impl Host {
let processes = self.processes.detach_project_kills(&project.root);
let terminals = self.terminals.detach_key(self.owner_window(window));
let root = (!project.light).then(|| project.root.clone());
let shutdown_agents = if !project.light
&& self.automations.retain_on_window_close(self, &project.root, &project.agents, agent_reason)
{
Vec::new()
} else {
vec![project.agents.clone()]
};
let handle = self.spawn_project_shutdown(ShutdownWork {
notebooks: vec![project.notebooks.clone()],
bridges: project.kotlin_bridge.iter().cloned().collect(),
lsp: Some(project.lsp.clone()),
// Debug sessions under the root belong to windows: a project served without one starts none.
debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
agents: vec![project.agents.clone()],
agents: shutdown_agents,
agent_reason,
terminals: Some(terminals),
processes: Some(processes),
@@ -639,6 +654,7 @@ impl Host {
}
pub fn shutdown_notebooks_on_exit_with(&self, agent_reason: ide_agent::AgentShutdownReason) {
self.automations.stop();
let projects = self.projects();
let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect();
if !projects.is_empty() {
+1 -1
Переглянути файл
@@ -444,7 +444,7 @@ impl BackgroundProjects {
impl Host {
/// The window, and its project, that has `root` open as a project (not in LightEdit).
fn window_project(&self, root: &Path) -> Option<(String, Arc<Project>)> {
pub(crate) fn window_project(&self, root: &Path) -> Option<(String, Arc<Project>)> {
let projects = self.projects.read();
let windows = projects.iter().filter(|(w, p)| !BackgroundProjects::is_key(w) && !p.light && p.root == root);
windows.min_by_key(|(w, _)| w.as_str()).map(|(w, p)| (w.clone(), p.clone()))
+40 -3
Переглянути файл
@@ -242,7 +242,11 @@ marked directory are not marked again.",
},
)
.param(Param::required("directoryPath", ParamType::String, RELATIVE_PATH_IN_PROJECT_DESCRIPTION))
.param(Param::optional("maxDepth", ParamType::Integer, "Maximum recursion depth"))
.param(Param::optional(
"maxDepth",
ParamType::Integer,
"Levels to list below the directory: 1 lists its entries, 2 their entries too, and so on (default 5)",
))
.param(Param::optional("limit", ParamType::Integer, "Entries to return at most (default 100)"))
.param(Param::optional("offset", ParamType::Integer, OFFSET))
.param(Param::optional("timeout", ParamType::Integer, TIMEOUT_MILLISECONDS_DESCRIPTION))
@@ -306,6 +310,7 @@ fn marker(git_ignored: bool, ide_excluded: bool) -> &'static str {
}
impl TreeRender {
/// `max_depth`: the levels to list below the entry (0 lists the entry alone);
/// `mark`: the entry's marker; `marked`: it or a directory above it is marked.
#[allow(clippy::too_many_arguments)]
fn render(
@@ -318,7 +323,7 @@ impl TreeRender {
mark: &str,
marked: bool,
) {
if max_depth <= 0 || self.timed_out || self.cancel.is_cancelled() {
if self.timed_out || self.cancel.is_cancelled() {
return;
}
if Instant::now() >= self.deadline {
@@ -343,7 +348,7 @@ impl TreeRender {
} else {
self.entry(&line)
};
if !is_dir {
if !is_dir || max_depth <= 0 {
return;
}
// Without exclusions, `ignored` is what `.gitignore` says.
@@ -482,6 +487,38 @@ mod tests {
assert_eq!(render(0, 100).0, " ├── a/\n │ ├── x.txt\n │ └── y.txt\n └── b.txt\n");
}
#[test]
fn max_depth_counts_the_levels_below_the_directory() {
let tmp = tempfile::tempdir().unwrap();
for file in ["a/b/c.txt", "d.txt"] {
let path = tmp.path().join(file);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "").unwrap();
}
let render = |max_depth| {
let mut tree = TreeRender {
out: String::new(),
errors: Vec::new(),
timed_out: false,
deadline: Instant::now() + Duration::from_secs(10),
cancel: CancellationToken::new(),
page: Page { offset: 0, limit: 100 },
seen: 0,
above: Vec::new(),
marks: Marks { root: tmp.path().to_path_buf(), excludes: None },
};
tree.render(tmp.path(), "", true, max_depth, true, "", false);
let root = format!("{}/\n", tmp.path().display());
(tree.out.strip_prefix(&root).unwrap().to_owned(), tree.seen)
};
assert_eq!(render(0), (String::new(), 0), "0 lists the directory alone");
assert_eq!(render(1), (" ├── a/\n └── d.txt\n".to_owned(), 2), "1 lists its entries");
assert_eq!(render(2), (" ├── a/\n │ └── b/\n └── d.txt\n".to_owned(), 3));
let full = " ├── a/\n │ └── b/\n │ └── c.txt\n └── d.txt\n".to_owned();
assert_eq!(render(3), (full.clone(), 4));
assert_eq!(render(5), (full, 4), "a depth beyond the tree lists all of it");
}
#[test]
fn what_the_project_leaves_out_is_marked_once() {
let tmp = tempfile::tempdir().unwrap();
+774 -69
Переглянути файл
@@ -5,14 +5,17 @@ use crate::Host;
use crate::agent_secrets::{AgentSecrets, Kept};
use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentMemoryCatalog,
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemoryOverrides, AgentMemorySettings, AgentModelCatalog, AgentProbe,
AcpImportOutcome, AgentAcceptOutcome, AgentAutomation, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent,
AgentMarketplaceBrowseResult, AgentMemoryCatalog, AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemoryOverrides,
AgentMemorySettings, AgentModelCatalog, AgentPluginCatalog, AgentPluginPreview, AgentPluginSettings, AgentProbe,
AgentPrompt, AgentProvider, AgentProviderMemoryPolicy, AgentQueued, AgentRecoveryReport, AgentSkillMode,
AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, CopilotAuthStatus, CreateAgentMemoryInput,
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource, McpImportSelection,
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput,
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, AutomationRun, AutomationRunsPage,
AutomationSnapshot, AutomationTrigger, AutomationWorkspace, CopilotAuthStatus, CreateAgentMemoryInput,
CreateSessionScheduleInput, CustomAgentInput, ExternalSession, InstallAgentPluginRequest,
InstallRemoteSkillRequest, Isolation, LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult, McpScope,
McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput, RemoteSkillBrowseResult,
RemoteSkillPreview, SaveAutomationInput, SessionSchedule, SkillsPolicy,
};
use ide_command::command;
use ide_core::error::ErrorKind;
@@ -30,18 +33,47 @@ pub fn agent_subscribe(
on_event: Channel<AgentEvent>,
subscriber: String,
) -> IdeResult<Vec<AgentTask>> {
Ok(host.project(window)?.agents.subscribe_as(
&subscriber,
std::sync::Arc::new(move |e| {
let _ = on_event.send(e);
}),
))
let sink: ide_agent::AgentSink = std::sync::Arc::new(move |e| {
let _ = on_event.send(e);
});
let scope = crate::automations::AutomationTaskScope::for_window(host, window);
let mut by_id: std::collections::HashMap<String, AgentTask> = std::collections::HashMap::new();
match host.project(window) {
Ok(proj) => {
for t in proj.agents.subscribe_as(&subscriber, sink.clone()) {
by_id.insert(t.id.clone(), t);
}
}
Err(e) => {
// Without an open project, `scope.allowed_roots` is empty (no wildcard!) so ONLY
// `ChatOnly` tasks may be subscribed if any exist.
let extras = host.automations.subscribe_window_extras(host, &scope, &subscriber, sink);
if extras.is_empty() {
return Err(e);
}
for t in extras {
by_id.insert(t.id.clone(), t);
}
let mut list: Vec<AgentTask> = by_id.into_values().collect();
list.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
return Ok(list);
}
}
for extra in host.automations.subscribe_window_extras(host, &scope, &subscriber, sink) {
by_id.insert(extra.id.clone(), extra);
}
let mut list: Vec<AgentTask> = by_id.into_values().collect();
list.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
Ok(list)
}
/// Stops the events of a window that closed.
#[command(trust = always)]
pub fn agent_unsubscribe(host: &Host, window: &str, subscriber: String) -> IdeResult<()> {
host.project(window)?.agents.unsubscribe(&subscriber);
host.automations.unsubscribe_window_extras(&subscriber);
if let Ok(proj) = host.project(window) {
proj.agents.unsubscribe(&subscriber);
}
Ok(())
}
@@ -422,8 +454,7 @@ pub async fn agent_entries(
task: String,
subagent: Option<String>,
) -> IdeResult<Vec<AgentEntry>> {
let agents = host.project(window)?.agents.clone();
host.blocking(move || agents.entries(&task, subagent)).await
host.automations.route_entries(host, window, task, subagent).await
}
/// Sessions of the project on this machine that no task holds yet, newest first.
@@ -478,8 +509,8 @@ pub async fn agent_create(host: &Host, window: &str, request: NewAgentTask) -> I
/// Sends a message; while the agent works it is queued, or with `now` it interrupts the turn.
#[command(trust = trusted)]
pub async fn agent_prompt(host: &Host, window: &str, task: String, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.prompt(&task, prompt, now).await
host.require_trust_if_project(window)?;
host.automations.route_prompt(host, window, task, prompt, now).await
}
/// Runs a `!` line of the composer in the task's folder with the user's shell, without
@@ -509,8 +540,8 @@ pub async fn agent_answer_question(
question: String,
answer: Option<String>,
) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.answer_question(&task, &question, answer).await
host.require_trust_if_project(window)?;
host.automations.route_answer_question(host, window, task, question, answer).await
}
/// Drops a queued message and returns it (to edit it).
@@ -615,7 +646,7 @@ pub async fn agent_context_usage(host: &Host, window: &str, task: String) -> Ide
/// Stops the task's current turn, or with `subagent` only that subagent's work.
#[command(trust = always)]
pub fn agent_cancel(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<()> {
host.project(window)?.agents.cancel(&task, subagent)
host.automations.route_cancel(host, window, task, subagent)
}
/// Resumes an interrupted task with a continuation turn (or immediately wakes a task waiting
@@ -645,7 +676,10 @@ pub async fn agent_dismiss_interrupted(host: &Host, window: &str, task: String)
/// Marks a task as read (`unread = false`) when viewed by the user.
#[command(trust = always)]
pub async fn agent_mark_read(host: &Host, window: &str, task: String) -> IdeResult<()> {
let agents = host.project(window)?.agents.clone();
let agents = match host.automations.authorized_local_manager(host, window, &task, false)? {
Some(mgr) => mgr,
None => host.project(window)?.agents.clone(),
};
host.blocking(move || agents.mark_read(&task)).await
}
@@ -689,7 +723,7 @@ pub async fn agent_reconcile_interrupted(host: &Host, window: &str) -> IdeResult
/// Stops one of the task's background tasks.
#[command(trust = always)]
pub async fn agent_stop_background(host: &Host, window: &str, task: String, background: String) -> IdeResult<()> {
host.project(window)?.agents.stop_background(&task, &background).await
host.automations.route_stop_background(host, window, task, background).await
}
/// Answers a permission request; `option: null` cancels it.
@@ -701,29 +735,48 @@ pub fn agent_respond(
permission: u32,
option: Option<String>,
) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.respond(&task, permission, option)
host.require_trust_if_project(window)?;
host.automations.route_respond(host, window, task, permission, option)
}
#[command(trust = always)]
pub fn agent_archive(host: &Host, window: &str, task: String) -> IdeResult<()> {
host.project(window)?.agents.archive(&task)
match host.automations.authorized_local_manager(host, window, &task, false)? {
Some(mgr) => mgr.archive(&task),
None => host.project(window)?.agents.archive(&task),
}
}
#[command(trust = always)]
pub fn agent_unarchive(host: &Host, window: &str, task: String) -> IdeResult<()> {
host.project(window)?.agents.unarchive(&task)
match host.automations.authorized_local_manager(host, window, &task, false)? {
Some(mgr) => mgr.unarchive(&task),
None => host.project(window)?.agents.unarchive(&task),
}
}
#[command(trust = trusted)]
pub fn agent_rename(host: &Host, window: &str, task: String, title: String) -> IdeResult<()> {
host.project(window)?.agents.rename(&task, &title)
host.require_trust_if_project(window)?;
match host.automations.authorized_local_manager(host, window, &task, true)? {
Some(mgr) => mgr.rename(&task, &title),
None => {
host.require_trust(window)?;
host.project(window)?.agents.rename(&task, &title)
}
}
}
#[command(trust = trusted)]
pub async fn agent_delete(host: &Host, window: &str, task: String, remove_worktree: bool) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.delete(&task, remove_worktree).await
host.require_trust_if_project(window)?;
match host.automations.authorized_local_manager(host, window, &task, true)? {
Some(mgr) => mgr.delete(&task, remove_worktree).await,
None => {
host.require_trust(window)?;
host.project(window)?.agents.delete(&task, remove_worktree).await
}
}
}
/// The task's changed files as `view` compares them (without: since it started).
@@ -956,7 +1009,20 @@ fn listed(
}
}
}
out
let plug_policy = host_plugins_policy(host, project.map(|p| p.as_ref()));
let home = host.home_dir();
let plug_states = ide_agent::plugins::resolve_plugins(
ide_agent::plugins::discover_plugins(&plug_policy.workspace_roots, home.as_deref()),
&plug_policy,
Some(&*host.agent_secrets),
);
let projected = ide_agent::plugins::projected_mcp_servers(
&plug_states,
&plug_policy,
home.as_deref(),
Some(&*host.agent_secrets),
);
ide_agent::mcp::merge_projected_servers(out, projected)
}
/// The MCP servers agent sessions of the project at `root` get: the user's, values filled in, and
@@ -1315,27 +1381,43 @@ pub fn agent_set_memory_overrides(
host.project(window)?.agents.set_memory_overrides(&task, overrides)
}
fn resolve_skills_with_host_plugins(
policy: &SkillsPolicy,
plug_policy: &ide_agent::plugins::PluginsPolicy,
home: Option<&std::path::Path>,
secrets: Option<&dyn ide_agent::EnvSecrets>,
) -> Vec<AgentSkillState> {
let plug_states = ide_agent::plugins::resolve_plugins(
ide_agent::plugins::discover_plugins(&policy.workspace_roots, home),
plug_policy,
secrets,
);
let projected = ide_agent::plugins::projected_skill_roots(&plug_states, None);
ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_agent_plugins(
&policy.workspace_roots,
home,
&policy.plugin_dirs,
&projected,
),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
)
}
/// Every skill discovered in the project, the user's folders and enabled plugins, with
/// the mode a session runs it with (without any session's own overrides).
#[command(trust = always)]
pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<AgentSkillState>> {
let project = host.project(window).ok().filter(|p| !p.light);
let policy = host_skills_policy(host, project.as_deref());
let home = dirs::home_dir();
blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(
&policy.workspace_roots,
home.as_deref(),
&policy.plugin_dirs,
),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
let plug_policy = host_plugins_policy(host, project.as_deref());
let home = host.home_dir();
let secrets = host.agent_secrets.clone();
blocking(move || Ok(resolve_skills_with_host_plugins(&policy, &plug_policy, home.as_deref(), Some(&*secrets))))
.await
}
/// Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
@@ -1380,14 +1462,9 @@ pub fn agent_skills_set_mode(
}
}
let policy = host_skills_policy(host, project.as_deref());
let home = dirs::home_dir();
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(&policy.workspace_roots, home.as_deref(), &policy.plugin_dirs),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
let plug_policy = host_plugins_policy(host, project.as_deref());
let home = host.home_dir();
Ok(resolve_skills_with_host_plugins(&policy, &plug_policy, home.as_deref(), Some(&*host.agent_secrets)))
}
/// Resolves a GitHub `owner/repo[/path][@ref]` source and lists the `SKILL.md` skills in it.
@@ -1478,20 +1555,10 @@ pub async fn agent_skills_install(
}
let policy = host_skills_policy(host, project.as_deref());
blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(
&policy.workspace_roots,
home.as_deref(),
&policy.plugin_dirs,
),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
let plug_policy = host_plugins_policy(host, project.as_deref());
let secrets = host.agent_secrets.clone();
blocking(move || Ok(resolve_skills_with_host_plugins(&policy, &plug_policy, home.as_deref(), Some(&*secrets))))
.await
}
/// The user's and the workspace's skill policies (`[agents.skills.<name>]`).
@@ -1650,9 +1717,18 @@ fn persist_memory_settings(
async fn current_memory_catalog(host: &Host, project: Option<&crate::Project>) -> IdeResult<AgentMemoryCatalog> {
let policy = host_memory_policy(host, project);
let plug_policy = host_plugins_policy(host, project);
let home = host.home_dir();
let secrets = host.agent_secrets.clone();
blocking(move || {
let entries = ide_agent::memory::discover_memories(&policy.workspace_roots, home.as_deref());
let plug_states = ide_agent::plugins::resolve_plugins(
ide_agent::plugins::discover_plugins(&policy.workspace_roots, home.as_deref()),
&plug_policy,
Some(&*secrets),
);
let projected = ide_agent::plugins::projected_memory_entries(&plug_states);
let entries =
ide_agent::memory::discover_memories_with_plugins(&policy.workspace_roots, home.as_deref(), projected);
Ok(ide_agent::memory::resolve_catalog(entries, None, &policy, home.as_deref()))
})
.await
@@ -1852,6 +1928,307 @@ pub async fn agent_memory_reset_provider(host: &Host, window: &str, provider: St
current_memory_catalog(host, project.as_deref()).await
}
fn host_plugins_policy(host: &Host, project: Option<&crate::Project>) -> ide_agent::plugins::PluginsPolicy {
match project {
Some(project) => ide_agent::plugins::PluginsPolicy {
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.plugins.clone(),
workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.plugins.clone(),
workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire),
workspace_roots: workspace_skill_roots(&project.root),
approved_capabilities: host.plugin_approvals.snapshot(),
},
None => ide_agent::plugins::PluginsPolicy {
user: host.global_settings.effective().agents.plugins.clone(),
workspace: Default::default(),
workspace_trusted: true,
workspace_roots: Vec::new(),
approved_capabilities: host.plugin_approvals.snapshot(),
},
}
}
fn plugins_settings_layers(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
) -> (AgentPluginSettings, Option<AgentPluginSettings>) {
let user = host.global_settings.effective().agents.plugins.clone();
let workspace =
project.map(|p| p.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.plugins.clone());
(user, workspace)
}
fn is_default_plugin_settings(s: &AgentPluginSettings) -> bool {
s.marketplaces.is_empty() && s.entries.is_empty()
}
fn persist_plugin_settings(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
scope: McpScope,
settings: &AgentPluginSettings,
) -> IdeResult<()> {
let value = if is_default_plugin_settings(settings) {
serde_json::Value::Null
} else {
serde_json::to_value(settings).map_err(|e| IdeError::invalid(e.to_string()))?
};
match scope {
McpScope::User => {
host.global_settings.set(ide_workspace::settings::SettingsScope::Global, "agents.plugins", value)?;
for p in host.projects() {
p.settings.reload();
p.agents.notify_mcp_servers_changed();
emit_plugin_projection_events(&p.sink);
}
}
McpScope::Workspace => {
let p = project.ok_or_else(|| IdeError::invalid("Open a project to configure workspace agent plugins"))?;
p.settings.set(ide_workspace::settings::SettingsScope::Project, "agents.plugins", value)?;
p.agents.notify_mcp_servers_changed();
emit_plugin_projection_events(&p.sink);
}
}
Ok(())
}
fn emit_plugin_projection_events(sink: &SharedSink) {
for key in ["agents.plugins", "agents.skills", "agents.mcpServers", "agents.memory"] {
sink.emit(IdeEvent::SettingsChanged { key: key.into() });
}
}
async fn current_plugins_catalog(host: &Host, project: Option<&crate::Project>) -> IdeResult<AgentPluginCatalog> {
let policy = host_plugins_policy(host, project);
let home = host.home_dir();
let secrets = host.agent_secrets.clone();
blocking(move || {
let discovered = ide_agent::plugins::discover_plugins(&policy.workspace_roots, home.as_deref());
Ok(ide_agent::plugins::resolve_catalog(discovered, &policy, home.as_deref(), Some(&*secrets)))
})
.await
}
/// Lists all discovered agent plugin bundles, registered/discovered marketplaces, and projection counts.
#[command(trust = always)]
pub async fn agent_plugins_list(host: &Host, window: &str) -> IdeResult<AgentPluginCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
current_plugins_catalog(host, project.as_deref()).await
}
/// Enables or disables an installed plugin in that harness's native configuration.
#[command(trust = always)]
pub async fn agent_plugins_set_enabled(
host: &Host,
window: &str,
id: String,
scope: McpScope,
enabled: bool,
approve_capabilities: bool,
capability_hash: Option<String>,
) -> IdeResult<AgentPluginCatalog> {
let id = id.trim().to_owned();
if id.is_empty() {
return Err(IdeError::invalid("Plugin ID is required"));
}
let project = host.project(window).ok().filter(|p| !p.light);
let project_root = project.as_ref().map(|p| p.root.clone());
let policy = host_plugins_policy(host, project.as_deref());
let home = host.home_dir();
let lookup_id = id.clone();
let home_for_discovery = home.clone();
let found_plugin = blocking(move || {
let discovered = ide_agent::plugins::discover_plugins(&policy.workspace_roots, home_for_discovery.as_deref());
// Ids are owner-qualified and stable, so only an exact match may be toggled.
Ok(discovered.into_iter().find(|p| p.scope == scope && p.id == lookup_id))
})
.await?;
let plugin = found_plugin.ok_or_else(|| IdeError::not_found(format!("Plugin `{id}` not found")))?;
if plugin.scope == McpScope::Workspace {
host.require_trust(window)?;
}
let approval_key = ide_agent::plugins::capability_approval_key(&plugin);
let already_approved = approval_key.as_ref().is_some_and(|key| host.plugin_approvals.snapshot().contains(key));
if enabled && plugin.capabilities.requires_consent && !approve_capabilities && !already_approved {
return Err(IdeError::invalid("Approve the plugin's executable capabilities before enabling it"));
}
if approve_capabilities && let Some(key) = approval_key {
// Approve only the capabilities the user was shown; re-inspection may have found others.
if capability_hash.as_deref() != plugin.capabilities.capability_hash.as_deref() {
return Err(IdeError::invalid(
"The plugin's executable capabilities changed since they were shown; review them again",
));
}
host.plugin_approvals.approve(key)?;
}
let plugin_for_write = plugin.clone();
let home_for_write = home.clone();
blocking(move || {
ide_agent::plugins::set_plugin_enabled(
&plugin_for_write,
enabled,
home_for_write.as_deref(),
project_root.as_deref(),
)
})
.await?;
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
emit_plugin_projection_events(&p.sink);
}
current_plugins_catalog(host, project.as_deref()).await
}
/// Registers a marketplace source (`owner/repo[#ref]`, GitHub URL, or local path) in `scope`.
#[command(trust = always)]
pub async fn agent_plugins_add_marketplace(
host: &Host,
window: &str,
scope: McpScope,
source: String,
) -> IdeResult<AgentPluginCatalog> {
let clean = source.trim().to_owned();
if clean.is_empty() {
return Err(IdeError::invalid("Enter a marketplace repository or local path"));
}
if scope == McpScope::Workspace {
host.require_trust(window)?;
}
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = plugins_settings_layers(host, project.as_ref());
let target = match scope {
McpScope::User => &mut user,
McpScope::Workspace => {
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace marketplaces"))?
}
};
if !target.marketplaces.iter().any(|m| m == &clean) {
target.marketplaces.push(clean);
let to_save = target.clone();
persist_plugin_settings(host, project.as_ref(), scope, &to_save)?;
}
current_plugins_catalog(host, project.as_deref()).await
}
/// Removes a registered marketplace source from `scope`.
#[command(trust = always)]
pub async fn agent_plugins_remove_marketplace(
host: &Host,
window: &str,
scope: McpScope,
source: String,
) -> IdeResult<AgentPluginCatalog> {
let clean = source.trim();
if scope == McpScope::Workspace {
host.require_trust(window)?;
}
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = plugins_settings_layers(host, project.as_ref());
let target = match scope {
McpScope::User => &mut user,
McpScope::Workspace => {
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace marketplaces"))?
}
};
let before = target.marketplaces.len();
target.marketplaces.retain(|m| m != clean);
if target.marketplaces.len() != before {
let to_save = target.clone();
persist_plugin_settings(host, project.as_ref(), scope, &to_save)?;
}
current_plugins_catalog(host, project.as_deref()).await
}
/// Browses installable plugins inside a marketplace (`owner/repo[#ref]`, GitHub URL, or local directory/manifest).
#[command(trust = always)]
pub async fn agent_plugins_browse_marketplace(
host: &Host,
window: &str,
source: String,
request: RequestId,
) -> IdeResult<AgentMarketplaceBrowseResult> {
let cancel = host.begin_request(request);
let ws_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let home = host.home_dir();
let search_path = ide_core::tool_path::search_path();
let res = blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::plugins::browse_marketplace(&fetcher, &source, home.as_deref(), ws_root.as_deref(), &cancel)
})
.await;
host.end_request(request);
res
}
/// Previews an agent plugin bundle from GitHub or a local folder before installation, scanning files and capabilities.
#[command(trust = always)]
pub async fn agent_plugins_preview(
host: &Host,
window: &str,
source: String,
subpath: Option<String>,
marketplace: Option<String>,
request: RequestId,
) -> IdeResult<AgentPluginPreview> {
let cancel = host.begin_request(request);
let ws_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let home = host.home_dir();
let search_path = ide_core::tool_path::search_path();
let res = blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::plugins::preview_plugin(
&fetcher,
&source,
subpath.as_deref(),
marketplace.as_deref(),
home.as_deref(),
ws_root.as_deref(),
&cancel,
)
})
.await;
host.end_request(request);
res
}
/// Atomically installs a previewed agent plugin into the selected harness's native plugin directory.
#[command(trust = always)]
pub async fn agent_plugins_install(
host: &Host,
window: &str,
input: InstallAgentPluginRequest,
request: RequestId,
) -> IdeResult<AgentPluginCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
if input.scope == McpScope::Workspace || input.source_kind == "local" {
host.require_trust(window)?;
}
let ws_root = project.as_ref().map(|p| p.root.clone());
let home = host.home_dir();
let cancel = host.begin_request(request);
let search_path = ide_core::tool_path::search_path();
let req_clone = input.clone();
let install_res = blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::plugins::install_plugin(&fetcher, &req_clone, home.as_deref(), ws_root.as_deref(), &cancel)
})
.await;
host.end_request(request);
let (_, approval_key) = install_res?;
if input.approve_capabilities
&& let Some(key) = approval_key
{
host.plugin_approvals.approve(key)?;
}
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
emit_plugin_projection_events(&p.sink);
}
current_plugins_catalog(host, project.as_deref()).await
}
fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::Path>) -> IdeResult<std::path::PathBuf> {
let Some(requested) = requested else {
return Ok(root.to_path_buf());
@@ -1869,6 +2246,312 @@ fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::P
Err(IdeError::invalid("Agent project must be the window project or a workspace member"))
}
// ---------------------------------------------------------------------------
// Agent Automations & In-Session Schedules
// ---------------------------------------------------------------------------
fn host_label_for(remote: bool) -> String {
std::env::var("HOSTNAME")
.ok()
.filter(|s| !s.trim().is_empty())
.unwrap_or_else(|| if remote { "Remote Server".into() } else { "Local Host".into() })
}
fn window_automation_scope(host: &Host, window: &str) -> (Option<Vec<std::path::PathBuf>>, bool) {
if let Some(p) = host.project(window).ok().filter(|p| !p.light) {
let trusted = host.trust.window_trusted(&p.root).unwrap_or(false);
let mut roots = vec![dunce::canonicalize(&p.root).unwrap_or_else(|_| p.root.clone())];
if let Ok(Some(ws)) = ide_workspace::workspace::Workspace::load(&p.root) {
for member in ws.projects {
let canon = dunce::canonicalize(&member).unwrap_or(member);
if !roots.contains(&canon) {
roots.push(canon);
}
}
}
(Some(roots), trusted)
} else {
(Some(Vec::new()), true)
}
}
fn require_window_trust_if_project(host: &Host, window: &str) -> IdeResult<()> {
if let Some(p) = host.project(window).ok().filter(|p| !p.light) {
p.require_trust()?;
}
Ok(())
}
fn ensure_window_owns_automation(host: &Host, window: &str, id: &str) -> IdeResult<AgentAutomation> {
require_window_trust_if_project(host, window)?;
let auto = host.automations.get(id).ok_or_else(|| IdeError::not_found(format!("unknown automation '{id}'")))?;
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
if let Some(roots) = allowed_roots {
match &auto.workspace {
AutomationWorkspace::ChatOnly if include_chat_only => {}
AutomationWorkspace::ChatOnly => {
return Err(IdeError::invalid("Trust the project before accessing automations"));
}
AutomationWorkspace::Project { root, .. } => {
let cand = dunce::canonicalize(&root.0).unwrap_or_else(|_| root.0.clone());
if !roots.contains(&cand) {
return Err(IdeError::invalid("Automation belongs to a different project"));
}
}
}
}
Ok(auto)
}
fn ensure_window_owns_session_schedule(host: &Host, window: &str, id: &str) -> IdeResult<()> {
host.require_trust(window)?;
let (allowed_roots, _) = window_automation_scope(host, window);
if let Some(roots) = allowed_roots {
let schedules = host.automations.list_session_schedules_scoped(Some(&roots), None);
if !schedules.iter().any(|s| s.id == id) {
return Err(IdeError::not_found(format!("unknown session schedule '{id}'")));
}
}
Ok(())
}
/// Returns the current project's automations, first page of run history, active session schedules,
/// and scheduler/boot-service status.
#[command(trust = always)]
pub async fn agent_automation_snapshot(
host: &std::sync::Arc<Host>,
window: &str,
remote: bool,
) -> IdeResult<AutomationSnapshot> {
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
let h = host.clone();
host.blocking(move || {
Ok(h.automations.snapshot_scoped(
&h,
allowed_roots.as_deref(),
include_chat_only,
remote,
host_label_for(remote),
))
})
.await
}
/// Creates or updates an [`AgentAutomation`]. Project-scoped automations require a trusted project.
#[command(trust = trusted)]
pub async fn agent_automation_save(
host: &std::sync::Arc<Host>,
window: &str,
mut input: SaveAutomationInput,
) -> IdeResult<AgentAutomation> {
require_window_trust_if_project(host, window)?;
if let Some(existing_id) = input.id.as_deref() {
let _ = ensure_window_owns_automation(host, window, existing_id)?;
}
if let AutomationWorkspace::Project { root, isolation, base, auto_clean_worktree } = input.workspace {
let project = host.project(window).ok().filter(|p| !p.light);
let validated = match &project {
Some(p) => {
p.require_trust()?;
validate_project_root(&p.root, Some(&root.0))?
}
None => {
if !host.trust.window_trusted(&root.0)? {
return Err(IdeError::invalid("Trust the project before creating an automation in it"));
}
dunce::canonicalize(&root.0)?
}
};
input.workspace =
AutomationWorkspace::Project { root: IpcPath(validated), isolation, base, auto_clean_worktree };
}
let h = host.clone();
host.blocking(move || h.automations.save(&h, input)).await
}
/// Enables or pauses an automation schedule.
#[command(trust = trusted)]
pub async fn agent_automation_set_enabled(
host: &std::sync::Arc<Host>,
window: &str,
id: String,
enabled: bool,
) -> IdeResult<AgentAutomation> {
let _ = ensure_window_owns_automation(host, window, &id)?;
let h = host.clone();
host.blocking(move || h.automations.set_enabled(&h, &id, enabled)).await
}
/// Pauses all enabled schedules (for the current window's project, or across all projects when `all_projects` is true).
#[command(trust = trusted)]
pub async fn agent_automation_pause_all(
host: &std::sync::Arc<Host>,
window: &str,
all_projects: bool,
) -> IdeResult<u32> {
require_window_trust_if_project(host, window)?;
let (allowed_roots, include_chat_only) =
if all_projects { (None, true) } else { window_automation_scope(host, window) };
let h = host.clone();
host.blocking(move || h.automations.pause_all_scoped(&h, allowed_roots.as_deref(), include_chat_only)).await
}
/// Deletes an automation and its run history entries.
#[command(trust = trusted)]
pub async fn agent_automation_delete(host: &std::sync::Arc<Host>, window: &str, id: String) -> IdeResult<()> {
let _ = ensure_window_owns_automation(host, window, &id)?;
let h = host.clone();
host.blocking(move || h.automations.delete(&h, &id)).await
}
/// Immediately triggers a manual run of automation `id`.
#[command(trust = trusted)]
pub async fn agent_automation_run_now(
host: &std::sync::Arc<Host>,
window: &str,
id: String,
) -> IdeResult<AutomationRun> {
let _ = ensure_window_owns_automation(host, window, &id)?;
host.automations.clone().run_now(host, &id).await
}
/// Lists paginated automation run history.
#[command(trust = always)]
pub async fn agent_automation_runs(
host: &std::sync::Arc<Host>,
window: &str,
automation_id: Option<String>,
cursor: Option<u32>,
limit: Option<u32>,
) -> IdeResult<AutomationRunsPage> {
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
let h = host.clone();
host.blocking(move || {
Ok(h.automations.runs_scoped(
allowed_roots.as_deref(),
include_chat_only,
automation_id.as_deref(),
cursor,
limit,
))
})
.await
}
/// Marks one run, one automation's runs, or all runs in the current window's scope as read.
#[command(trust = trusted)]
pub async fn agent_automation_mark_read(
host: &std::sync::Arc<Host>,
window: &str,
run_id: Option<String>,
automation_id: Option<String>,
) -> IdeResult<()> {
require_window_trust_if_project(host, window)?;
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
let h = host.clone();
host.blocking(move || {
h.automations.mark_read_scoped(
&h,
allowed_roots.as_deref(),
include_chat_only,
run_id.as_deref(),
automation_id.as_deref(),
)
})
.await
}
/// Previews the next `count` firing timestamps (epoch ms) for a schedule trigger.
#[command(trust = always)]
pub async fn agent_automation_preview_schedule(
host: &std::sync::Arc<Host>,
trigger: AutomationTrigger,
count: Option<u32>,
) -> IdeResult<Vec<f64>> {
let h = host.clone();
host.blocking(move || h.automations.preview_schedule(&trigger, count)).await
}
/// Exports automation `id` into portable `.automation.md` text.
#[command(trust = trusted)]
pub async fn agent_automation_export_markdown(
host: &std::sync::Arc<Host>,
window: &str,
id: String,
) -> IdeResult<String> {
let _ = ensure_window_owns_automation(host, window, &id)?;
let h = host.clone();
host.blocking(move || h.automations.export_markdown(&id)).await
}
/// Imports a `.automation.md` template into the current project (or as ChatOnly) with `enabled = false`.
#[command(trust = trusted)]
pub async fn agent_automation_import_markdown(
host: &std::sync::Arc<Host>,
window: &str,
markdown: String,
chat_only: bool,
provider: String,
) -> IdeResult<AgentAutomation> {
require_window_trust_if_project(host, window)?;
let workspace = if chat_only {
AutomationWorkspace::ChatOnly
} else {
host.require_trust(window)?;
let project = host.project(window)?;
AutomationWorkspace::Project {
root: IpcPath(project.root.clone()),
isolation: Isolation::Worktree,
base: None,
auto_clean_worktree: true,
}
};
let h = host.clone();
host.blocking(move || h.automations.import_markdown(&h, &markdown, workspace, provider)).await
}
/// Attaches a `Send Later` one-shot or `/loop` recurring schedule to an existing task session.
#[command(trust = trusted)]
pub async fn agent_session_schedule_create(
host: &std::sync::Arc<Host>,
window: &str,
input: CreateSessionScheduleInput,
) -> IdeResult<SessionSchedule> {
host.require_trust(window)?;
let project = host.project(window)?;
let root = project.root.clone();
let h = host.clone();
host.blocking(move || h.automations.create_session_schedule(&h, root, input)).await
}
/// Pauses or resumes an in-session `/loop` or `Send Later` schedule.
#[command(trust = trusted)]
pub async fn agent_session_schedule_set_paused(
host: &std::sync::Arc<Host>,
window: &str,
id: String,
paused: bool,
) -> IdeResult<SessionSchedule> {
ensure_window_owns_session_schedule(host, window, &id)?;
let h = host.clone();
host.blocking(move || h.automations.set_session_schedule_paused(&h, &id, paused)).await
}
/// Sends a queued `Send Later` prompt or fires a `/loop` iteration immediately.
#[command(trust = trusted)]
pub async fn agent_session_schedule_run_now(host: &std::sync::Arc<Host>, window: &str, id: String) -> IdeResult<()> {
ensure_window_owns_session_schedule(host, window, &id)?;
host.automations.clone().run_session_schedule_now(host, &id).await
}
/// Cancels and deletes an in-session `Send Later` or `/loop` schedule.
#[command(trust = trusted)]
pub async fn agent_session_schedule_delete(host: &std::sync::Arc<Host>, window: &str, id: String) -> IdeResult<()> {
ensure_window_owns_session_schedule(host, window, &id)?;
let h = host.clone();
host.blocking(move || h.automations.delete_session_schedule(&h, &id)).await
}
#[cfg(test)]
mod tests {
use super::*;
@@ -2111,6 +2794,17 @@ ide_command::domain!(
agent_context_usage,
agent_changes,
agent_cli_update,
agent_automation_delete,
agent_automation_export_markdown,
agent_automation_import_markdown,
agent_automation_mark_read,
agent_automation_pause_all,
agent_automation_preview_schedule,
agent_automation_run_now,
agent_automation_runs,
agent_automation_save,
agent_automation_set_enabled,
agent_automation_snapshot,
agent_cli_update_check,
agent_commands,
agent_copilot_auth_status,
@@ -2143,6 +2837,13 @@ ide_command::domain!(
agent_memory_reset_provider,
agent_memory_set_auto,
agent_memory_set_mode,
agent_plugins_add_marketplace,
agent_plugins_browse_marketplace,
agent_plugins_install,
agent_plugins_list,
agent_plugins_preview,
agent_plugins_remove_marketplace,
agent_plugins_set_enabled,
agent_poke_network,
agent_preview_copilot_models,
agent_probe,
@@ -2160,6 +2861,10 @@ ide_command::domain!(
agent_rollback,
agent_rollback_changes,
agent_send_queued_now,
agent_session_schedule_create,
agent_session_schedule_delete,
agent_session_schedule_run_now,
agent_session_schedule_set_paused,
agent_set_additional_args,
agent_set_auto_resume_once,
agent_set_command,
+102 -1
Переглянути файл
@@ -15,6 +15,52 @@ pub async fn fs_entry_kind(host: &Host, path: PathBuf) -> IdeResult<ide_vfs::Ent
.await
}
/// Rejects relative paths and any `..` parent traversal without touching the filesystem.
fn reject_parent_traversal(path: &Path) -> Option<PathBuf> {
use std::path::Component;
if !path.is_absolute() {
return None;
}
let mut out = PathBuf::new();
for comp in path.components() {
match comp {
Component::Prefix(p) => out.push(p.as_os_str()),
Component::RootDir => out.push(comp.as_os_str()),
Component::CurDir => {}
Component::ParentDir => return None,
Component::Normal(c) => out.push(c),
}
}
Some(out)
}
/// Resolves symlinks for a path inside the window's project roots and returns its canonical path.
/// Rejects relative paths, `..` parent traversal, and paths outside those roots before touching
/// the filesystem, and rejects symlink targets that canonicalize outside those roots.
#[command(trust = always)]
pub async fn fs_canonicalize(host: &Host, window: &str, path: PathBuf) -> IdeResult<ide_core::IpcPath> {
let project = host.project(window)?;
host.blocking(move || {
let Some(clean) = reject_parent_traversal(&path) else {
return Err(IdeError::invalid(format!("{}: outside the project", path.display())));
};
let raw_roots: Vec<PathBuf> = std::iter::once(project.root.clone()).chain(project.content_roots()).collect();
let canonical_roots: Vec<PathBuf> = raw_roots.iter().filter_map(|r| dunce::canonicalize(r).ok()).collect();
let mut allowed_lexical: Vec<PathBuf> = raw_roots.iter().filter_map(|r| reject_parent_traversal(r)).collect();
allowed_lexical.extend(canonical_roots.iter().cloned());
if !inside_any_root(&clean, &allowed_lexical) {
return Err(IdeError::invalid(format!("{}: outside the project", path.display())));
}
let real = dunce::canonicalize(&clean)
.map_err(|_| IdeError::not_found(format!("{}: no such file", path.display())))?;
if !inside_any_root(&real, &canonical_roots) {
return Err(IdeError::invalid(format!("{}: outside the project", path.display())));
}
Ok(real.into())
})
.await
}
#[command(trust = always)]
pub async fn fs_compare_directories(
host: &Host,
@@ -408,7 +454,9 @@ pub(crate) fn inside_any_root(path: &Path, roots: &[PathBuf]) -> bool {
#[cfg(test)]
mod tests {
use super::inside_any_root;
use super::{fs_canonicalize, inside_any_root};
use crate::{Host, HostConfig};
use ide_core::error::ErrorKind;
use std::path::{Path, PathBuf};
#[test]
@@ -421,10 +469,63 @@ mod tests {
assert!(!inside_any_root(Path::new("/home/me/.ssh/id_rsa"), &roots));
assert!(!inside_any_root(Path::new("/work/spec.pdf"), &[]));
}
#[tokio::test]
async fn fs_canonicalize_enforces_window_project_roots() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let root = base.join("project");
let outside = base.join("outside");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let inside = root.join("guide.mdx");
std::fs::write(&inside, "# Guide").unwrap();
let secret = outside.join("secret.ts");
std::fs::write(&secret, "export const secret = 1;").unwrap();
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
host.open_project("main", &root).unwrap();
// Valid path inside the window's project root succeeds with its canonical path.
let resolved = fs_canonicalize(&host, "main", inside.clone()).await.unwrap();
assert_eq!(resolved.0, dunce::canonicalize(&inside).unwrap());
// Path outside the project (existing or nonexistent) is rejected with InvalidInput before touching disk.
let outside_existing = fs_canonicalize(&host, "main", secret.clone()).await.unwrap_err();
assert_eq!(outside_existing.kind, ErrorKind::InvalidInput);
let outside_missing = fs_canonicalize(&host, "main", outside.join("does-not-exist.ts")).await.unwrap_err();
assert_eq!(outside_missing.kind, ErrorKind::InvalidInput);
// Parent traversal (`..`) is rejected even when lexically inside the project root.
let traversal = fs_canonicalize(&host, "main", root.join("../outside/secret.ts")).await.unwrap_err();
assert_eq!(traversal.kind, ErrorKind::InvalidInput);
let in_root_parent = fs_canonicalize(&host, "main", root.join("sub/../guide.mdx")).await.unwrap_err();
assert_eq!(in_root_parent.kind, ErrorKind::InvalidInput);
// Symlink inside the project pointing outside (directly or via `..`) is rejected.
#[cfg(unix)]
{
let link = root.join("link.ts");
std::os::unix::fs::symlink(&secret, &link).unwrap();
let escaped = fs_canonicalize(&host, "main", link).await.unwrap_err();
assert_eq!(escaped.kind, ErrorKind::InvalidInput);
let dir_link = root.join("dir-link");
std::os::unix::fs::symlink(&outside, &dir_link).unwrap();
let symlink_parent =
fs_canonicalize(&host, "main", dir_link.join("../outside/secret.ts")).await.unwrap_err();
assert_eq!(symlink_parent.kind, ErrorKind::InvalidInput);
}
// Unknown window with no open project is rejected.
assert!(fs_canonicalize(&host, "other", inside).await.is_err());
}
}
ide_command::domain!(
fs:
fs_canonicalize,
fs_compare_directories,
fs_copy,
fs_copy_merge,
+10 -1
Переглянути файл
@@ -116,6 +116,13 @@ pub fn apply_setting(host: &Arc<Host>, window: &str, key: &str) {
if key == "mcpServer" || key.starts_with("mcpServer.") {
host.mcp.apply(host);
}
if key == "agents" || key == "agents.automations" || key.starts_with("agents.automations.") {
let h = host.clone();
host.runtime.spawn_blocking(move || {
h.automations.sync_boot_service(&h);
h.automations.broadcast_changed(&h);
});
}
if key == "terminal" || key.starts_with("terminal.") {
super::term::apply_output_rate(host, window);
}
@@ -489,12 +496,14 @@ pub fn set_settings(
project.agents.notify_mcp_servers_changed();
}
}
// A skill or memory policy change re-resolves the modes; an idle session restarts to pick them up.
// A skill, memory, or agent-plugin policy change re-resolves the modes; an idle session restarts to pick them up.
if key == "agents"
|| key == "agents.skills"
|| key.starts_with("agents.skills.")
|| key == "agents.memory"
|| key.starts_with("agents.memory.")
|| key == "agents.plugins"
|| key.starts_with("agents.plugins.")
{
for project in affected() {
project.agents.notify_mcp_servers_changed();
+12 -7
Переглянути файл
@@ -9,7 +9,11 @@ use std::path::{Path, PathBuf};
struct DocumentsHost<'a>(&'a Documents);
impl ReplaceHost for DocumentsHost<'_> {
fn edit_file(&self, path: &Path, compute: &mut dyn FnMut(&str) -> IdeResult<Vec<TextEdit>>) -> IdeResult<u32> {
fn edit_file(
&self,
path: &Path,
compute: &mut dyn FnMut(&str) -> IdeResult<Vec<TextEdit>>,
) -> IdeResult<(u32, bool)> {
let docs = self.0;
let (doc, transient) = match docs.by_path(path) {
Some(doc) => (doc, false),
@@ -24,7 +28,7 @@ impl ReplaceHost for DocumentsHost<'_> {
let snap = docs.text_snapshot(doc)?;
let edits = compute(&snap.text)?;
if edits.is_empty() {
return Ok(0);
return Ok((0, false));
}
if docs.text_snapshot(doc)?.version != snap.version {
continue;
@@ -33,12 +37,13 @@ impl ReplaceHost for DocumentsHost<'_> {
// An open tab's file may have changed on disk before the watcher reported it:
// autosave keeps that change and leaves the replacement unsaved. A file opened
// just for this was read now.
if transient {
let disk_conflict = if transient {
docs.save(doc)?;
} else if save {
docs.autosave(doc)?;
}
return Ok(edits.len() as u32);
false
} else {
save && !docs.autosave(doc)?
};
return Ok((edits.len() as u32, disk_conflict));
}
Err(ide_core::IdeError::unavailable("the file kept changing during Replace"))
})();
+104 -2
Переглянути файл
@@ -66,6 +66,9 @@ pub struct Project {
pub detected_roots: Arc<RwLock<Vec<SourceFolder>>>,
/// The excluded folders of the workspace's other projects; see [`member_excludes`].
pub(crate) member_excludes: MemberExcludes,
/// Last reported trust state of attached workspace members, so trust changes on an
/// attached-only root still emit `ProjectTrustChanged` for the workspace window.
pub(crate) member_trust: RwLock<BTreeMap<PathBuf, bool>>,
/// Per-project cache directory (build tool sync results…).
pub cache_dir: PathBuf,
/// Pending launches and retained snapshots, scoped to each workspace project.
@@ -163,6 +166,20 @@ impl Host {
ide_build::gradle::forget_build_dirs(&root);
let detected_roots = Arc::new(RwLock::new(ide_workspace::roots::detect(&root)));
let member_excludes: MemberExcludes = Arc::new(RwLock::new(member_excludes(&settings, &root)));
let initial_member_trust: BTreeMap<PathBuf, bool> = ide_workspace::workspace::Workspace::load(&root)
.ok()
.flatten()
.map(|ws| {
ws.projects
.into_iter()
.filter(|p| p != &root)
.map(|p| {
let t = self.trust.trusted(&p).unwrap_or(false);
(p, t)
})
.collect()
})
.unwrap_or_default();
let excludes = exclude_globs(&root, &settings.effective(), &detected_roots.read(), &member_excludes.read());
let build_cache = self.local_data_dir.join("cache").join(project_key(&root)).join("build");
let extra_roots = content_roots(&settings.effective(), &root, &build_cache, trusted.load(Ordering::Acquire));
@@ -821,6 +838,7 @@ impl Host {
syntax,
detected_roots,
member_excludes,
member_trust: RwLock::new(initial_member_trust),
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
@@ -937,7 +955,21 @@ impl Host {
.with_local_external_tunnels(self.local_database_tunnels),
);
let http_history = Arc::new(ide_http::History::new(self.data_dir.join("http-history").join(project_key)));
let agents = Arc::new(ide_agent::AgentManager::new(
let agents = self.automations.take_or_build_project_agents(self, root, project_key, settings, sink);
(db, http_history, agents)
}
pub(crate) fn create_agent_manager(
&self,
root: &Path,
project_key: &str,
settings: &Arc<SettingsStore>,
sink: &SharedSink,
force_git_enabled: Option<bool>,
) -> Arc<ide_agent::AgentManager> {
let live_external =
self.automations.live_external_task_ids_for((project_key != "__chat_automations__").then_some(root));
let agents = Arc::new(ide_agent::AgentManager::new_with_live_tasks(
ide_agent::AgentPaths {
project_root: root.to_path_buf(),
store_dir: self.data_dir.join("agents").join(project_key),
@@ -960,12 +992,60 @@ impl Host {
})),
},
self.runtime.clone(),
&live_external,
));
let settings = settings.clone();
{
let settings = settings.clone();
agents.set_security_hook(Arc::new(move || settings.effective().agent_security));
}
{
let settings = settings.clone();
agents.set_new_task_approvals_hook(Arc::new(move || settings.effective().agents.new_task_approvals));
}
{
let trust = self.trust.clone();
agents.set_repo_trust_hook(Arc::new(move |repo_root| {
let _ = trust.reload();
trust.window_trusted(repo_root).unwrap_or(false)
}));
}
if project_key != "__chat_automations__" {
let trust = self.trust.clone();
agents.set_dispatch_trust_hook(Arc::new(move |proj_root, isolation| {
let _ = trust.reload();
if !trust.window_trusted(proj_root).unwrap_or(false) {
return Err(format!("Paused: project {} is not trusted (Restricted Mode).", proj_root.display()));
}
if isolation == ide_agent::Isolation::Worktree
&& let Ok(Some(canon_repo)) = ide_agent::canonical_repo_root(proj_root)
&& !trust.window_trusted(&canon_repo).unwrap_or(false)
{
return Err(format!(
"Paused: Git repository {} is not trusted (trust the repository root before running worktree automations).",
canon_repo.display()
));
}
Ok(())
}));
}
{
let automations = self.automations.clone();
let config_dir = self.config_dir.clone();
let data_dir = self.data_dir.clone();
let home_dir = self.home_dir();
let sink_c = sink.clone();
agents.set_scheduled_blocked_hook(Arc::new(move |meta, reason| {
automations.pause_blocked_scheduled_turn_raw(
&config_dir,
&data_dir,
home_dir.as_deref(),
Some(&sink_c),
meta,
reason,
);
}));
}
{
let settings = settings.clone();
agents.set_recovery_settings_hook(Arc::new(move || {
@@ -973,6 +1053,12 @@ impl Host {
(effective.agents.network_retry_window, effective.agents.resume_interrupted)
}));
}
if let Some(git_on) = force_git_enabled {
agents.set_git_enabled_hook(Arc::new(move || git_on));
} else {
let settings = settings.clone();
agents.set_git_enabled_hook(Arc::new(move || settings.effective().vcs.git.enabled));
}
let approvals = self.mcp_approvals.clone();
let secrets = self.agent_secrets.clone();
let root = root.to_path_buf();
@@ -1010,6 +1096,21 @@ impl Host {
workspace_roots: crate::ops::agent::workspace_skill_roots(&mem_root),
}
}));
let plug_settings = settings.clone();
let plug_root = root.clone();
let plug_trust = self.trust.clone();
let plug_approvals = self.plugin_approvals.clone();
agents.set_plugins_policy_hook(Box::new(move || {
let layer = |scope| plug_settings.layer(scope).agents.plugins.clone();
let workspace_trusted = plug_trust.window_trusted(&plug_root).unwrap_or(false);
ide_agent::plugins::PluginsPolicy {
user: layer(ide_workspace::settings::SettingsScope::Global),
workspace: layer(ide_workspace::settings::SettingsScope::Project),
workspace_trusted,
workspace_roots: crate::ops::agent::workspace_skill_roots(&plug_root),
approved_capabilities: plug_approvals.snapshot(),
}
}));
agents.set_mcp_servers_hook(Box::new(move || {
crate::ops::agent::session_mcp_servers(&settings, &approvals, &secrets, &root)
}));
@@ -1017,7 +1118,7 @@ impl Host {
let mcp_executable = self.mcp_executable.clone();
agents.set_mcp_executable_hook(Box::new(move || mcp_executable.read().clone()));
}
(db, http_history, agents)
agents
}
}
@@ -1127,6 +1228,7 @@ impl Host {
syntax,
detected_roots: Arc::default(),
member_excludes: Arc::default(),
member_trust: RwLock::default(),
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
+1
Переглянути файл
@@ -364,6 +364,7 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
| IdeEvent::UpdateAvailable { .. } => false,
IdeEvent::McpRequest { .. } | IdeEvent::McpRequestClosed { .. } => trusted,
IdeEvent::DbSourcesChanged
| IdeEvent::AutomationsChanged
| IdeEvent::PlotAdded { .. }
| IdeEvent::ProjectTrustChanged { .. }
| IdeEvent::Direnv { .. }
+64
Переглянути файл
@@ -87,6 +87,21 @@ impl TrustStore {
self.state.lock().clone()
}
/// Re-reads persisted `project-trust.json` from disk so trust revocations made by another
/// OpenIDEA process (e.g. desktop revoking trust while `--scheduler` or `--daemon` runs)
/// take effect immediately before scheduled execution.
pub fn reload(&self) -> IdeResult<()> {
let loaded = match std::fs::read(&self.file) {
Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| IdeError::invalid(e.to_string())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(TrustDecisions::default()),
Err(e) => Err(e.into()),
};
let mut state = self.state.lock();
let res = loaded.as_ref().map(|_| ()).map_err(Clone::clone);
*state = loaded;
res
}
pub fn trusted(&self, path: &Path) -> IdeResult<bool> {
let root = dunce::canonicalize(path)?;
let decisions = self.decisions()?;
@@ -237,6 +252,38 @@ impl McpServerApprovals {
}
}
/// Agent plugin capability approvals ([`ide_agent::plugins::capability_approval_key`]) the user
/// granted on this machine. Kept out of settings: enablement lives in each harness's own
/// configuration, and approving what a plugin runs is a per-machine decision.
pub struct PluginCapabilityApprovals {
file: PathBuf,
approved: Mutex<std::collections::BTreeSet<String>>,
}
impl PluginCapabilityApprovals {
pub fn load(data: &Path) -> Self {
let file = data.join("agent-plugin-approvals.json");
let approved = std::fs::read(&file).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
Self { file, approved: Mutex::new(approved) }
}
pub fn snapshot(&self) -> std::collections::BTreeSet<String> {
self.approved.lock().clone()
}
pub fn approve(&self, key: String) -> IdeResult<()> {
let mut approved = self.approved.lock();
if approved.contains(&key) {
return Ok(());
}
let mut next = approved.clone();
next.insert(key);
persist(&self.file, &next)?;
*approved = next;
Ok(())
}
}
impl crate::Host {
pub async fn set_project_trust(&self, path: &Path, trusted: bool, folder: bool) -> IdeResult<()> {
self.trust.decide(path, trusted, folder)?;
@@ -251,6 +298,23 @@ impl crate::Host {
let trusted = self.trust.window_trusted(&project.root).unwrap_or(false);
let roots = project.content_roots();
let previous = project.trusted.swap(trusted, std::sync::atomic::Ordering::AcqRel);
// Notify workspace windows when an attached-only member's trust changes, even if the
// container window's own `window_trusted` boolean did not flip.
if let Ok(Some(workspace)) = ide_workspace::workspace::Workspace::load(&project.root) {
let mut known = project.member_trust.write();
let current_members: std::collections::BTreeSet<PathBuf> =
workspace.projects.into_iter().filter(|m| m != &project.root).collect();
known.retain(|k, _| current_members.contains(k));
for member in current_members {
let member_trusted = self.trust.trusted(&member).unwrap_or(false);
if known.insert(member.clone(), member_trusted) != Some(member_trusted) {
project.sink.emit(ide_core::IdeEvent::ProjectTrustChanged {
root: member.into(),
trusted: member_trusted,
});
}
}
}
if previous == trusted {
continue;
}
File diff suppressed because it is too large. Load diff
+225
Переглянути файл
@@ -2291,3 +2291,228 @@ async fn debugger_breakpoints_update_by_id_and_clear_by_file() {
let removed = h.json("xdebug_remove_breakpoint", json!({"owner": "agent"})).await;
assert_eq!(removed["count"], 2);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn agent_plugins_ipc_installs_for_a_harness_and_projects_native_children() {
ide_ssh::secrets::testing::use_memory_store();
let h = Harness::new();
// Prepare a local marketplace directory outside the workspace with 1 plugin (`cloud-kit`)
let local_mkt = h.tmp.path().join("local-mkt");
let plug_src = local_mkt.join("plugins/cloud-kit");
std::fs::create_dir_all(local_mkt.join(".claude-plugin")).unwrap();
std::fs::create_dir_all(plug_src.join(".claude-plugin")).unwrap();
std::fs::create_dir_all(plug_src.join("skills/cloud-diag")).unwrap();
std::fs::create_dir_all(plug_src.join("rules")).unwrap();
std::fs::write(
local_mkt.join(".claude-plugin/marketplace.json"),
r#"{"name":"local-mkt","owner":{"name":"Test"},"plugins":[{"name":"cloud-kit","source":"./plugins/cloud-kit","description":"Cloud diagnostics"}]}"#,
)
.unwrap();
std::fs::write(
plug_src.join(".claude-plugin/plugin.json"),
r#"{"name":"cloud-kit","version":"1.0.0","description":"Cloud diagnostics","userConfig":{"region":{"type":"string","default":"us-west-2"},"apiKey":{"type":"string","sensitive":true}}}"#,
)
.unwrap();
std::fs::write(
plug_src.join("skills/cloud-diag/SKILL.md"),
"---\nname: cloud-diag\ndescription: Diagnose cloud health\n---\n",
)
.unwrap();
std::fs::write(
plug_src.join("rules/cloud.mdc"),
"---\nglobs: infra/**/*.tf\n---\nTag all cloud resources with owner.\n",
)
.unwrap();
std::fs::write(
plug_src.join(".mcp.json"),
r#"{"mcpServers":{"cloud-mcp":{"command":"node","args":["${CLAUDE_PLUGIN_ROOT}/index.js","--region=${user_config.region}"],"env":{"CLOUD_KEY":"${user_config.apiKey}"}}}}"#,
)
.unwrap();
// 1. Untrusted workspace rejects Workspace-scope plugin installation:
let mkt_str = local_mkt.to_string_lossy().into_owned();
let browsed = ide_host::ops::agent::agent_plugins_browse_marketplace(
&h.host,
"main",
mkt_str.clone(),
ide_core::RequestId(1),
)
.await
.unwrap();
assert_eq!(browsed.candidates.len(), 1);
assert_eq!(browsed.candidates[0].name, "cloud-kit");
let preview = ide_host::ops::agent::agent_plugins_preview(
&h.host,
"main",
browsed.candidates[0].source_spec.clone(),
None,
Some("local-mkt".into()),
ide_core::RequestId(2),
)
.await
.unwrap();
assert!(preview.capabilities.requires_consent);
assert_eq!(preview.marketplace_source.as_deref(), dunce::canonicalize(&local_mkt).unwrap().to_str());
let untrusted_err = ide_host::ops::agent::agent_plugins_install(
&h.host,
"main",
ide_agent::InstallAgentPluginRequest {
source_kind: "local".into(),
owner: None,
repo: None,
git_ref: None,
tree_sha: preview.tree_sha.clone(),
commit_sha: None,
subpath: String::new(),
local_path: preview.local_path.clone(),
marketplace: Some("local-mkt".into()),
marketplace_source: preview.marketplace_source.clone(),
scope: ide_agent::McpScope::Workspace,
harness: "claude".into(),
approve_capabilities: true,
approved_capability_hash: None,
confirm_warnings: true,
overwrite: false,
},
ide_core::RequestId(3),
)
.await;
assert!(untrusted_err.is_err(), "untrusted workspace cannot install workspace plugins");
let untrusted_user_err = ide_host::ops::agent::agent_plugins_install(
&h.host,
"main",
ide_agent::InstallAgentPluginRequest {
source_kind: "local".into(),
owner: None,
repo: None,
git_ref: None,
tree_sha: preview.tree_sha.clone(),
commit_sha: None,
subpath: String::new(),
local_path: preview.local_path.clone(),
marketplace: Some("local-mkt".into()),
marketplace_source: preview.marketplace_source.clone(),
scope: ide_agent::McpScope::User,
harness: "claude".into(),
approve_capabilities: true,
approved_capability_hash: None,
confirm_warnings: true,
overwrite: false,
},
ide_core::RequestId(30),
)
.await;
assert!(untrusted_user_err.is_err(), "local install from an untrusted workspace requires trust");
assert!(
ide_host::ops::agent::agent_plugins_remove_marketplace(
&h.host,
"main",
ide_agent::McpScope::Workspace,
"acme/plugins".into(),
)
.await
.is_err(),
"an untrusted workspace cannot edit workspace marketplaces"
);
// 2. Trust the workspace, install with capability approval, and verify live projection across Skills, MCP, and Memory!
h.trust().await;
let cat = ide_host::ops::agent::agent_plugins_install(
&h.host,
"main",
ide_agent::InstallAgentPluginRequest {
source_kind: "local".into(),
owner: None,
repo: None,
git_ref: None,
tree_sha: preview.tree_sha.clone(),
commit_sha: None,
subpath: String::new(),
local_path: preview.local_path.clone(),
marketplace: Some("local-mkt".into()),
marketplace_source: preview.marketplace_source.clone(),
scope: ide_agent::McpScope::Workspace,
harness: "claude".into(),
approve_capabilities: true,
approved_capability_hash: preview.capabilities.capability_hash.clone(),
confirm_warnings: true,
overwrite: true,
},
ide_core::RequestId(4),
)
.await
.unwrap();
let installed = cat.plugins.iter().find(|s| s.plugin.name == "cloud-kit").expect("cloud-kit in catalog");
assert!(installed.enabled);
assert!(!installed.consent_required);
let plug_id = installed.plugin.id.clone();
let native_settings: Value =
serde_json::from_str(&std::fs::read_to_string(h.root.join(".claude/settings.json")).unwrap()).unwrap();
assert_eq!(native_settings["enabledPlugins"]["cloud-kit@local-mkt"], true);
assert_eq!(native_settings["extraKnownMarketplaces"]["local-mkt"]["source"]["source"], "directory");
assert_eq!(
native_settings["extraKnownMarketplaces"]["local-mkt"]["source"]["path"],
dunce::canonicalize(&local_mkt).unwrap().to_string_lossy().as_ref()
);
// Projected into Skills, MCP Connections, and Memory for inspectability:
let skills = ide_host::ops::agent::agent_skills_list(&h.host, "main").await.unwrap();
assert!(
skills.iter().any(|s| s.skill.name == "cloud-diag" && s.skill.plugin_id.as_deref() == Some(plug_id.as_str()))
);
let mcps = ide_host::ops::agent::agent_mcp_list(&h.host, "main").unwrap();
let cloud_mcp = mcps.iter().find(|m| m.name == "cloud-mcp").expect("projected MCP server");
assert_eq!(cloud_mcp.plugin_id.as_deref(), Some(plug_id.as_str()));
assert!(cloud_mcp.args.iter().any(|a| a == "--region=us-west-2"));
let mems = ide_host::ops::agent::agent_memory_list(&h.host, "main").await.unwrap();
assert!(mems.entries.iter().any(|e| e.entry.plugin_id.as_deref() == Some(plug_id.as_str())));
// 3. Disabling the parent bundle atomically drops its projected skill, MCP server, and rule!
ide_host::ops::agent::agent_plugins_set_enabled(
&h.host,
"main",
plug_id.clone(),
ide_agent::McpScope::Workspace,
false,
false,
None,
)
.await
.unwrap();
assert!(
!ide_host::ops::agent::agent_skills_list(&h.host, "main")
.await
.unwrap()
.iter()
.any(|s| s.skill.name == "cloud-diag")
);
assert!(!ide_host::ops::agent::agent_mcp_list(&h.host, "main").unwrap().iter().any(|m| m.name == "cloud-mcp"));
assert!(
!ide_host::ops::agent::agent_memory_list(&h.host, "main").await.unwrap().entries.iter().any(|e| e
.entry
.plugin_id
.as_deref()
== Some(plug_id.as_str()))
);
// 4. Approving capabilities other than the ones shown is refused.
let stale = ide_host::ops::agent::agent_plugins_set_enabled(
&h.host,
"main",
plug_id.clone(),
ide_agent::McpScope::Workspace,
true,
true,
Some("0000".into()),
)
.await
.unwrap_err();
assert!(stale.message.contains("changed since they were shown"), "{stale:?}");
}
+11 -1
Переглянути файл
@@ -165,6 +165,8 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
std::fs::write(&stale_path, "TOKEN\nexternal\n").unwrap();
let mut search = query("TOKEN", false);
search.scope = SearchScope::Directory { path: scope.into() };
let summary = Arc::new(Mutex::new(None));
let out = summary.clone();
ops::search::replace_in_files(
&host,
"main",
@@ -174,10 +176,18 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
false,
vec![],
true,
ops::Channel::new(|_| {}),
ops::Channel::new(move |e| {
if let ReplaceEvent::Done { summary } = e {
*out.lock().unwrap() = Some(summary);
}
}),
)
.await
.unwrap();
let summary = summary.lock().unwrap().take().expect("Done");
// #7273: the stale tab is replaced (counted in `files`) and reported as not saved; the
// user's own unsaved buffer is not.
assert_eq!((summary.files, summary.replacements, summary.failed, summary.unsaved), (4, 4, 0, 1));
let disk = |name: &str| std::fs::read_to_string(root.join(name)).unwrap();
assert_eq!(disk("previewed.txt"), "DONE\n");
assert_eq!(disk("closed.txt"), "DONE\n");
+54
Переглянути файл
@@ -417,3 +417,57 @@ async fn a_project_created_with_new_project_is_trusted() {
std::fs::create_dir(&sibling).unwrap();
assert!(!host.trust.status(&sibling).unwrap().trusted);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn attached_container_member_trust_change_emits_event_for_workspace() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let container = base.join("ws");
let member_a = base.join("member-a");
let member_b = base.join("member-b");
for path in [&container, &member_a, &member_b] {
std::fs::create_dir_all(path).unwrap();
}
ide_workspace::workspace::Workspace::save(&container, "WS", vec![member_a.clone(), member_b.clone()], true)
.unwrap();
let events = Arc::new(parking_lot::Mutex::new(Vec::<ide_core::IdeEvent>::new()));
let captured = events.clone();
let mut cfg = common::host_config(&base.join("app"));
cfg.sink_for = Box::new(move |_window| {
let captured = captured.clone();
Arc::new(move |ev| captured.lock().push(ev))
});
let host = Arc::new(Host::new(cfg));
host.trust.decide(&container, true, false).unwrap();
host.trust.decide(&member_a, true, false).unwrap();
host.trust.decide(&member_b, true, false).unwrap();
host.open_project("main", &container).unwrap();
events.lock().clear();
// Revoking trust on an attached-only member keeps the container window trusted, yet still emits
// ProjectTrustChanged for that member so open previews recheck its trust immediately.
host.set_project_trust(&member_b, false, false).await.unwrap();
assert!(
events.lock().iter().any(|ev| matches!(
ev,
ide_core::IdeEvent::ProjectTrustChanged { root, trusted: false } if root.0 == member_b
)),
"expected ProjectTrustChanged(member_b, false), got {:?}",
*events.lock()
);
events.lock().clear();
host.set_project_trust(&member_b, true, false).await.unwrap();
assert!(
events.lock().iter().any(|ev| matches!(
ev,
ide_core::IdeEvent::ProjectTrustChanged { root, trusted: true } if root.0 == member_b
)),
"expected ProjectTrustChanged(member_b, true), got {:?}",
*events.lock()
);
host.shutdown().await;
}
+6 -18
Переглянути файл
@@ -230,25 +230,13 @@ pub fn default_simulator(dir: &Path) -> Option<String> {
pick_simulator(&String::from_utf8_lossy(&out.stdout))
}
/// The same rule as the toolbar's default (`currentIosSimulator`), over the same ordering.
fn pick_simulator(json: &str) -> Option<String> {
let devices: serde_json::Value = serde_json::from_str(json).ok()?;
let mut runtimes: Vec<(Vec<u32>, &Vec<serde_json::Value>)> = devices
.get("devices")?
.as_object()?
.iter()
.filter_map(|(runtime, list)| {
let version = runtime.strip_prefix("com.apple.CoreSimulator.SimRuntime.iOS-")?;
Some((version.split('-').filter_map(|n| n.parse().ok()).collect(), list.as_array()?))
})
.collect();
runtimes.sort_by(|a, b| b.0.cmp(&a.0));
let all = || runtimes.iter().flat_map(|(_, list)| list.iter());
let field = |d: &serde_json::Value, key: &str| d.get(key).and_then(|v| v.as_str()).unwrap_or_default().to_owned();
all()
.find(|d| field(d, "state") == "Booted")
.or_else(|| all().find(|d| field(d, "name").starts_with("iPhone")))
.map(|d| field(d, "udid"))
.filter(|udid| !udid.is_empty())
let list = crate::simulator::parse_list(json).ok()?;
list.iter()
.find(|d| d.state == "Booted")
.or_else(|| list.iter().find(|d| d.name.starts_with("iPhone")))
.map(|d| d.udid.clone())
}
/// The run configuration parameter that holds the simulator's UDID. Empty means
+19 -4
Переглянути файл
@@ -147,7 +147,7 @@ pub fn project_libraries_stream(
// `exclude`) without its own keeps none, as RustRover leaves crates it doesn't attach.
let locked = workspace.canonicalize().unwrap_or_else(|_| workspace.clone()) != project
&& !workspace.join("Cargo.lock").is_file();
let batch = rust_groups(&workspace, &settings, locked, cancel);
let batch = rust_groups(&workspace, &project, &settings, locked, cancel);
if !cancel.is_cancelled() && !batch.is_empty() {
on_groups(batch.clone());
groups.extend(batch);
@@ -867,7 +867,13 @@ pub(crate) fn package_dependencies(package_json: &str) -> Vec<String> {
// ------------------------------------------------------------------ rust
/// `locked`: `cargo metadata --locked`, which fails instead of writing a Cargo.lock.
fn rust_groups(root: &Path, s: &Settings, locked: bool, cancel: &CancellationToken) -> Vec<LibraryGroup> {
fn rust_groups(
root: &Path,
project: &Path,
s: &Settings,
locked: bool,
cancel: &CancellationToken,
) -> Vec<LibraryGroup> {
let Some(files) = manifests(root, CARGO_MANIFESTS) else { return Vec::new() };
if !root.join("Cargo.toml").is_file() {
return Vec::new();
@@ -897,7 +903,7 @@ fn rust_groups(root: &Path, s: &Settings, locked: bool, cancel: &CancellationTok
args.push("--locked");
}
let json = query_in_cancellable(&cargo, &args, root, &[], GRAPH_TIMEOUT, cancel)?;
let roots = parse_cargo_metadata(&json)?;
let roots = outside_project(parse_cargo_metadata(&json)?, project);
Some(group("Cargo dependencies", "cargo", named_roots(roots)).into_iter().collect())
});
// An edited manifest that names crates not downloaded yet fails offline until the next
@@ -950,6 +956,13 @@ fn cargo_lock_roots(root: &Path, home: &Path) -> Vec<(String, PathBuf)> {
.collect()
}
/// Drops the path dependencies that lie inside the open project: a sibling crate of a separate
/// workspace (`vpn-core = { path = ".." }`) is the project's own code, not an external library.
/// A `vendor` copy stays a library, as for Go modules.
pub(crate) fn outside_project(roots: Vec<(String, PathBuf)>, project: &Path) -> Vec<(String, PathBuf)> {
roots.into_iter().filter(|(_, dir)| !is_project_source(project, dir)).collect()
}
/// `(name version, source dir)` of the non-workspace packages in `cargo metadata` output, by name.
pub(crate) fn parse_cargo_metadata(json: &str) -> Option<Vec<(String, PathBuf)>> {
#[derive(Deserialize)]
@@ -1331,7 +1344,9 @@ mod go_cache_tests {
let mut settings = Settings::default();
settings.languages.rust.toolchain = "tools".into();
assert!(project_libraries(root, &settings, &[]).is_empty());
let source = root.join("local");
// Outside the project: a path dependency inside it is the project's own code.
let external = tempfile::tempdir().unwrap();
let source = external.path().join("local");
std::fs::create_dir(&source).unwrap();
let json = serde_json::json!({"packages": [{"id":"dep", "name":"dep", "version":"1.0.0", "source":null,
"manifest_path":source.join("Cargo.toml")}], "workspace_members":[]});
+16
Переглянути файл
@@ -2475,6 +2475,22 @@ fn cargo_metadata_lists_registry_and_non_workspace_path_dependencies() {
assert!(crate::libraries::parse_cargo_metadata("error: no Cargo.toml").is_none());
}
#[test]
fn cargo_path_dependencies_inside_the_project_are_not_libraries() {
let tmp = tempfile::tempdir().unwrap();
let project = tmp.path().canonicalize().unwrap();
let roots = vec![
("vpn-core 0.3.37".to_owned(), project.clone()),
("sibling 0.1.0".to_owned(), project.join("crates/sibling")),
("serde 1.0.200".to_owned(), project.parent().unwrap().join("registry/serde-1.0.200")),
("vendored 1.0.0".to_owned(), project.join("vendor/vendored")),
("other 0.1.0".to_owned(), std::path::PathBuf::from(format!("{}-other", project.display()))),
];
let kept = crate::libraries::outside_project(roots, &project);
let names: Vec<_> = kept.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(names, ["serde 1.0.200", "vendored 1.0.0", "other 0.1.0"]);
}
#[test]
fn go_modules_skip_the_main_module_and_missing_downloads() {
let out = r#"{"Path":"example.com/app","Main":true,"Dir":"/p"}
+12 -3
Переглянути файл
@@ -57,6 +57,9 @@ pub struct ReplaceSummary {
pub files: u32,
pub replacements: u32,
pub failed: u32,
/// Files changed in the editor but not saved because the file changed on disk first;
/// counted in `files` too.
pub unsaved: u32,
pub cancelled: bool,
pub elapsed_ms: u32,
}
@@ -72,9 +75,14 @@ pub struct ReplacePreview {
/// Where replacements are applied. `compute` receives the file's current text
/// (unsaved editor buffer included) and returns the edits for it; the host
/// applies them atomically and returns how many it applied.
/// applies them atomically and returns how many it applied, and whether they were left
/// unsaved because the file changed on disk.
pub trait ReplaceHost: Sync {
fn edit_file(&self, path: &Path, compute: &mut dyn FnMut(&str) -> IdeResult<Vec<TextEdit>>) -> IdeResult<u32>;
fn edit_file(
&self,
path: &Path,
compute: &mut dyn FnMut(&str) -> IdeResult<Vec<TextEdit>>,
) -> IdeResult<(u32, bool)>;
}
/// IDEA's "Preserve case": `FOO` → upper-cases the replacement, `Foo` →
@@ -275,10 +283,11 @@ pub fn replace_files_in_context(
edits_except(text, query, replacement, preserve, only, skip, found.as_deref())
});
match result {
Ok(n) => {
Ok((n, disk_conflict)) => {
if n > 0 {
summary.files += 1;
summary.replacements += n;
summary.unsaved += u32::from(disk_conflict);
}
on_event(ReplaceEvent::File { path: target.path.clone(), replacements: n, done, total });
}
+10 -3
Переглянути файл
@@ -51,7 +51,11 @@ impl FakeDocs {
}
impl ReplaceHost for FakeDocs {
fn edit_file(&self, path: &Path, compute: &mut dyn FnMut(&str) -> IdeResult<Vec<TextEdit>>) -> IdeResult<u32> {
fn edit_file(
&self,
path: &Path,
compute: &mut dyn FnMut(&str) -> IdeResult<Vec<TextEdit>>,
) -> IdeResult<(u32, bool)> {
let mut files = self.files.lock().unwrap();
let text = files.get(path).cloned().ok_or_else(|| IdeError::not_found("no such file"))?;
let edits = compute(&text)?;
@@ -62,7 +66,7 @@ impl ReplaceHost for FakeDocs {
if let Some(c) = &self.cancel_after_first {
c.cancel();
}
Ok(edits.len() as u32)
Ok((edits.len() as u32, false))
}
}
@@ -125,7 +129,10 @@ fn replace_files_one_step_per_file_with_progress() {
assert_eq!(docs.text("a"), "bar bar");
assert_eq!(docs.text("c"), "x bar");
assert_eq!(*docs.steps.lock().unwrap(), vec![(PathBuf::from("a"), 2), (PathBuf::from("c"), 1)]);
assert_eq!((summary.files, summary.replacements, summary.failed, summary.cancelled), (2, 3, 1, false));
assert_eq!(
(summary.files, summary.replacements, summary.failed, summary.unsaved, summary.cancelled),
(2, 3, 1, 0, false)
);
let events = events.lock().unwrap();
assert_eq!(events.len(), 4);
assert!(matches!(&events[0], ReplaceEvent::File { replacements: 2, done: 1, total: 4, .. }));
+21
Переглянути файл
@@ -78,6 +78,8 @@ const USER_ONLY: &[&[&str]] = &[
&["agents", "confirmTerminateOnClose"],
// OS notification centre: machine-local; projects must not enable/disable.
&["notifications", "systemNotifications"],
// MDX JSX execution policy: projects must never opt themselves into automatic execution.
&["languages", "markdown", "mdxExecution"],
];
/// The [`USER_ONLY`] setting that writing `value` at `key` would set, as a dotted key.
@@ -1720,6 +1722,25 @@ mod tests {
assert!(s.agents.show_cost);
}
#[test]
fn mdx_execution_is_a_user_setting() {
let tmp = tempfile::tempdir().unwrap();
let config = tmp.path().join("config");
let project = tmp.path().join("project");
std::fs::create_dir_all(project.join(".openidea")).unwrap();
std::fs::write(project.join(".openidea/settings.toml"), "[languages.markdown]\nmdxExecution = \"trusted\"\n")
.unwrap();
let settings = SettingsStore::load(&config, Some(&project));
use ide_core::settings::MdxExecutionPolicy;
assert_eq!(settings.effective().languages.markdown.mdx_execution, MdxExecutionPolicy::Ask);
assert!(settings.set(SettingsScope::Project, "languages.markdown.mdxExecution", json!("trusted")).is_err());
assert!(
settings.set(SettingsScope::Project, "languages.markdown", json!({"mdxExecution": "trusted"})).is_err()
);
let s = settings.set(SettingsScope::Global, "languages.markdown.mdxExecution", json!("trusted")).unwrap();
assert_eq!(s.languages.markdown.mdx_execution, MdxExecutionPolicy::Trusted);
}
#[test]
fn new_task_approvals_are_a_user_setting() {
let tmp = tempfile::tempdir().unwrap();
+2
Переглянути файл
@@ -69,6 +69,8 @@ const NEVER: &[&[&str]] = &[
&["agents", "mcpServers"],
&["agents", "skills"],
&["agents", "memory"],
&["agents", "plugins"],
&["agents", "automations"],
&["terminal", "shellPath"],
&["toolDownloads", "githubMirror"],
&["notifications", "systemNotifications"],
+21
Переглянути файл
@@ -161,6 +161,17 @@ In the composer, `/skills` (or the **Add Context** menu) opens the per-session p
- **Per-file modes (`Auto`, `Always`, `Off`)**: `Off` keeps a file out of new sessions; `Always` also passes another agent's file to every agent (for example a Cursor rule to Claude Code).
- **Promote to AGENTS.md**: move a learned auto-memory note into `AGENTS.md`, under a heading of your choice, so every agent reads it.
### Agent plugins
**Settings › Agents › Plugins** manages composite agent bundles in each harness's own folders, grouped by harness and scope. It discovers Claude Code, Copilot, Codex, and Gemini CLI plugins where those CLIs install them.
- **Native enablement**: installs use each harness's own store (`~/.claude/plugins/cache/<marketplace>/<plugin>/<version>`, `~/.copilot/installed-plugins/<marketplace>/<plugin>`, `~/.codex/plugins/cache/<marketplace>/<plugin>/<version>`, or `~/.gemini/extensions/<extension>`). The toggle changes only the record that harness's own `enable`/`disable` command changes: Claude `enabledPlugins`; Copilot's `installedPlugins` entry (plus `enabledPlugins["<plugin>@<marketplace>"]` for marketplace plugins); `[plugins."<plugin>@<marketplace>"]` in Codex `config.toml`; or a Gemini `extension-enablement.json` rule (Gemini's user scope is a rule for your home folder, as `gemini extensions disable` writes). Workspace rows edit the owning project's `.claude/settings.json`, `.github/copilot/settings.json`, or `.codex/config.toml`. Unrelated content and comments are kept. OpenIDEA does not stage or translate an uninstalled plugin into another harness.
- **Marketplaces**: Claude Code and Codex install only from a named marketplace. Codex installs need a marketplace Codex knows: one already added with `codex plugin marketplace add`, or a local marketplace folder, which OpenIDEA registers the same way. Copilot enables a plugin for a single repository only through that repository's settings, so workspace installs need a marketplace too.
- **Consent** is remembered on this machine, separately from settings, and is tied to what the plugin runs.
- **Native layouts** follow each CLI's published contract: [Claude Code plugin storage](https://code.claude.com/docs/en/plugins/loading.md#find-plugins-on-disk), [Copilot CLI plugin files and settings](https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-plugin-reference#file-locations), [Codex cache storage](https://github.com/openai/codex/blob/main/codex-rs/core-plugins/src/store.rs) and [plugin config](https://github.com/openai/codex/blob/main/codex-rs/config/src/types.rs), and [Gemini extension enablement](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/config/extensions/extensionEnablement.ts).
- **Child provenance**: Skills, MCP Connections, and Memory entries contributed by a bundle show `from plugin <name>`. Copilot plugin skills are grouped under their bundle.
- **Install from a marketplace or repository**: pick the target harness before installation. Unsupported harnesses are disabled unless the bundle ships a native manifest they read. Local folders must be absolute, `~/…`, or `./…` relative to the project. OpenIDEA pins the previewed GitHub commit and tree (or the local folder's content), scans the contents, and requires capability consent before enabling plugins with executable MCP processes or hooks; the consent covers MCP commands, hook files (default locations, paths named in the manifest, and inline manifest hooks), and the scripts those hooks reference, so changing any of them asks again.
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply.
For a walkthrough of how **Plugins**, **Memory**, **MCP**, **Tools**, and **Skills** interact across a task's lifecycle—and what enters the LLM context window—see [Agent resources and lifecycle](/en/guide/agent-resources).
@@ -205,6 +216,16 @@ MY_AGENT_LOG = "info"
The file name (without `.toml`) is the agent's id. A file named after a built-in agent (`gemini.toml`, `claude.toml`…) replaces that agent's command; this is what the **Built-in** tab writes when you set a custom executable or environment. Files that fail to parse are skipped and logged.
## Agent automations
Open **Automations** from the **Agents** tool window header (or **Settings › Agents › Automations**) to schedule recurring prompts locally or on a remote `openidea-server --daemon` host without any cloud service:
- **Schedules & triggers**: choose **Weekdays**, **Daily**, **Weekly**, **Hourly**, a 5-field **Cron expression** with an IANA time zone, **One-shot**, or **Manual only**, and preview the next firing times live.
- **Workspace isolation & continuity**: run each tick in an **Isolated Git worktree** (automatically deleting zero-diff worktrees while retaining transcripts), on your **Local checkout**, or as **Chat only**, either starting a **Fresh session** per run or reusing a **Rolling session**.
- **In-session `/loop` & Send Later**: inside any active conversation, click the clock button next to **Send** or type `/loop 10m <prompt>`, `/after 1h <prompt>`, or `/automate <prompt>` to queue delayed or repeating turns.
- **Reboot & background survival**: by default, schedules run while OpenIDEA or `openidea-server --daemon` is running (missed runs follow your configured missed-schedule policy). Turn on **Keep automations running when OpenIDEA is closed** in **Automations** (or **Settings › Agents › Automations**) to register a lightweight user login service (`--scheduler`) while schedules are active; turning it off or pausing the last schedule unregisters it automatically.
- **Portable `.automation.md`**: export or import YAML-frontmatter `.automation.md` templates; imported schedules start paused until you review and enable them.
## Limits
- Agents run on your machine with your credentials and your subscriptions or API keys; OpenIDEA does not proxy or meter them.
+1 -1
Переглянути файл
@@ -90,7 +90,7 @@ Method breakpoints and field watchpoints need an adapter that supports DAP funct
**View Breakpoints…** (`⌘⇧F8` / `Ctrl+Shift+F8`) lists every breakpoint in the project. From there you can enable, edit, remove and jump to breakpoints, toggle **Mute breakpoints** (skip all of them without removing them), and set exception filters. **Remove All Breakpoints** clears the list. **Remove All Breakpoints In The Current File** (Find Action) removes only the line, method and field breakpoints of the file in the active editor.
Breakpoints are saved per project and kept across restarts. A breakpoint the adapter could not place is shown as unverified.
Breakpoints are saved per project and kept across restarts. A breakpoint the adapter could not place is shown as unverified; hover it in the gutter to see why. With lldb-dap or CodeLLDB that is usually code not loaded yet, or debug info that records the file under another path (a symlink, or `/tmp` for `/private/tmp`), which a `sourceMap` in the launch configuration maps back. Xcode schemes under `/private/tmp`, `/private/var` or `/private/etc` get that mapping automatically.
## Step through code
+1 -1
Переглянути файл
@@ -16,7 +16,7 @@ Problems are underlined in the editor and marked in the scrollbar. The widget at
| **Error Description** | `⌘F1` | `Ctrl+F1` |
| **Problems** tool window | `⌘6` | `Alt+6` |
The **Problems** tool window has two tabs: **File** (the current editor) and **Project Errors**. Its options menu sorts by severity or name, shows a preview and can autoscroll to the source.
The **Problems** tool window has two tabs: **File** (the current editor) and **Project Errors**. Problems are grouped by file; the toolbar has **Expand All** / **Collapse All** for the files. Its options menu sorts by severity or name, shows a preview and can autoscroll to the source.
## Quick fixes and intentions
+6 -4
Переглянути файл
@@ -82,7 +82,7 @@ OpenIDEA recognizes `Dockerfile`, `Containerfile`, `Dockerfile.<name>`, `*.docke
The gutter shows run icons:
- On a Dockerfile `FROM` line: **Run '…'** (build, then run) and **Build Image '…'** for the final stage, or **Build Stage '…'** for a named intermediate stage.
- On a Dockerfile `FROM` line: **Run '…'** (build the image, start the container in the background and open it in **Services** with its log) and **Build Image '…'** for the final stage, or **Build Stage '…'** for a named intermediate stage.
- In a Compose file: **Compose Up (All Services)** on `services:`, and **Compose Up '…'** on each service.
- **Modify Run Configuration…** opens the generated configuration so you can save and change it.
@@ -94,20 +94,22 @@ The image tag is derived from the folder name (`My App` becomes `my-app:latest`)
<AccordionGroup>
<Accordion title="Dockerfile">
Builds an image and, with **Run built image** checked, runs a container from it.
Builds an image and, with **Run built image** checked, runs a container from it. The container runs in the background by default (**Run in the background (-d)** is checked): building and starting are two separate steps, the Run window keeps the build output, and once the command line returns the container lives in the Docker daemon while the **Services** tool window opens on it with its **Log**. Closing the window or the IDE leaves it running. Uncheck the option to run attached, where **Stop** runs `docker stop`; background containers are stopped from the **Services** tool window.
**Server** picks the Docker daemon for both the build and the run (the `docker` CLI gets that connection's `DOCKER_HOST`): with a remote connection the image is built on the remote daemon, so no local daemon is needed — only the `docker` CLI.
**Dockerfile** (relative to the project root), **Context folder**, **Image tag**, **Build stage**, **Build args** (`KEY=value; OTHER=value`), **Build options** (for example `--no-cache --platform linux/amd64`), **Run built image**, **Command**, plus the container fields below.
</Accordion>
<Accordion title="Docker Image">
Runs a container from an image: **Image ID or name**, **Pull the image before running**, **Command**, plus the container fields below.
Runs a container from an image, also in the background by default and opened in **Services**: **Image ID or name**, **Pull the image before running**, **Command**, plus the container fields below.
</Accordion>
<Accordion title="Docker Compose">
Starts Compose services: **Compose files** (separated by `;`), **Services** (empty for all), **Project name**, **Run in the background (-d)**, **Build images before starting (--build)**, **Up options**. Stopping an attached run runs `docker compose down`.
</Accordion>
</AccordionGroup>
Container fields: **Container name**, **Bind ports** (`8080:80, 5005:5005`), **Bind mounts** (`./data:/data; cache:/root/.cache`), **Container environment**, **Run options** (for example `--rm --network host`). Before each run, a previous container with the same name is removed; **Stop** runs `docker stop`.
Container fields: **Container name**, **Bind ports** (`8080:80, 5005:5005`), **Bind mounts** (`./data:/data; cache:/root/.cache`), **Container environment**, **Run options** (for example `--rm --network host`). Before each run, a previous container with the same name is removed; **Stop** of an attached run runs `docker stop`, background containers are stopped from **Services**.
## Deployment (SFTP)
+4
Переглянути файл
@@ -47,6 +47,10 @@ Supported lines:
`set clipboard+=unnamedplus` (or `unnamed`) also copies yanks, deletes and changes without a register to the system clipboard. The `"+` register always reads and writes the system clipboard.
`set number` (`nu`) and `set relativenumber` (`rnu`) switch the line numbers of every editor, as in IdeaVim: both together show hybrid numbers, `relativenumber` alone shows 0 on the caret line, and `nonumber norelativenumber` hides them. An option the file does not set follows **Settings › Editor › General › Appearance › Show line numbers**, and nothing is written to Settings.
`<C-g>u` on the right-hand side of an Insert-mode mapping breaks the undo sequence, as in Vim.
Anything else (functions, `if`, `autocmd`, plugin commands) is reported as ignored and never executed.
### Map keys to IDE actions
+21
Переглянути файл
@@ -161,6 +161,17 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
- **单个文件的模式(`自动`、`始终`、`关闭`)**:`关闭` 让该文件不进入新会话;`始终` 还会把其他智能体的文件交给所有智能体(例如把 Cursor 规则交给 Claude Code)。
- **提升到 AGENTS.md**:把自动学到的记忆笔记移入 `AGENTS.md`(可指定标题),让所有智能体都能读到。
### 智能体插件
**设置 › 智能体 › 插件** 按智能体与作用域汇总各 CLI 自己安装目录中的复合插件包,支持 Claude Code、Copilot、Codex 和 Gemini CLI。
- **原生启停**:安装使用各智能体自己的目录(例如 `~/.claude/plugins/cache/<marketplace>/<plugin>/<version>`、`~/.copilot/installed-plugins/<marketplace>/<plugin>`、`~/.codex/plugins/cache/<marketplace>/<plugin>/<version>` 或 `~/.gemini/extensions/<extension>`)。开关只修改该智能体自己的 `enable`/`disable` 命令会修改的记录:Claude 的 `enabledPlugins`;Copilot 的 `installedPlugins` 条目(市场插件还包括 `enabledPlugins["<plugin>@<marketplace>"]`);Codex `config.toml` 中的 `[plugins."<plugin>@<marketplace>"]`;或 Gemini `extension-enablement.json` 规则(与 `gemini extensions disable` 一致,用户作用域是针对主目录的规则)。工作区行修改其所属项目的 `.claude/settings.json`、`.github/copilot/settings.json` 或 `.codex/config.toml`。无关内容与注释保持不变。OpenIDEA 不会通过运行时参数把未安装的插件临时注入其他智能体,也不做格式转换。
- **插件市场**:Claude Code 和 Codex 只从具名插件市场安装。Codex 安装需要 Codex 已知的市场:已通过 `codex plugin marketplace add` 添加的市场,或本地市场文件夹(OpenIDEA 会用相同方式注册)。Copilot 只能通过仓库设置为单个仓库启用插件,因此工作区安装同样需要插件市场。
- **执行确认**保存在本机,与设置分开,并与插件实际执行的内容绑定。
- **原生布局**遵循各 CLI 发布的约定:[Claude Code 插件存储](https://code.claude.com/docs/en/plugins/loading.md#find-plugins-on-disk)、[Copilot CLI 插件文件与配置](https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-plugin-reference#file-locations)、[Codex 缓存存储](https://github.com/openai/codex/blob/main/codex-rs/core-plugins/src/store.rs) 与[插件配置](https://github.com/openai/codex/blob/main/codex-rs/config/src/types.rs)、以及 [Gemini 扩展启停](https://github.com/google-gemini/gemini-cli/blob/main/packages/cli/src/config/extensions/extensionEnablement.ts)。
- **子能力来源**:由插件贡献的技能、MCP 连接和记忆条目会显示 `来自插件 <名称>`;Copilot 插件技能会按插件包分组。
- **从市场或仓库安装**:安装前选择目标智能体;没有该智能体原生清单格式的选项会被禁用并说明原因。本地文件夹需使用绝对路径、`~/…` 或相对项目的 `./…`。OpenIDEA 会锁定预览时的 GitHub commit 与 tree SHA(本地文件夹则锁定其内容)、静态扫描文件,并要求确认可执行 MCP 进程与 hook;确认范围包括 MCP 命令、hook 文件(默认位置、清单中指定的路径以及清单内联的 hook)及 hook 引用的脚本,其中任一变化都会重新请求确认。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。
关于 **插件**、**记忆**、**MCP**、**工具** 和 **技能** 在整个任务生命周期中如何协同工作以及它们对 LLM 上下文窗口的影响,参见 [智能体资源与生命周期](/zh/guide/agent-resources)。
@@ -204,6 +215,16 @@ MY_AGENT_LOG = "info"
文件名(去掉 `.toml`)就是 agent 的 ID。以内置 agent 命名的文件(`gemini.toml`、`claude.toml`…)会替换该 agent 的启动命令;在 **内置** 标签页中设置自定义可执行文件或环境变量时,写入的就是这个文件。无法解析的文件会被跳过并记录到日志。
## Agent 自动化任务
从 **智能体** 工具窗口顶部打开 **自动化**(或前往 **设置 › 智能体 › 自动化**),无需任何云端服务即可在本机或远程 `openidea-server --daemon` 主机上按计划运行提示词:
- **计划与触发器**:支持 **工作日**、**每天**、**每周**、**每小时**、带 IANA 时区的 5 字段 **Cron 表达式**、**单次执行** 或 **仅手动触发**,并实时预览后续触发时间。
- **工作区隔离与会话延续**:每次运行可在 **独立 Git worktree**(无文件改动时自动清理临时 worktree 并保留对话记录)、**当前工作区** 或 **仅聊天** 模式下执行,支持每次新建会话或复用滚动会话。
- **会话内 `/loop` 与稍后发送**:在任意对话输入框旁点击时钟按钮,或输入 `/loop 10m <提示词>`、`/after 1h <提示词>`、`/automate <提示词>` 即可设置定时发送或循环轮询。
- **后台与重启自启**:默认情况下,计划任务在 OpenIDEA 或 `openidea-server --daemon` 运行期间执行(离线期间错过的运行按已配置的错过策略处理)。如需在关闭应用后继续运行,可在 **自动化** 面板(或 **设置 › 智能体 › 自动化**)中开启 **在 OpenIDEA 关闭时保持自动化继续运行** 以注册轻量级系统登录自启服务(`--scheduler`);关闭该选项或所有计划暂停后会自动注销。
- **可移植 `.automation.md`**:支持导出与导入带 YAML 头部的 `.automation.md` 模板;导入的模板默认处于暂停状态,审阅后再启用。
## 限制
- agent 在你的电脑上运行,使用你自己的凭据、订阅或 API key;OpenIDEA 不做代理,也不计费。
+1 -1
Переглянути файл
@@ -92,7 +92,7 @@ C 和 C++ 的配置也可以改用 GDB 14 及以上版本(`gdb -i dap`):
**查看断点…**(`⌘⇧F8` / `Ctrl+Shift+F8`)列出项目中的所有断点。可以在这里启用、编辑、删除断点和跳转到断点位置,打开 **静音断点**(暂时跳过所有断点而不删除),以及设置异常过滤器。**移除所有断点** 会清空列表。**移除当前文件中的所有断点**(通过查找操作)只移除当前编辑器中文件的行断点、方法断点和字段监视点。
断点按项目保存,重启后仍然保留。适配器无法设置的断点会标为未验证。
断点按项目保存,重启后仍然保留。适配器无法设置的断点会标为未验证;在边栏悬停可查看原因。使用 lldb-dap 或 CodeLLDB 时,通常是代码尚未加载,或调试信息以另一条路径记录该文件(经过符号链接,或以 `/tmp` 代替 `/private/tmp`),可在启动配置中用 `sourceMap` 映射回来。位于 `/private/tmp`、`/private/var` 或 `/private/etc` 下的 Xcode scheme 会自动获得该映射。
## 单步执行
+1 -1
Переглянути файл
@@ -16,7 +16,7 @@ description: "编辑器和问题工具窗口中的问题、快速修复与意图
| **错误描述** | `⌘F1` | `Ctrl+F1` |
| **问题** 工具窗口 | `⌘6` | `Alt+6` |
**问题** 工具窗口有两个标签页:**文件**(当前编辑器)和 **项目错误**。在它的选项菜单中可以按严重性或名称排序、显示预览、自动滚动到源代码。
**问题** 工具窗口有两个标签页:**文件**(当前编辑器)和 **项目错误**。问题按文件分组,工具栏上的 **全部展开** / **全部折叠** 可以展开或折叠所有文件。在它的选项菜单中可以按严重性或名称排序、显示预览、自动滚动到源代码。
## 快速修复与意图操作
+6 -4
Переглянути файл
@@ -82,7 +82,7 @@ OpenIDEA 能识别 `Dockerfile`、`Containerfile`、`Dockerfile.<名称>`、`*.d
边栏中会显示运行图标:
- Dockerfile 的 `FROM` 行:最终阶段提供 **Run '…'**(先构建再运行)和 **构建镜像 '…'**,命名的中间阶段提供 **Build Stage '…'**。
- Dockerfile 的 `FROM` 行:最终阶段提供 **Run '…'**(先构建镜像,再在后台启动容器,并在 **Services** 中打开它的日志)和 **构建镜像 '…'**,命名的中间阶段提供 **Build Stage '…'**。
- Compose 文件:`services:` 行提供 **Compose Up (All Services)**,每个服务行提供 **Compose Up '…'**。
- **修改运行配置…** 打开生成的配置,方便保存和修改。
@@ -94,20 +94,22 @@ OpenIDEA 能识别 `Dockerfile`、`Containerfile`、`Dockerfile.<名称>`、`*.d
<AccordionGroup>
<Accordion title="Dockerfile">
构建镜像;勾选 **运行构建的镜像** 时再用它启动容器。
构建镜像;勾选 **运行构建的镜像** 时再用它启动容器。容器默认在后台运行(**在后台运行 (-d)** 默认勾选):构建和启动是两步,运行窗口只显示构建输出,命令返回后容器仍在 Docker 守护进程里;随后 **Services** 工具窗口自动选中该容器并显示它的 **日志**,关掉窗口或 IDE 容器也不会退出。取消勾选则容器前台运行,**停止** 执行 `docker stop`;后台容器在 **Services** 工具窗口中启停。
**服务器** 决定构建和运行都走哪个 Docker 守护进程(`docker` CLI 按该连接设置 `DOCKER_HOST`):选远程连接时镜像在远程构建,本地不需要运行 daemon,只需要 `docker` CLI。
**Dockerfile**(相对于项目根目录)、**上下文文件夹**、**镜像标签**、**构建阶段**、**构建实参**(`KEY=value; OTHER=value`)、**构建选项**(例如 `--no-cache --platform linux/amd64`)、**运行构建的镜像**、**命令**,以及下面的容器字段。
</Accordion>
<Accordion title="Docker 镜像">
用镜像启动容器:**镜像 ID 或名称**、**运行前拉取镜像**、**命令**,以及下面的容器字段。
用镜像启动容器,同样默认后台运行并在 **Services** 中打开日志:**镜像 ID 或名称**、**运行前拉取镜像**、**命令**,以及下面的容器字段。
</Accordion>
<Accordion title="Docker Compose">
启动 Compose 服务:**Compose 文件**(用 `;` 分隔)、**Services**(留空表示全部)、**项目名称**、**在后台运行 (-d)**、**启动前构建镜像 (--build)**、**Up 选项**。停止前台运行时会执行 `docker compose down`。
</Accordion>
</AccordionGroup>
容器字段:**容器名称**、**绑定端口**(`8080:80, 5005:5005`)、**绑定挂载**(`./data:/data; cache:/root/.cache`)、**容器环境**、**运行选项**(例如 `--rm --network host`)。每次运行前会删除同名的旧容器;**停止** 执行 `docker stop`。
容器字段:**容器名称**、**绑定端口**(`8080:80, 5005:5005`)、**绑定挂载**(`./data:/data; cache:/root/.cache`)、**容器环境**、**运行选项**(例如 `--rm --network host`)。每次运行前会删除同名的旧容器;前台运行的 **停止** 执行 `docker stop`,后台运行的容器在 **Services** 中停止。
## 部署(SFTP)
+4
Переглянути файл
@@ -47,6 +47,10 @@ Vim 模式开启时(如果上次是开启状态,启动时也会),OpenIDE
`set clipboard+=unnamedplus`(或 `unnamed`)让不指定寄存器的复制、删除和修改也写入系统剪贴板。`"+` 寄存器始终读写系统剪贴板。
`set number`(`nu`)和 `set relativenumber`(`rnu`)与 IdeaVim 一样切换所有编辑器的行号:两者同时开启显示混合行号,只开 `relativenumber` 时光标行显示 0,`nonumber norelativenumber` 隐藏行号。文件里没有设置的选项跟随 **设置 › 编辑器 › 常规 › 外观 › 显示行号**,不会写回设置。
在插入模式映射的右侧,`<C-g>u` 会像 Vim 一样断开撤销序列。
其他内容(函数、`if`、`autocmd`、插件命令等)都会被标记为已忽略,不会执行。
### 把按键映射到 IDE 命令
+814
Переглянути файл
@@ -0,0 +1,814 @@
import type {
AgentAutomation_Serialize,
AgentEntry,
AgentProvider,
AgentTask,
AutomationRun_Serialize,
AutomationTrigger,
CreateSessionScheduleInput,
SaveAutomationInput_Deserialize,
SessionSchedule_Serialize as SessionSchedule,
} from "../src/bindings";
import { expect, stubDesktop, stubSettingsWrites, test } from "./fixtures";
const claudeProvider: AgentProvider = {
id: "claude",
name: "Claude Code",
command: "claude",
program: "claude",
args: [],
defaultProgram: "claude",
defaultArgs: [],
loginHint: null,
commandOverridden: false,
commandEditable: true,
commandReadOnlyReason: null,
installed: true,
env: {},
commands: [],
source: { kind: "builtin" },
config: [
{
id: "model",
category: "model",
name: "Model",
description: null,
current: "claude-sonnet-4.6",
via: "option",
values: [{ value: "claude-sonnet-4.6", name: "Claude Sonnet 4.6", description: null }],
},
],
thoughtLevels: {},
};
const manualSession: AgentTask = {
id: "manual-session-1",
title: "Refactor auth middleware",
provider: "claude",
status: "ready",
isolation: "local",
model: "claude-sonnet-4.6",
cwd: "/dev/acme-api",
branch: "main",
base: null,
baseCommit: null,
error: null,
createdMs: 1_000,
updatedMs: 5_000,
config: claudeProvider.config,
commands: [],
usage: null,
queue: [],
mcpOverrides: {},
skillOverrides: {},
};
async function installAutomationDesktopHarness(page: import("@playwright/test").Page) {
await stubDesktop(page);
await stubSettingsWrites(page);
await page.evaluate(
async ({ claudeProvider, manualSession }) => {
const storeModule = "/src/features/agents/store.ts";
const autoModule = "/src/features/agents/automationsModel.ts";
const store = await import(/* @vite-ignore */ storeModule);
const autoMod = await import(/* @vite-ignore */ autoModule);
let seq = 1;
let autoStartService = false;
let automations: AgentAutomation_Serialize[] = [];
let runs: AutomationRun_Serialize[] = [];
let sessionSchedules: SessionSchedule[] = [];
const tasks = new Map<string, AgentTask>([[manualSession.id, structuredClone(manualSession)]]);
const entriesByTask = new Map<string, AgentEntry[]>([
[
manualSession.id,
[
{ type: "user", text: "Inspect auth middleware.", attachments: [] },
{ type: "agent", text: "Ready for follow-up or scheduled turns." },
],
],
]);
const handlers = window.__ipc.handlers;
handlers.agent_subscribe = () => [...tasks.values()];
handlers.agent_providers = () => [claudeProvider];
handlers.agent_refresh_models = () => ({
provider: claudeProvider.id,
config: claudeProvider.config,
thoughtLevels: {},
refreshing: false,
refreshedAtMs: Date.now(),
retryAtMs: null,
error: null,
});
handlers.agent_probe = () => null;
handlers.agent_entries = ({ task }) => entriesByTask.get(task as string) ?? [];
handlers.agent_changes = () => [];
handlers.agent_grouped_changes = () => ({ uncommitted: [], commits: [] });
handlers.agent_commands = () => [];
handlers.agent_skills_list = () => [];
handlers.agent_memory_list = () => ({
entries: [],
providers: [],
autoMemory: "inherit",
autoMemoryOrigin: "none",
});
handlers.mcp_list = () => ({ servers: [], external: [] });
handlers.vcs_branch_info = () => ({ head: "main" });
handlers.vcs_branches = () => [{ name: "main", remote: false, current: true }];
handlers.agent_set_unread = () => null;
const buildSnapshot = () => {
for (const a of automations) {
a.unreadRuns = runs.filter((r) => r.automationId === a.id && r.unread).length;
}
const activeSchedules = automations.filter((a) => a.enabled && a.trigger.kind !== "manual").length;
const unreadRuns = runs.filter((r) => r.unread).length;
const needsInputRuns = runs.filter((r) => r.status === "needsInput").length;
const runningRuns = runs.filter((r) => r.status === "running").length;
const nextRunMs =
automations
.filter((a) => a.enabled && a.nextRunMs != null)
.map((a) => a.nextRunMs!)
.sort((x, y) => x - y)[0] ?? null;
const bootRegistered = autoStartService && activeSchedules > 0;
return {
automations: structuredClone(automations),
runs: structuredClone(runs),
runsNextCursor: null,
sessionSchedules: structuredClone(sessionSchedules),
host: {
remote: false,
hostLabel: "Local Host",
activeSchedules,
runningRuns,
needsInputRuns,
unreadRuns,
nextRunMs,
bootServiceKind: "LaunchAgent",
bootServiceRegistered: bootRegistered,
bootServicePath: bootRegistered ? "/Users/dev/Library/LaunchAgents/ai.l0ng.openidea.scheduler.plist" : null,
bootServiceError: null,
linuxLingerEnabled: null,
},
};
};
const prevSettingsSet = handlers.settings_set;
handlers.settings_set = (args) => {
if (args.key === "agents.automations.autoStartService") {
autoStartService = JSON.parse(String(args.value)) === true;
}
return prevSettingsSet ? prevSettingsSet(args) : null;
};
handlers.agent_automation_snapshot = () => buildSnapshot();
handlers.agent_automation_preview_schedule = ({ trigger, count }) => {
try {
return autoMod.previewTriggerBrowser(trigger as AutomationTrigger, Date.now(), (count as number | null) ?? 3);
} catch (err) {
throw { kind: "invalid", message: err instanceof Error ? err.message : String(err), detail: null };
}
};
handlers.agent_automation_save = ({ input }) => {
const req = input as SaveAutomationInput_Deserialize;
const nextList = autoMod.previewTriggerBrowser(req.trigger, Date.now(), 1);
const now = Date.now();
const idx = req.id ? automations.findIndex((a) => a.id === req.id) : -1;
const prev = idx >= 0 ? automations[idx] : undefined;
const saved: AgentAutomation_Serialize = {
id: prev?.id ?? `auto-${seq++}`,
name: req.name,
enabled: req.enabled,
prompt: req.prompt,
workspace:
req.workspace.kind === "chatOnly"
? { kind: "chatOnly" }
: {
kind: "project",
root: req.workspace.root,
isolation: req.workspace.isolation ?? "worktree",
base: req.workspace.base ?? null,
autoCleanWorktree: req.workspace.autoCleanWorktree ?? true,
},
continuity: req.continuity ?? "newTask",
lastTaskId: prev?.lastTaskId ?? null,
provider: req.provider,
config: req.config ?? [],
permissions: req.permissions ?? "assisted",
mcpOverrides: req.mcpOverrides ?? {},
skillOverrides: req.skillOverrides ?? {},
memoryOverrides: req.memoryOverrides ?? null,
trigger: req.trigger,
misfirePolicy: req.misfirePolicy ?? null,
disableAfterMs: req.disableAfterMs ?? null,
maxRuns: req.maxRuns ?? null,
nextRunMs: req.enabled ? (nextList[0] ?? null) : null,
runCount: prev?.runCount ?? 0,
unreadRuns: prev?.unreadRuns ?? 0,
createdMs: prev?.createdMs ?? now,
updatedMs: now,
};
if (idx >= 0) automations[idx] = saved;
else automations.unshift(saved);
window.__ipc.emit({ type: "automationsChanged" });
return saved;
};
handlers.agent_automation_set_enabled = ({ id, enabled }) => {
const found = automations.find((a) => a.id === id)!;
found.enabled = Boolean(enabled);
found.nextRunMs = found.enabled
? (autoMod.previewTriggerBrowser(found.trigger, Date.now(), 1)[0] ?? null)
: null;
window.__ipc.emit({ type: "automationsChanged" });
return structuredClone(found);
};
handlers.agent_automation_delete = ({ id }) => {
automations = automations.filter((a) => a.id !== id);
runs = runs.filter((r) => r.automationId !== id);
window.__ipc.emit({ type: "automationsChanged" });
return null;
};
handlers.agent_automation_pause_all = () => {
let n = 0;
for (const a of automations) {
if (a.enabled) {
a.enabled = false;
a.nextRunMs = null;
n += 1;
}
}
window.__ipc.emit({ type: "automationsChanged" });
return n;
};
handlers.agent_automation_mark_read = ({ runId, automationId }) => {
for (const r of runs) {
if (
(runId && r.id === runId) ||
(!runId && automationId && r.automationId === automationId) ||
(!runId && !automationId)
) {
r.unread = false;
}
}
window.__ipc.emit({ type: "automationsChanged" });
return null;
};
handlers.agent_automation_run_now = ({ id }) => {
const found = automations.find((a) => a.id === id)!;
found.runCount += 1;
const needsApproval = found.prompt.text.includes("NEEDS_APPROVAL");
const reuseTask =
found.continuity === "sameTask" && found.lastTaskId && tasks.has(found.lastTaskId)
? tasks.get(found.lastTaskId)!
: null;
const taskId = reuseTask ? reuseTask.id : `auto-task-${seq++}`;
found.lastTaskId = taskId;
const taskObj: AgentTask = reuseTask
? {
...reuseTask,
status: needsApproval ? "needsInput" : "ready",
updatedMs: Date.now(),
automation: {
automationId: found.id,
automationName: found.name,
runId: `run-${seq}`,
runNumber: found.runCount,
triggerSummary: "Scheduled",
},
}
: {
id: taskId,
title: `${found.name} (#${found.runCount})`,
provider: found.provider,
status: needsApproval ? "needsInput" : "ready",
isolation: found.workspace.kind === "project" ? found.workspace.isolation : "local",
model: "claude-sonnet-4.6",
cwd: "/dev/acme-api",
branch:
found.workspace.kind === "project" && found.workspace.isolation === "worktree"
? `agent/auto-${found.runCount}`
: "main",
base: "main",
baseCommit: null,
error: null,
createdMs: Date.now(),
updatedMs: Date.now(),
config: claudeProvider.config,
commands: [],
usage: null,
queue: [],
mcpOverrides: {},
skillOverrides: {},
automation: {
automationId: found.id,
automationName: found.name,
runId: `run-${seq}`,
runNumber: found.runCount,
triggerSummary: "Scheduled",
},
};
tasks.set(taskId, taskObj);
entriesByTask.set(taskId, [
{ type: "user", text: found.prompt.text, attachments: [] },
...(needsApproval
? ([
{
type: "permission",
id: 1,
title: "Run gh pr edit --add-label triaged",
command: "gh pr edit --add-label triaged",
options: [
{ id: "allow", kind: "allow_once", name: "Allow once" },
{ id: "deny", kind: "reject_once", name: "Decline" },
],
chosen: null,
},
] as AgentEntry[])
: ([
{
type: "agent",
text: `Completed automated run #${found.runCount} cleanly.`,
},
] as AgentEntry[])),
]);
store.useAgents.setState((s: { tasks: Map<string, AgentTask> }) => ({
tasks: new Map(s.tasks).set(taskId, taskObj),
}));
const run: AutomationRun_Serialize = {
id: `run-${seq++}`,
automationId: found.id,
automationName: found.name,
runNumber: found.runCount,
taskId,
projectRoot: "/dev/acme-api",
provider: found.provider,
origin: { kind: "manual" },
status: needsApproval ? "needsInput" : "completed",
startedMs: Date.now(),
finishedMs: needsApproval ? null : Date.now(),
error: null,
unread: true,
added: needsApproval ? 0 : 0,
removed: 0,
branch: taskObj.branch ?? null,
worktreeCleaned:
!needsApproval &&
found.continuity === "newTask" &&
found.workspace.kind === "project" &&
found.workspace.isolation === "worktree" &&
found.workspace.autoCleanWorktree,
};
runs.unshift(run);
window.__ipc.emit({ type: "automationsChanged" });
return run;
};
handlers.agent_automation_export_markdown = ({ id }) => {
const found = automations.find((a) => a.id === id)!;
return `---\nversion: 1\nid: ${found.id}\nname: "${found.name}"\nschedule:\n kind: cron\n expression: "0 9,15 * * MON-FRI"\n timeZone: "America/Los_Angeles"\n---\n\n${found.prompt.text}\n`;
};
handlers.agent_automation_import_markdown = ({ markdown, chatOnly, provider }) => {
const m = /name:\s*"?([^"\n]+)"?/.exec(markdown as string);
const name = m?.[1]?.trim() || "Imported Schedule";
const body = (markdown as string).split("---").slice(2).join("---").trim();
return handlers.agent_automation_save!({
input: {
name,
enabled: false,
prompt: { text: body || "Imported prompt", files: [], images: [] },
workspace: chatOnly
? { kind: "chatOnly" }
: { kind: "project", root: "/dev/acme-api", isolation: "worktree", autoCleanWorktree: true },
continuity: "newTask",
provider: provider as string,
trigger: { kind: "cron", expression: "0 9,15 * * MON-FRI", timeZone: "America/Los_Angeles" },
},
});
};
handlers.agent_session_schedule_create = ({ input }) => {
const req = input as CreateSessionScheduleInput;
const created: SessionSchedule = {
id: `ssched-${seq++}`,
taskId: req.taskId,
projectRoot: "/dev/acme-api",
prompt: req.prompt,
kind: req.kind,
paused: false,
nextRunMs:
req.kind.kind === "sendLater"
? (req.kind.runAtMs ?? Date.now() + 900_000)
: Date.now() + req.kind.intervalSecs * 1000,
runs: 0,
createdMs: Date.now(),
};
sessionSchedules.push(created);
window.__ipc.emit({ type: "automationsChanged" });
return created;
};
handlers.agent_session_schedule_set_paused = ({ id, paused }) => {
const sc = sessionSchedules.find((s) => s.id === id)!;
sc.paused = Boolean(paused);
window.__ipc.emit({ type: "automationsChanged" });
return structuredClone(sc);
};
handlers.agent_session_schedule_run_now = ({ id }) => {
const idx = sessionSchedules.findIndex((s) => s.id === id);
if (idx >= 0) {
const sc = sessionSchedules[idx]!;
if (sc.kind.kind === "sendLater") sessionSchedules.splice(idx, 1);
else sc.runs = (sc.runs ?? 0) + 1;
}
window.__ipc.emit({ type: "automationsChanged" });
return null;
};
handlers.agent_session_schedule_delete = ({ id }) => {
sessionSchedules = sessionSchedules.filter((s) => s.id !== id);
window.__ipc.emit({ type: "automationsChanged" });
return null;
};
await store.connect();
await autoMod.refreshAutomations();
},
{ claudeProvider, manualSession },
);
}
test("creates, validates cron, runs, inspects provenance, exports/imports .automation.md, and deletes automations", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1320, height: 860 });
await installAutomationDesktopHarness(page);
// Open Agents tool window and click the pinned Automations hub row
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("agents.showToolWindow");
});
const hub = page.getByTestId("agents-automations-hub");
await expect(hub).toBeVisible();
await hub.getByRole("button", { name: /Automations/ }).click();
const editor = page.getByTestId("automations-editor");
await expect(editor).toBeVisible();
await expect(editor).toContainText("Automate recurring agent workflows");
// Click a starter template to open New Automation dialog pre-populated
await editor.getByRole("button", { name: /Morning PR & CI Triage/ }).click();
const dialog = page.getByRole("dialog", { name: "New Automation" });
await expect(dialog).toBeVisible();
await expect(dialog.getByLabel("Name")).toHaveValue("Morning PR & CI Triage");
// Switch to 5-field Cron expression and verify live validation rejects invalid syntax
await dialog.getByRole("button", { name: "Schedule", exact: true }).click();
await page.getByRole("option", { name: "Cron expression" }).click();
const cronInput = dialog.getByLabel("Cron Expression (5-field)");
await cronInput.fill("99 9 * * *");
await expect(dialog.getByTestId("automation-schedule-preview")).toContainText("out of range");
await expect(dialog.getByRole("button", { name: "Create Automation" })).toBeDisabled();
// Fix cron + timezone -> verify live Upcoming runs preview and enable Create
await cronInput.fill("0 9,15 * * MON-FRI");
await dialog.getByLabel("Time Zone").fill("America/Los_Angeles");
await expect(dialog.getByTestId("automation-schedule-preview")).toContainText("Upcoming runs:");
await expect(dialog.getByRole("button", { name: "Create Automation" })).toBeEnabled();
await dialog.getByLabel("Stop After Runs (optional)").fill("25");
await dialog.getByRole("button", { name: "Create Automation" }).click();
await expect(dialog).toHaveCount(0);
// Verify dashboard row, default-off login service, inline toggle registration, and status bar item
await expect(page.getByTestId("scheduler-host-pill")).toContainText("1 active schedule");
await expect(page.getByTestId("scheduler-host-pill")).not.toContainText("Auto-starts on login");
await editor.getByRole("checkbox", { name: "Keep automations running when OpenIDEA is closed" }).click();
await expect(page.getByTestId("scheduler-host-pill")).toContainText("Auto-starts on login");
await expect(page.getByTestId("status-scheduler-button")).toContainText("1 scheduled");
// Trigger Run Now -> switches to Run History and opens SessionEditor with Provenance Banner
await editor.getByRole("button", { name: "Run Now" }).click();
const provenance = page.getByTestId("automation-provenance-banner");
await expect(provenance).toBeVisible();
await expect(provenance).toContainText("Automated by");
await expect(provenance).toContainText("Morning PR & CI Triage");
await expect(provenance).toContainText("#1");
// Click Open Automation on provenance banner to jump back to Automations dashboard
await provenance.getByRole("button", { name: "Open Automation" }).click();
await expect(editor).toBeVisible();
// Check Run History tab -> zero-diff worktree auto-GC badge + Mark All as Read
await editor.getByRole("tab", { name: /Run History/ }).click();
await expect(editor).toContainText("Zero-diff worktree cleaned");
await editor.getByRole("button", { name: "Mark All as Read" }).click();
// Switch back to Schedules -> Export .automation.md -> Import .automation.md (starts Paused!)
await editor.getByRole("tab", { name: /Schedules/ }).click();
await editor.getByRole("button", { name: "More Actions" }).click();
await page.getByRole("menuitem", { name: "Export .automation.md…" }).click();
const exportDialog = page.getByRole("dialog", { name: "Export .automation.md" });
await expect(exportDialog.getByLabel("Exported Automation Markdown")).toHaveValue(
/expression: "0 9,15 \* \* MON-FRI"/,
);
const exportedMd = await exportDialog.getByLabel("Exported Automation Markdown").inputValue();
await exportDialog.getByRole("button", { name: "Close" }).click();
await editor.getByRole("button", { name: "Import .automation.md" }).click();
const importDialog = page.getByRole("dialog", { name: "Import .automation.md" });
await importDialog
.getByLabel("Automation Markdown")
.fill(exportedMd.replace("Morning PR & CI Triage", "Imported Security Audit"));
await importDialog.getByRole("button", { name: "Import Disabled" }).click();
await expect(editor).toContainText("Imported Security Audit");
await expect(editor.locator('[data-testid^="automation-row-"]').first()).toContainText("Paused");
// Delete Imported Security Audit via More Actions › Delete… confirmation dialog
await editor
.locator('[data-testid^="automation-row-"]')
.first()
.getByRole("button", { name: "More Actions" })
.click();
await page.getByRole("menuitem", { name: "Delete…" }).click();
await page.getByRole("dialog", { name: "Delete Automation" }).getByRole("button", { name: "Delete" }).click();
await expect(editor).not.toContainText("Imported Security Audit");
});
test("supports SameTask rolling continuity, NeedsInput approval flow, and sidebar automated-run visibility filters", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1320, height: 860 });
await installAutomationDesktopHarness(page);
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("agents.showToolWindow");
await executeAction("agents.automations");
});
const editor = page.getByTestId("automations-editor");
// 1) Create a completed clean automation (NewTask) and run it once -> completed & read
await editor.getByRole("button", { name: "New Automation" }).click();
let dialog = page.getByRole("dialog", { name: "New Automation" });
await dialog.getByLabel("Name").fill("Quiet Clean Sweep");
await dialog.getByLabel("Prompt Instructions").fill("Check formatting cleanly.");
await dialog.getByRole("button", { name: "Create Automation" }).click();
await editor.getByRole("button", { name: "Run Now" }).first().click();
// Return to Automations and mark read so Quiet Clean Sweep (#1) is completed + read
await page.getByTestId("automation-provenance-banner").getByRole("button", { name: "Open Automation" }).click();
await editor.getByRole("tab", { name: /Run History/ }).click();
await editor.getByRole("button", { name: "Mark All as Read" }).click();
await editor.getByRole("tab", { name: /Schedules/ }).click();
// 2) Create a SameTask rolling automation that requests tool approval (NEEDS_APPROVAL)
await editor.getByRole("button", { name: "New Automation" }).click();
dialog = page.getByRole("dialog", { name: "New Automation" });
await dialog.getByLabel("Name").fill("Rolling PR Labeler");
await dialog.getByLabel("Prompt Instructions").fill("NEEDS_APPROVAL label triaged PRs");
await dialog.getByRole("button", { name: "Session Continuity" }).click();
await page.getByRole("option", { name: "Reuse rolling session" }).click();
await dialog.getByRole("button", { name: "Create Automation" }).click();
// Run twice -> SameTask reuses the same rolling task id and lands in needsInput!
await editor.getByRole("button", { name: "Run Now" }).first().click();
const visibleBanner = page.getByTestId("automation-provenance-banner").locator("visible=true");
await expect(visibleBanner).toContainText("Rolling PR Labeler");
await expect(visibleBanner).toContainText("#1");
await expect(visibleBanner).toContainText("Waiting for approval");
// Trigger a second run on the same rolling session and verify #2 reuses the exact same task!
await visibleBanner.getByRole("button", { name: "Open Automation" }).click();
await editor.getByRole("tab", { name: /Schedules/ }).click();
await editor.getByRole("button", { name: "Run Now" }).first().click();
await expect(visibleBanner).toContainText("#2");
// Check sidebar task tree under default filter ("Active & Needs Input"):
// Manual task + NeedsInput automated task are shown; completed read automated task is hidden!
const taskTree = page.getByRole("tree", { name: "Agent tasks" });
await expect(taskTree).toContainText("Refactor auth middleware");
await expect(taskTree).toContainText("Rolling PR Labeler (#1)");
await expect(taskTree).not.toContainText("Quiet Clean Sweep (#1)");
// Switch filter to Show All -> Quiet Clean Sweep (#1) appears
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("agents.automatedRunsAll");
});
await expect(taskTree).toContainText("Quiet Clean Sweep (#1)");
// Switch filter to Hide All -> both automated tasks hide, manual task stays!
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("agents.automatedRunsHidden");
});
await expect(taskTree).toContainText("Refactor auth middleware");
await expect(taskTree).not.toContainText("Rolling PR Labeler (#1)");
await expect(taskTree).not.toContainText("Quiet Clean Sweep (#1)");
});
test("schedules in-session Send Later, /loop recurring prompts, and /automate from SessionComposer", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1280, height: 840 });
await installAutomationDesktopHarness(page);
await page.evaluate(async () => {
const storeModule = "/src/features/agents/store.ts";
const store = await import(/* @vite-ignore */ storeModule);
store.openTask("manual-session-1");
});
const composerBox = page.getByRole("textbox", { name: "Message" });
await expect(composerBox).toBeVisible();
// 1) Type a message and schedule via the clock menu ("Send in 15 minutes")
await composerBox.click();
await page.keyboard.type("Verify staging deployment health");
await page.getByRole("button", { name: "Schedule or Loop Message" }).click();
await page.getByRole("menuitem", { name: "Send in 15 minutes" }).click();
const strip = page.getByTestId("session-schedule-strip");
await expect(strip).toBeVisible();
await expect(strip).toContainText("Send at");
await expect(strip).toContainText("Verify staging deployment health");
// 2) Type /loop 10m <prompt> and submit with Enter
await composerBox.click();
await page.keyboard.type("/loop 10m poll workflow status");
await page.keyboard.press("Enter");
await expect(strip).toContainText("Every 10m");
await expect(strip).toContainText("poll workflow status");
// Pause & Resume the loop item, then fire Send Now on the one-shot item, then Cancel loop
const rows = strip.locator('[data-testid^="session-schedule-"]');
await expect(rows).toHaveCount(2);
await rows.nth(1).getByRole("button", { name: "Pause" }).click();
await expect(rows.nth(1)).toContainText("Paused");
await rows.nth(1).getByRole("button", { name: "Resume" }).click();
// Send Now on Send Later removes the one-shot item
await rows.nth(0).getByRole("button", { name: "Send Now" }).click();
await expect(rows).toHaveCount(1);
// Cancel the remaining /loop item
await rows.nth(0).getByRole("button", { name: "Cancel Schedule" }).click();
await expect(page.getByTestId("session-schedule-strip")).toHaveCount(0);
// 3) Type /automate <prompt> -> opens New Automation dialog prefilled with prompt!
await composerBox.click();
await page.keyboard.type("/automate audit weekly flaky tests");
await page.keyboard.press("Enter");
const dialog = page.getByRole("dialog", { name: "New Automation" });
await expect(dialog).toBeVisible();
await expect(dialog.getByLabel("Prompt Instructions")).toHaveValue("audit weekly flaky tests");
await dialog.getByRole("button", { name: "Cancel" }).click();
});
test("manages status-bar scheduler popover, Settings › Agents › Automations persistence, and untrusted banner", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1280, height: 840 });
await installAutomationDesktopHarness(page);
// Create one active schedule first
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("agents.newAutomation");
});
const dialog = page.getByRole("dialog", { name: "New Automation" });
await dialog.getByLabel("Name").fill("Hourly Health Ping");
await dialog.getByLabel("Prompt Instructions").fill("Ping health endpoint.");
await dialog.getByRole("button", { name: "Create Automation" }).click();
// Click status bar scheduler pill -> inspect popover -> Pause All
const statusBtn = page.getByTestId("status-scheduler-button");
await expect(statusBtn).toContainText("1 scheduled");
await statusBtn.click();
const popover = page.getByTestId("status-scheduler-popover");
await expect(popover).toBeVisible();
await expect(popover).toContainText("Local Host Scheduler");
await expect(popover).toContainText("Idle");
await popover.getByRole("button", { name: "Pause All" }).click();
await expect(statusBtn).toHaveCount(0);
// Open Settings › Agents › Automations and verify settings write through IPC
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("file.settings", "agents.automations");
});
const settingsPage = page.getByTestId("automations-settings-page");
await expect(settingsPage).toBeVisible();
await expect(settingsPage).toContainText("OS login service idle");
await settingsPage.getByRole("checkbox", { name: "Keep automations running when OpenIDEA is closed" }).click();
await settingsPage.getByRole("button", { name: "Default missed schedule policy" }).click();
await page.getByRole("option", { name: "Skip missed runs until next scheduled tick" }).click();
await page.getByRole("dialog", { name: "Settings" }).getByRole("button", { name: "Apply" }).click();
const savedKeys = await page.evaluate(() =>
window.__ipc.calls.filter((c) => c.cmd === "settings_set").map((c) => c.args.key),
);
expect(savedKeys).toContain("agents.automations.autoStartService");
expect(savedKeys).toContain("agents.automations.misfirePolicy");
await page.getByRole("dialog", { name: "Settings" }).getByRole("button", { name: "OK" }).click();
// Mark workspace untrusted -> verify AutomationsEditor shows the untrusted workspace banner
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const actionsModule = "/src/platform/actions.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const cur = useProject.getState().project!;
useProject.setState({ project: { ...cur, trusted: false } });
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("agents.automations");
});
await expect(page.getByTestId("automations-editor")).toContainText(
"This project is untrusted. Workspace automations stay paused until you trust the project.",
);
});
test("supports Weekly day picker, Local Autonomous warning, ChatOnly workspace, Duplicate, Pause/Resume, and Remote Daemon linger warning", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1320, height: 860 });
await installAutomationDesktopHarness(page);
// Switch host snapshot to Remote Daemon with Linux systemd linger disabled
await page.evaluate(() => {
const orig = window.__ipc.handlers.agent_automation_snapshot!;
window.__ipc.handlers.agent_automation_snapshot = (args) => {
const snap = orig(args) as { host: Record<string, unknown> };
snap.host.remote = true;
snap.host.hostLabel = "Remote Daemon";
snap.host.bootServiceKind = "systemdUser";
snap.host.linuxLingerEnabled = false;
return snap;
};
});
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("agents.automations");
});
const editor = page.getByTestId("automations-editor");
await expect(page.getByTestId("scheduler-host-pill")).toContainText("Remote Daemon");
// Open New Automation -> test Local checkout + Autonomous warning, Weekly day buttons, then switch to ChatOnly
await editor.getByRole("button", { name: "New Automation" }).click();
const dialog = page.getByRole("dialog", { name: "New Automation" });
await dialog.getByLabel("Name").fill("Weekly Release Notes");
await dialog.getByLabel("Prompt Instructions").fill("Draft release notes from merged PRs.");
await dialog.getByRole("button", { name: "Checkout Isolation" }).click();
await page.getByRole("option", { name: "Local checkout" }).click();
await dialog.getByRole("button", { name: "Unattended Permissions" }).click();
await page.getByRole("option", { name: "Allow all (capped by your interactive approval setting)" }).click();
await expect(dialog).toContainText(
"Warning: Autonomous mode on a local checkout can modify your working files directly.",
);
// Switch to Weekly schedule and toggle Friday + Tuesday, and switch Workspace Target to No workspace (chat only)
await dialog.getByRole("button", { name: "Schedule", exact: true }).click();
await page.getByRole("option", { name: "Weekly" }).click();
await dialog.getByRole("button", { name: "Tue" }).click();
await expect(dialog.getByRole("button", { name: "Tue" })).toHaveAttribute("aria-pressed", "true");
await dialog.getByRole("button", { name: "Workspace Target" }).click();
await page.getByRole("option", { name: "No workspace (chat only)" }).click();
await dialog.getByRole("button", { name: "Create Automation" }).click();
await expect(editor).toContainText("Weekly Release Notes");
await expect(editor).toContainText("Chat only");
// Duplicate -> creates "(Copy)" paused, then Resume and Pause schedule
await editor.getByRole("button", { name: "More Actions" }).click();
await page.getByRole("menuitem", { name: "Duplicate" }).click();
await expect(editor).toContainText("Weekly Release Notes (Copy)");
const copyRow = editor.locator('[data-testid^="automation-row-"]').first();
await copyRow.getByRole("button", { name: "Resume Schedule" }).click();
await expect(page.getByTestId("scheduler-host-pill")).toContainText("2 active schedules");
await copyRow.getByRole("button", { name: "Pause Schedule" }).click();
await expect(page.getByTestId("scheduler-host-pill")).toContainText("1 active schedule");
// Open Settings › Agents › Automations -> verify Remote Daemon Scheduler + Linux linger hint!
await editor.getByRole("button", { name: "Automation Settings" }).click();
const settingsPage = page.getByTestId("automations-settings-page");
await expect(settingsPage).toContainText("Remote Daemon Scheduler");
await expect(settingsPage).toContainText("loginctl enable-linger $USER");
});
+381
Переглянути файл
@@ -0,0 +1,381 @@
import { readFileSync } from "node:fs";
import path from "node:path";
import { expect, test } from "./fixtures";
test("previews MDX safely on open, opts into sandboxed JSX execution, and configures MDX execution in Settings", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1280, height: 800 });
await page.evaluate(async () => {
const backendPath = "/src/editor/core/backend.ts";
const servicePath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(servicePath);
docBackend().files.set(
"/dev/acme-api/Counter.tsx",
[
'import { useState } from "react";',
"export function Counter({ initial = 1 }: { initial?: number }) {",
" const [count, setCount] = useState(initial);",
" return (",
' <button type="button" onClick={() => setCount((c) => c + 1)}>',
" Clicks: {count}",
" </button>",
" );",
"}",
].join("\n"),
);
docBackend().files.set("/dev/acme-api/Part.mdx", "Transcluded **MDX** snippet from `./Part.mdx`.");
docBackend().files.set(
"/dev/acme-api/guide.mdx",
[
"---",
'title: "Interactive Guide"',
"---",
"",
"{/* Stripped MDX comment */}",
'import { Counter } from "./Counter";',
'import Part from "./Part.mdx";',
"",
"# {frontmatter.title}",
"",
"<Steps>",
' <Step title="Safe static preview">',
" Documentation tags render immediately.",
" </Step>",
"</Steps>",
"",
'<Note title="Sandbox">Runs inside an isolated frame.</Note>',
"",
"<Part />",
"",
"<Counter initial={3} />",
].join("\n"),
);
await editorService().openFile("/dev/acme-api/guide.mdx");
});
// 1. Safe static preview renders immediately without executing JSX, and shows the opt-in banner.
await expect(page.getByRole("button", { name: "Editor Only", exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "Editor and Preview", exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "Preview Only", exact: true })).toBeVisible();
await expect(page.getByText("This MDX file contains JSX components or imports.")).toBeVisible();
const staticPreview = page.getByRole("document", { name: "Markdown preview" });
await expect(staticPreview).toContainText("Safe static preview");
await expect(staticPreview).toContainText("Runs inside an isolated frame.");
await expect(staticPreview).not.toContainText("Stripped MDX comment");
// 2. Dynamic opt-in launches the sandboxed iframe and evaluates imported TSX + transcluded MDX.
await page.getByRole("button", { name: "Run JSX", exact: true }).click();
await expect(page.getByText("Running JSX in sandbox")).toBeVisible();
const sandboxFrame = page.frameLocator('iframe[title="MDX preview"]');
await expect(sandboxFrame.getByRole("heading", { name: "Interactive Guide" })).toBeVisible();
await expect(sandboxFrame.getByText("Transcluded MDX snippet from ./Part.mdx.")).toBeVisible();
const counterBtn = sandboxFrame.getByRole("button", { name: "Clicks: 3" });
await expect(counterBtn).toBeVisible();
await counterBtn.click();
await expect(sandboxFrame.getByRole("button", { name: "Clicks: 4" })).toBeVisible();
// 3. Stepping back to Safe Mode restores the static sanitized preview.
await page.getByRole("button", { name: "Safe Mode", exact: true }).click();
await expect(page.getByText("This MDX file contains JSX components or imports.")).toBeVisible();
await expect(page.getByRole("document", { name: "Markdown preview" })).toBeVisible();
// 4. Settings › Languages & Frameworks › Markdown exposes MDX component execution.
await page.keyboard.press("Meta+,");
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
await settings.getByRole("textbox", { name: "Search settings" }).fill("Markdown");
await settings.getByRole("treeitem", { name: "Markdown", exact: true, level: 2 }).click();
const mdxSelect = settings.getByRole("button", { name: "MDX component execution", exact: true });
await expect(mdxSelect).toBeVisible();
await expect(mdxSelect).toContainText("Ask before running");
await mdxSelect.click();
await page.getByRole("option", { name: "Disabled", exact: true }).click();
await settings.getByRole("button", { name: "OK", exact: true }).click();
await expect(settings).toBeHidden();
});
test("renders OpenIDEA docs/en/introduction.mdx with Run JSX and docs/plugins.mdx with ambient React hooks", async ({
workbench: page,
}) => {
const repoRoot = path.resolve(import.meta.dirname, "..");
const docsFiles: Record<string, string> = {
"/dev/acme-api/docs/docs.json": readFileSync(path.join(repoRoot, "docs/docs.json"), "utf8"),
"/dev/acme-api/docs/home.css": readFileSync(path.join(repoRoot, "docs/home.css"), "utf8"),
"/dev/acme-api/docs/plugins.mdx": readFileSync(path.join(repoRoot, "docs/plugins.mdx"), "utf8"),
"/dev/acme-api/docs/snippets/marketplace.jsx": readFileSync(
path.join(repoRoot, "docs/snippets/marketplace.jsx"),
"utf8",
),
"/dev/acme-api/docs/snippets/plugin-catalog.jsx": readFileSync(
path.join(repoRoot, "docs/snippets/plugin-catalog.jsx"),
"utf8",
),
"/dev/acme-api/docs/en/introduction.mdx": readFileSync(path.join(repoRoot, "docs/en/introduction.mdx"), "utf8"),
};
await page.evaluate(async (seed) => {
const backendPath = "/src/editor/core/backend.ts";
const servicePath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(servicePath);
for (const [k, v] of Object.entries(seed)) {
docBackend().files.set(k, v);
}
await editorService().openFile("/dev/acme-api/docs/en/introduction.mdx");
}, docsFiles);
// 1. en/introduction.mdx shows the Run JSX button and runs <CardGroup> + <Note> in sandbox.
await expect(page.getByRole("button", { name: "Run JSX", exact: true })).toBeVisible();
await page.getByRole("button", { name: "Run JSX", exact: true }).click();
const introFrame = page.frameLocator('iframe[title="MDX preview"]');
await expect(introFrame.getByRole("heading", { name: "Where to go next" })).toBeVisible();
await expect(introFrame.getByRole("link", { name: "Install" })).toBeVisible();
// 2. docs/plugins.mdx imports /snippets/marketplace.jsx (which uses ambient useState/useEffect without imports)
// and auto-loads docs/home.css.
await page.evaluate(async () => {
const servicePath = "/src/workbench/contributions.ts";
const { editorService } = await import(servicePath);
await editorService().openFile("/dev/acme-api/docs/plugins.mdx");
});
await expect(page.getByRole("button", { name: "Run JSX", exact: true })).toBeVisible();
await page.getByRole("button", { name: "Run JSX", exact: true }).click();
await expect(page.getByRole("alert")).toHaveCount(0);
const marketFrame = page.frameLocator('iframe[data-mdx-path="/dev/acme-api/docs/plugins.mdx"]');
await expect(marketFrame.getByRole("heading", { name: "Make OpenIDEA yours." })).toBeVisible();
const searchInput = marketFrame.getByRole("searchbox", { name: "Search plugins" });
await expect(searchInput).toBeVisible();
await searchInput.fill("Graphviz");
await expect(marketFrame.getByRole("heading", { name: "Graphviz" })).toBeVisible();
});
test("renders Mermaid diagrams and docs-root <video> elements in both Safe Mode and sandboxed Run JSX mode", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const backendPath = "/src/editor/core/backend.ts";
const servicePath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(servicePath);
docBackend().files.set("/dev/acme-api/docs/docs.json", "{}");
// Minimal ftyp box bytes encoded as a data URL in the in-memory workspace
docBackend().files.set(
"/dev/acme-api/docs/videos/agent-resources-lifecycle.mp4",
"data:video/mp4;base64,AAAAGGZ0eXBtcDQyAAAAAGlzb21tcDQy",
);
docBackend().files.set(
"/dev/acme-api/docs/en/guide/agent-resources.mdx",
[
"---",
'title: "Agent resources and lifecycle"',
"---",
"",
'<video controls className="w-full aspect-video rounded-xl" src="/videos/agent-resources-lifecycle.mp4" />',
"",
"## Architecture and data flow",
"",
"```mermaid",
"flowchart LR",
' Host["OpenIDEA Host"] --> MCP["Built-in MCP Server"]',
"```",
"",
"<Steps>",
' <Step title="Phase 1">',
" Host startup.",
" </Step>",
"</Steps>",
].join("\n"),
);
await editorService().openFile("/dev/acme-api/docs/en/guide/agent-resources.mdx");
});
// 1. Safe Static Mode renders the Mermaid diagram as SVG and resolves the docs-root <video> to a blob: URL.
const staticPreview = page.getByRole("document", { name: "Markdown preview" });
await expect(staticPreview.locator('[data-mermaid-state="ok"] .mermaid-output svg')).toBeVisible();
await expect(staticPreview.locator("video")).toHaveAttribute("src", /^blob:/);
// 2. Clicking Run JSX renders both the Mermaid SVG and the <video> blob: URL inside the sandboxed frame.
await page.getByRole("button", { name: "Run JSX", exact: true }).click();
await expect(page.getByText("Running JSX in sandbox")).toBeVisible();
await expect(page.getByRole("alert")).toHaveCount(0);
const liveFrame = page.frameLocator('iframe[data-mdx-path="/dev/acme-api/docs/en/guide/agent-resources.mdx"]');
await expect(liveFrame.getByRole("heading", { name: "Architecture and data flow" })).toBeVisible();
await expect(liveFrame.locator('[data-mdx-mermaid="ok"] svg')).toBeVisible();
await expect(liveFrame.locator("video")).toHaveAttribute("src", /^blob:/);
});
test("confirms external links only on a real browser click in the MDX frame and blocks scripted/focus attempts", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const backendPath = "/src/editor/core/backend.ts";
const servicePath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(servicePath);
(window as { __openedExternalUrls?: string[] }).__openedExternalUrls = [];
window.open = ((url?: string | URL) => {
(window as { __openedExternalUrls?: string[] }).__openedExternalUrls!.push(String(url ?? ""));
return null;
}) as typeof window.open;
docBackend().files.set(
"/dev/acme-api/links.mdx",
[
'import { useEffect, useRef } from "react";',
"",
"export function LinkProbe() {",
" const linkRef = useRef(null);",
" useEffect(() => {",
' window.parent.postMessage({ tag: "openidea-mdx-preview", op: "openLink", href: "https://evil.example/on-mount", clickId: 1 }, "*");',
" linkRef.current?.click();",
" const onFocus = () => {",
' window.parent.postMessage({ tag: "openidea-mdx-preview", op: "openLink", href: "https://evil.example/on-focus", clickId: 2 }, "*");',
" linkRef.current?.click();",
" };",
' window.addEventListener("focus", onFocus);',
' return () => window.removeEventListener("focus", onFocus);',
" }, []);",
" return (",
" <div>",
' <button type="button" onClick={() => { linkRef.current?.click(); window.parent.postMessage({ tag: "openidea-mdx-preview", op: "openLink", href: "https://evil.example/hijack", clickId: 3 }, "*"); }}>Benign Button</button>',
' <a ref={linkRef} href="https://[email protected]/docs?q=1">External Docs</a>',
" </div>",
" );",
"}",
"",
"# Link Guard",
"",
"<LinkProbe />",
].join("\n"),
);
await editorService().openFile("/dev/acme-api/links.mdx");
});
await page.getByRole("button", { name: "Run JSX", exact: true }).click();
await expect(page.getByText("Running JSX in sandbox")).toBeVisible();
const iframe = page.locator('iframe[data-mdx-path="/dev/acme-api/links.mdx"]');
const liveFrame = page.frameLocator('iframe[data-mdx-path="/dev/acme-api/links.mdx"]');
await expect(liveFrame.getByRole("link", { name: "External Docs" })).toBeVisible();
// 1. Mount-time postMessage + synthetic link.click() must not open the confirmation dialog.
const dialog = page.getByRole("dialog", { name: "Open External Link?" });
await expect(dialog).toHaveCount(0);
// 2. Focusing the iframe without clicking the link must not open the confirmation dialog.
await iframe.focus();
await page.waitForTimeout(100);
await expect(dialog).toHaveCount(0);
// 3. Clicking a benign button whose handler calls synthetic link.click() / postMessage must not open the dialog.
await liveFrame.getByRole("button", { name: "Benign Button" }).click();
await page.waitForTimeout(100);
await expect(dialog).toHaveCount(0);
// 4. A real browser click on the link opens the confirmation showing parsed scheme+host prominently.
await liveFrame.getByRole("link", { name: "External Docs" }).click();
await expect(dialog).toBeVisible();
await expect(page.getByTestId("mdx-external-link-destination")).toHaveText("https://evil.example");
await expect(page.getByTestId("mdx-external-link-full")).toHaveText("https://[email protected]/docs?q=1");
// Dismissing with Cancel keeps the URL unopened and does not re-open on focus/script.
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(dialog).toHaveCount(0);
await page.waitForTimeout(100);
await expect(dialog).toHaveCount(0);
expect(await page.evaluate(() => (window as { __openedExternalUrls?: string[] }).__openedExternalUrls)).toEqual([]);
// 5. Clicking the link a second time with real input opens confirmation again; clicking Open opens the parsed URL.
await liveFrame.getByRole("link", { name: "External Docs" }).click();
await expect(dialog).toBeVisible();
await dialog.getByRole("button", { name: "Open", exact: true }).click();
await expect(dialog).toHaveCount(0);
expect(await page.evaluate(() => (window as { __openedExternalUrls?: string[] }).__openedExternalUrls)).toEqual([
"https://[email protected]/docs?q=1",
]);
});
test("does not open the external link prompt for hover, forged link handlers, or a stolen bridge port", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const backendPath = "/src/editor/core/backend.ts";
const servicePath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(servicePath);
docBackend().files.set(
"/dev/acme-api/forged-links.mdx",
[
'import { useEffect } from "react";',
"",
"export const portThief = { port: null };",
'export const dataGetter = Object.getOwnPropertyDescriptor(MessageEvent.prototype, "data").get;',
'export const patched = Object.defineProperty(MessageEvent.prototype, "data", {',
" configurable: true,",
" get() {",
" if (this.target instanceof MessagePort) portThief.port = this.target;",
" return dataGetter.call(this);",
" },",
"});",
"",
"export function Probe({ A }) {",
" useEffect(() => {",
" let n = 100;",
" const forge = (ev) => {",
' const el = A({ href: "https://evil.example/forged", children: "x" });',
" el.props.onClick({ preventDefault() {}, defaultPrevented: false, nativeEvent: ev });",
' portThief.port?.postMessage({ tag: "openidea-mdx-preview", op: "openLink", href: "https://evil.example/port", clickId: n++ });',
" };",
' document.addEventListener("mousemove", forge);',
' document.addEventListener("click", forge);',
" return () => {",
' document.removeEventListener("mousemove", forge);',
' document.removeEventListener("click", forge);',
" };",
" }, []);",
" return (",
" <div style={{ height: 300 }}>",
' <button type="button">Benign Button</button>',
" </div>",
" );",
"}",
"",
"# Forged Links",
"",
"<Probe A={props.components.a} />",
].join("\n"),
);
await editorService().openFile("/dev/acme-api/forged-links.mdx");
});
await page.getByRole("button", { name: "Run JSX", exact: true }).click();
const iframe = page.locator('iframe[data-mdx-path="/dev/acme-api/forged-links.mdx"]');
const liveFrame = page.frameLocator('iframe[data-mdx-path="/dev/acme-api/forged-links.mdx"]');
await expect(liveFrame.getByRole("button", { name: "Benign Button" })).toBeVisible();
const dialog = page.getByRole("dialog", { name: "Open External Link?" });
const box = (await iframe.boundingBox())!;
for (let i = 0; i < 5; i++) await page.mouse.move(box.x + 100 + i * 10, box.y + 150);
await page.waitForTimeout(200);
await expect(dialog).toHaveCount(0);
await liveFrame.getByRole("button", { name: "Benign Button" }).click();
await page.waitForTimeout(200);
await expect(dialog).toHaveCount(0);
});
+108
Переглянути файл
@@ -1,5 +1,113 @@
import { expect, test } from "./fixtures";
test.use({ video: "on" });
test("Show Usages drags by the title bar, keeps its controls usable and stays inside the viewport", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const usages = "/src/features/code-insight/usages.ts";
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
const path = "/dev/app/src/Main.ts";
useUsagesPopup.setState({
open: true,
anchor: { x: 100, y: 100 },
symbol: "run",
scope: "project",
groups: [
{
path,
usages: Array.from({ length: 4 }, (_, line) => ({ path, line, col: 0, endCol: 3, text: "run();" })),
},
],
});
});
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
const title = popup.getByText("Usages of run", { exact: true });
await expect(popup).toBeVisible();
await popup.evaluate((el) => Promise.all(el.getAnimations().map((a) => a.finished)));
const before = (await popup.boundingBox())!;
await page.screenshot({ path: test.info().outputPath("usages-before-drag.png") });
// The empty space after the caption, where the reported drag failed.
const caption = (await title.locator("..").boundingBox())!;
const start = { x: caption.x + caption.width - 4, y: caption.y + caption.height / 2 };
await page.mouse.move(start.x, start.y);
await page.mouse.down();
await page.mouse.move(start.x + 120, start.y + 100, { steps: 5 });
await page.mouse.up();
await expect.poll(async () => (await popup.boundingBox())!.x).toBeCloseTo(before.x + 120, 0);
await expect.poll(async () => (await popup.boundingBox())!.y).toBeCloseTo(before.y + 100, 0);
const moved = (await popup.boundingBox())!;
expect(moved.width).toBeCloseTo(before.width, 0);
expect(moved.height).toBeCloseTo(before.height, 0);
await page.screenshot({ path: test.info().outputPath("usages-after-drag.png") });
await popup.getByRole("button", { name: "Scope", exact: true }).click();
await expect(page.getByRole("option", { name: "Project and Libraries", exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await popup.getByRole("button", { name: "Show Preview", exact: true }).click();
await expect(popup.getByRole("region", { name: "Preview", exact: true })).toBeVisible();
await expect.poll(async () => (await popup.boundingBox())!.x).toBeCloseTo(moved.x, 0);
await expect.poll(async () => (await popup.boundingBox())!.y).toBeCloseTo(moved.y, 0);
const resizeBefore = (await popup.boundingBox())!;
const corner = (await popup.getByRole("separator", { name: "Resize" }).boundingBox())!;
await page.mouse.move(corner.x + 4, corner.y + 4);
await page.mouse.down();
await page.mouse.move(corner.x + 84, corner.y + 64, { steps: 5 });
await page.mouse.up();
await expect.poll(async () => (await popup.boundingBox())!.width).toBeCloseTo(resizeBefore.width + 80, 0);
await expect.poll(async () => (await popup.boundingBox())!.height).toBeCloseTo(resizeBefore.height + 60, 0);
expect((await popup.boundingBox())!.x).toBeCloseTo(moved.x, 0);
expect((await popup.boundingBox())!.y).toBeCloseTo(moved.y, 0);
// Cancelling a press must release the drag before the next pointer move.
const cancelAt = (await title.boundingBox())!;
await page.mouse.move(cancelAt.x + 5, cancelAt.y + 5);
await page.mouse.down();
await page.evaluate(() => window.dispatchEvent(new PointerEvent("pointercancel")));
await page.mouse.move(cancelAt.x + 45, cancelAt.y + 25);
await page.mouse.up();
expect((await popup.boundingBox())!.x).toBeCloseTo(moved.x, 0);
expect((await popup.boundingBox())!.y).toBeCloseTo(moved.y, 0);
// A later drag starts at the new position and clamps at both sides of the viewport.
let handle = (await title.boundingBox())!;
await page.mouse.move(handle.x + 5, handle.y + 5);
await page.mouse.down();
await page.mouse.move(-1000, -1000, { steps: 5 });
await page.mouse.up();
await expect.poll(async () => (await popup.boundingBox())!.x).toBeCloseTo(6, 0);
await expect.poll(async () => (await popup.boundingBox())!.y).toBeCloseTo(6, 0);
handle = (await title.boundingBox())!;
await page.mouse.move(handle.x + 5, handle.y + 5);
await page.mouse.down();
await page.mouse.move(2400, 1600, { steps: 5 });
await page.mouse.up();
const viewport = page.viewportSize()!;
await expect
.poll(async () => {
const box = (await popup.boundingBox())!;
return box.x + box.width;
})
.toBeCloseTo(viewport.width - 6, 0);
await expect
.poll(async () => {
const box = (await popup.boundingBox())!;
return box.y + box.height;
})
.toBeCloseTo(viewport.height - 6, 0);
handle = (await title.boundingBox())!;
await page.mouse.move(handle.x + 5, handle.y + 5);
await page.mouse.down();
await page.keyboard.press("Escape");
await expect(popup).toHaveCount(0);
await expect(page.locator("[data-drag-cursor-surface]")).toHaveCount(0);
await page.mouse.up();
});
test("Show Usages distinguishes same-named files without losing the line or snippet", async ({ workbench: page }) => {
await page.setViewportSize({ width: 480, height: 620 });
await page.evaluate(async () => {
+58
Переглянути файл
@@ -0,0 +1,58 @@
import { expect, stubDesktop, test } from "./fixtures";
const FILE = "/dev/acme-api/line-numbers.txt";
/** Applies rc file lines through the same parser and engine the app uses. */
async function applyRc(page: import("@playwright/test").Page, rc: string) {
await page.evaluate(async (text) => {
// Load the app modules in the browser's Vite realm; the variables keep knip from resolving the URLs.
const enginePath = "/src/features/vim/engine.ts";
const rcPath = "/src/features/vim/rc.ts";
const { applyRcCommands } = await import(enginePath);
const { parseVimrc } = await import(rcPath);
applyRcCommands(parseVimrc(text).commands);
}, rc);
}
test("set relativenumber in the rc file switches the editor's line numbers (#7341)", async ({ page }) => {
test.setTimeout(180_000);
await page.addInitScript(() =>
localStorage.setItem("openidea.vim.v1", JSON.stringify({ enabled: true, handlers: {} })),
);
await page.goto("/");
await expect(page.getByRole("tree", { name: "Project" })).toBeVisible();
await stubDesktop(page);
await page.evaluate(async (path) => {
const backendPath = "/src/editor/core/backend.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(contributionsPath);
docBackend().files.set(path, "a\nb\nc\nd\ne\n");
await editorService().openFile(path);
}, FILE);
const editor = page.locator(".cm-editor").first();
await expect(editor).toHaveAttribute("data-openidea-vim", "true");
const numbers = editor.locator(".cm-lineNumbers .cm-gutterElement:not([style*='visibility: hidden'])");
await editor.locator(".cm-content").click();
await page.keyboard.press("g");
await page.keyboard.press("g");
await page.keyboard.press("j");
await page.keyboard.press("j");
await expect(numbers.filter({ hasText: /^\d+$/ }).first()).toBeVisible();
// `number` follows Settings (absolute numbers on): hybrid, the caret line keeps its number.
await applyRc(page, "set relativenumber");
await expect(numbers.nth(0)).toHaveText("2");
await expect(numbers.nth(2)).toHaveText("3");
await expect(numbers.nth(3)).toHaveText("1");
await applyRc(page, "set nonumber relativenumber");
await expect(numbers.nth(2)).toHaveText("0");
await applyRc(page, "set nonu nornu");
await expect(editor.locator(".cm-lineNumbers")).toHaveCount(0);
await applyRc(page, "");
await expect(numbers.nth(0)).toHaveText("1");
await expect(numbers.nth(2)).toHaveText("3");
});
+72
Переглянути файл
@@ -0,0 +1,72 @@
import type { Page } from "@playwright/test";
import { expect, stubDesktop, test } from "./fixtures";
const FILE = "/dev/acme-api/undo-break.txt";
async function openEditor(page: Page) {
const editor = page.locator(".cm-editor").first();
await expect(editor).toHaveAttribute("data-openidea-vim", "true");
await editor.locator(".cm-content").click();
return editor;
}
/** Applies rc file lines through the same parser and engine the app uses. */
async function applyRc(page: Page, rc: string) {
await page.evaluate(async (text) => {
// Load the app modules in the browser's Vite realm; the variables keep knip from resolving the URLs.
const enginePath = "/src/features/vim/engine.ts";
const rcPath = "/src/features/vim/rc.ts";
const { applyRcCommands } = await import(enginePath);
const { parseVimrc } = await import(rcPath);
applyRcCommands(parseVimrc(text).commands);
}, rc);
}
const documentText = (page: Page) =>
page.evaluate(async () => {
// Load the app module in the browser's Vite realm; the variable keeps knip from resolving the URL.
const apiPath = "/src/editor/api.ts";
const { activeEditor } = await import(apiPath);
return activeEditor()!.view.state.doc.toString();
});
test.beforeEach(async ({ page }) => {
test.setTimeout(180_000);
await page.addInitScript(() =>
localStorage.setItem("openidea.vim.v1", JSON.stringify({ enabled: true, handlers: {} })),
);
await page.goto("/");
await expect(page.getByRole("tree", { name: "Project" })).toBeVisible();
await stubDesktop(page);
await page.evaluate(async (path) => {
const backendPath = "/src/editor/core/backend.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const { docBackend } = await import(backendPath);
const { editorService } = await import(contributionsPath);
docBackend().files.set(path, "one\ntwo\n");
await editorService().openFile(path);
}, FILE);
await openEditor(page);
});
test("inoremap . .<C-g>u inserts only the dot and breaks undo", async ({ page }) => {
await applyRc(page, "inoremap . .<C-g>u");
await page.evaluate(async () => {
const apiPath = "/src/editor/api.ts";
const { activeEditor } = await import(apiPath);
const view = activeEditor()!.view;
view.dispatch({ selection: { anchor: 0 } });
view.focus();
});
await page.keyboard.press("i");
await page.keyboard.type("uno.");
await page.keyboard.type("dos");
await expect.poll(() => documentText(page)).toBe("uno.dosone\ntwo\n");
await page.keyboard.press("Escape");
await page.keyboard.press("u");
await expect.poll(() => documentText(page)).toBe("uno.one\ntwo\n");
await page.keyboard.press("u");
await expect.poll(() => documentText(page)).toBe("one\ntwo\n");
});
+5
Переглянути файл
@@ -75,6 +75,8 @@
"@lezer/lr": "^1.4.11",
"@mathjax/mathjax-tex-font": "4.1.3",
"@mathjax/src": "4.1.3",
"@mdx-js/mdx": "^3.1.0",
"@mdx-js/react": "^3.1.0",
"@plutojl/lang-julia": "^1.2.0",
"@replit/codemirror-vim": "6.4.0",
"@tanstack/react-virtual": "^3.14.21",
@@ -97,6 +99,9 @@
"react-colorful": "5.6.1",
"react-dom": "^19.1.0",
"react-resizable-panels": "^4.14.6",
"remark-frontmatter": "^5.0.0",
"remark-gfm": "^4.0.1",
"sucrase": "^3.35.0",
"zustand": "^5.0.15"
},
"devDependencies": {
+42
Переглянути файл
@@ -0,0 +1,42 @@
diff --git a/vim.js b/vim.js
--- a/vim.js
+++ b/vim.js
@@ -236,6 +236,8 @@
{ keys: '"<register>', type: 'action', action: 'setRegister' },
{ keys: '<C-r><register>', type: 'action', action: 'insertRegister', context: 'insert', isEdit: true },
{ keys: '<C-o>', type: 'action', action: 'oneNormalCommand', context: 'insert' },
+ // OpenIDEA: insert-mode undo break; the host defines this action.
+ { keys: '<C-g>u', type: 'action', action: 'openideaUndoBreak', context: 'insert' },
{ keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }},
{ keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
{ keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }},
@@ -248,6 +250,11 @@
{ keys: '<C-t>', type: 'action', action: 'indent', actionArgs: { indentRight: true }, context: 'insert' },
{ keys: '<C-d>', type: 'action', action: 'indent', actionArgs: { indentRight: false }, context: 'insert' },
// Text object motions
+ // OpenIDEA: function text objects; the host defines the motion. Built in, so a noremap's keys reach them.
+ { keys: 'af', type: 'motion', motion: 'openideaFunction', context: 'operatorPending' },
+ { keys: 'if', type: 'motion', motion: 'openideaFunction', motionArgs: { textObjectInner: true }, context: 'operatorPending' },
+ { keys: 'af', type: 'motion', motion: 'openideaFunction', context: 'visual' },
+ { keys: 'if', type: 'motion', motion: 'openideaFunction', motionArgs: { textObjectInner: true }, context: 'visual' },
{ keys: 'a<register>', type: 'motion', motion: 'textObjectManipulation' },
{ keys: 'i<register>', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},
// Search
@@ -2582,6 +2589,8 @@
if (head.sticky == "before") head.ch--;
return head;
},
+ // OpenIDEA: the host overrides this with the function text object.
+ openideaFunction: function(cm, head) { return head; },
textObjectManipulation: function(cm, head, motionArgs, vim) {
// TODO: lots of possible exceptions that can be thrown here. Try da(
// outside of a () block.
@@ -3423,6 +3432,8 @@
cm.replaceSelection(text);
}
},
+ // OpenIDEA: the host overrides this with the undo-break implementation.
+ openideaUndoBreak: function() {},
oneNormalCommand: function(cm, actionArgs, vim) {
exitInsertMode(cm, true);
vim.insertModeReturn = true;
Створено
+1376 -2
File diff suppressed because it is too large. Load diff
+1
Переглянути файл
@@ -7,3 +7,4 @@ patchedDependencies:
"@codemirror/[email protected]": patches/@[email protected]
"@codemirror/view": patches/@codemirror__view.patch
"@lezer/lr": patches/@lezer__lr.patch
"@replit/[email protected]": patches/@[email protected]
+84 -2
Переглянути файл
@@ -4,7 +4,7 @@
//! Tauri adapters of project-host commands are derived from their `ide-host` declarations. No
//! domain logic lives here.
// `commands::catalogue!` recurses once per command, so the limit grows with the command count.
#![recursion_limit = "512"]
#![recursion_limit = "1024"]
mod application_focus;
#[cfg(target_os = "macos")]
@@ -101,6 +101,9 @@ pub fn run() {
let app_data = ide_host::data_dirs::data_dir(&context.config().identifier).unwrap_or_default();
std::process::exit(ide_mcp::stdio::run(&ide_mcp::discovery_path(&app_data), project));
}
if std::env::args().skip(1).any(|a| a == "--scheduler") {
std::process::exit(run_headless_scheduler(&context.config().identifier));
}
// The `openidea` command: answer and exit, no UI.
if let Some(code) = cli::run(&context.config().identifier) {
std::process::exit(code);
@@ -320,7 +323,13 @@ pub fn run() {
#[cfg(target_os = "macos")]
if let Some(w) = window.try_state::<WindowsState>() {
let settings = ide_host::ops::project::settings_get(&state.host, window.label());
w.keep_alive.store(settings.general.close_without_welcome, std::sync::atomic::Ordering::SeqCst);
let keep_for_automations = settings.agents.automations.auto_start_service
&& settings.agents.automations.keep_alive_in_background
&& state.host.automations.has_enabled_schedules();
w.keep_alive.store(
settings.general.close_without_welcome || keep_for_automations,
std::sync::atomic::Ordering::SeqCst,
);
}
let reason = match window.try_state::<WindowsState>() {
Some(w) if w.restart_requested() => ide_agent::AgentShutdownReason::Restart,
@@ -469,3 +478,76 @@ pub(crate) fn dispatch_menu_action(app: &tauri::AppHandle, id: &str) {
},
}
}
fn run_headless_scheduler(identifier: &str) -> i32 {
logging::init(identifier);
let _ = ide_host::shell_env::inherit_login_shell_path(identifier);
let Ok(config_dir) = ide_host::data_dirs::config_dir(identifier) else { return 1 };
let Ok(data_dir) = ide_host::data_dirs::data_dir(identifier) else { return 1 };
let Ok(local_data_dir) = ide_host::data_dirs::startup_local_data_dir(identifier) else { return 1 };
let _ = std::fs::create_dir_all(&config_dir);
let _ = std::fs::create_dir_all(&data_dir);
let _ = std::fs::create_dir_all(&local_data_dir);
ide_tools::extend_process_path(&local_data_dir);
let Ok(languages) = ide_language::LanguageRegistry::load(Some(&config_dir.join("languages"))) else {
return 1;
};
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("tokio runtime");
runtime.block_on(async move {
let host = Arc::new(ide_host::Host::new(ide_host::HostConfig {
config_dir,
data_dir,
local_data_dir,
languages: Arc::new(languages),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
host.mcp.apply(&host);
host.automations.set_headless_worker_mode(true);
host.automations.start(&host);
let mut idle_ticks = 0u32;
let mut check = tokio::time::interval(std::time::Duration::from_secs(5));
#[cfg(unix)]
let mut terminate =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).expect("SIGTERM listener");
loop {
#[cfg(unix)]
tokio::select! {
_ = tokio::signal::ctrl_c() => break,
_ = terminate.recv() => break,
_ = check.tick() => {}
}
#[cfg(not(unix))]
tokio::select! {
_ = tokio::signal::ctrl_c() => break,
_ = check.tick() => {}
}
let service_enabled = ide_workspace::SettingsStore::load(&host.config_dir, None)
.effective()
.agents
.automations
.auto_start_service;
let running = host.automations.has_running_runs();
if host.automations.worker_stop_requested() || !service_enabled {
if !running {
break;
}
} else if host.automations.has_enabled_schedules() || running {
idle_ticks = 0;
} else {
idle_ticks += 1;
if idle_ticks >= 3 {
break;
}
}
}
host.automations.stop();
host.shutdown_notebooks_on_exit();
host.stop_processes_on_exit();
host.mcp.stop(&host);
0
})
}
+33 -7
Переглянути файл
@@ -46,6 +46,14 @@ pub const FRAME_HOST_PATH: &str = ".frame";
const FRAME_HOST_CSP: &str = "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline'; \
style-src 'unsafe-inline'; img-src data:; font-src data:; media-src data:";
/// The host page of sandboxed MDX previews (`MDX_FRAME_HOST_PATH` / `MDX_FRAME_CSP` in
/// src/platform/sandboxFrame.ts), adding `blob:` for local workspace media streams without
/// widening plugin view pages.
pub const MDX_FRAME_HOST_PATH: &str = ".mdx-frame";
const MDX_FRAME_HOST_CSP: &str = "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline'; \
style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src data: blob:";
const FRAME_HOST: &str = r#"<!doctype html><meta charset="utf-8"><script>
addEventListener("message", (e) => {
const d = e.data;
@@ -90,16 +98,23 @@ pub fn handle<R: Runtime>(ctx: UriSchemeContext<'_, R>, request: Request<Vec<u8>
});
}
fn frame_host_response(csp: &str) -> Response<Vec<u8>> {
Response::builder()
.header(header::CONTENT_TYPE, "text/html; charset=utf-8")
.header(header::CONTENT_SECURITY_POLICY, csp)
.header(header::CACHE_CONTROL, "no-cache")
.header("X-Content-Type-Options", "nosniff")
.body(FRAME_HOST.as_bytes().to_vec())
.unwrap_or_else(|_| status(StatusCode::INTERNAL_SERVER_ERROR))
}
fn serve(plugins: &ide_host::plugins::PluginHost, path: &str) -> Response<Vec<u8>> {
let decoded = percent_encoding::percent_decode_str(path.trim_start_matches('/')).decode_utf8_lossy();
if decoded == FRAME_HOST_PATH {
return Response::builder()
.header(header::CONTENT_TYPE, "text/html; charset=utf-8")
.header(header::CONTENT_SECURITY_POLICY, FRAME_HOST_CSP)
.header(header::CACHE_CONTROL, "no-cache")
.header("X-Content-Type-Options", "nosniff")
.body(FRAME_HOST.as_bytes().to_vec())
.unwrap_or_else(|_| status(StatusCode::INTERNAL_SERVER_ERROR));
return frame_host_response(FRAME_HOST_CSP);
}
if decoded == MDX_FRAME_HOST_PATH {
return frame_host_response(MDX_FRAME_HOST_CSP);
}
let Some((plugin, rest)) = decoded.split_once('/') else { return status(StatusCode::NOT_FOUND) };
match plugins.web_file(plugin, rest) {
@@ -166,8 +181,19 @@ mod tests {
let frame = include_str!("../../src/features/plugins/views/frame.ts");
let csp = frame.split("FRAME_CSP =").nth(1).and_then(|s| s.split('"').nth(1)).unwrap();
assert_eq!(FRAME_HOST_CSP.strip_prefix("sandbox allow-scripts; ").unwrap(), csp);
assert!(!FRAME_HOST_CSP.contains("blob:"), "plugin frame host must not allow blob: {FRAME_HOST_CSP}");
let tag = frame.split("FRAME_TAG =").nth(1).and_then(|s| s.split('"').nth(1)).unwrap();
assert!(FRAME_HOST.contains(&format!("d.tag !== \"{tag}\"")), "{FRAME_HOST}");
assert!(frame.contains(&format!("FRAME_HOST_PATH = \"{FRAME_HOST_PATH}\"")));
}
#[test]
fn the_mdx_frame_host_follows_sandbox_frame() {
let sandbox = include_str!("../../src/platform/sandboxFrame.ts");
let csp = sandbox.split("MDX_FRAME_CSP =").nth(1).and_then(|s| s.split('"').nth(1)).unwrap();
assert_eq!(MDX_FRAME_HOST_CSP.strip_prefix("sandbox allow-scripts; ").unwrap(), csp);
let tag = sandbox.split("SANDBOX_FRAME_TAG =").nth(1).and_then(|s| s.split('"').nth(1)).unwrap();
assert!(FRAME_HOST.contains(&format!("d.tag !== \"{tag}\"")), "{FRAME_HOST}");
assert!(sandbox.contains(&format!("MDX_FRAME_HOST_PATH = \"{MDX_FRAME_HOST_PATH}\"")));
}
}
+1
Переглянути файл
@@ -118,6 +118,7 @@ impl AppState {
let announce = global_sink.clone();
host.set_background_projects_observer(Arc::new(move || announce.emit(IdeEvent::McpBackgroundProjectsChanged)));
host.start_background_sweeper();
host.automations.start(&host);
Ok(Self {
recent: RecentProjects::load(&config_dir),
updates: Default::default(),
+1 -1
Переглянути файл
@@ -26,7 +26,7 @@
}
],
"security": {
"csp": "default-src 'self'; img-src 'self' asset: data: blob: http: https:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src ipc: http://ipc.localhost; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:; frame-src http://127.0.0.1:* openidea-plugin: http://openidea-plugin.localhost; frame-ancestors 'none'; base-uri 'self'; form-action 'none'"
"csp": "default-src 'self'; img-src 'self' asset: data: blob: http: https:; media-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src ipc: http://ipc.localhost; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:; frame-src http://127.0.0.1:* openidea-plugin: http://openidea-plugin.localhost; frame-ancestors 'none'; base-uri 'self'; form-action 'none'"
}
},
"bundle": {
+17
Переглянути файл
@@ -35,6 +35,23 @@ const OFF_MAIN_THREAD: &[&str] = &[
"agent_memory_promote",
"agent_memory_delete",
"agent_memory_reset_provider",
"agent_plugins_list",
"agent_plugins_set_enabled",
"agent_plugins_add_marketplace",
"agent_plugins_remove_marketplace",
"agent_plugins_browse_marketplace",
"agent_plugins_preview",
"agent_plugins_install",
"agent_automation_snapshot",
"agent_automation_save",
"agent_automation_set_enabled",
"agent_automation_pause_all",
"agent_automation_delete",
"agent_automation_run_now",
"agent_automation_runs",
"agent_automation_mark_read",
"agent_automation_export_markdown",
"agent_automation_import_markdown",
"plugin_post_events",
"plugin_secrets",
"plugin_set_active_file",
+23
Переглянути файл
@@ -3,6 +3,17 @@
agent_accept_changes trusted project_host bindings async
agent_answer_question trusted project_host bindings async
agent_archive always project_host bindings sync
agent_automation_delete trusted project_host bindings async
agent_automation_export_markdown trusted project_host bindings async
agent_automation_import_markdown trusted project_host bindings async
agent_automation_mark_read trusted project_host bindings async
agent_automation_pause_all trusted project_host bindings async
agent_automation_preview_schedule always project_host bindings async
agent_automation_run_now trusted project_host bindings async
agent_automation_runs always project_host bindings async
agent_automation_save trusted project_host bindings async
agent_automation_set_enabled trusted project_host bindings async
agent_automation_snapshot always project_host bindings async
agent_base_text trusted project_host bindings async
agent_cancel always project_host bindings sync
agent_changes trusted project_host bindings async
@@ -43,6 +54,13 @@ agent_memory_promote trusted project_host bin
agent_memory_reset_provider always project_host bindings async
agent_memory_set_auto always project_host bindings async
agent_memory_set_mode always project_host bindings async
agent_plugins_add_marketplace always project_host bindings async
agent_plugins_browse_marketplace always project_host bindings async
agent_plugins_install always project_host bindings async
agent_plugins_list always project_host bindings async
agent_plugins_preview always project_host bindings async
agent_plugins_remove_marketplace always project_host bindings async
agent_plugins_set_enabled always project_host bindings async
agent_poke_network always project_host bindings sync
agent_preview_copilot_models trusted project_host bindings async
agent_probe trusted project_host bindings async
@@ -60,6 +78,10 @@ agent_resume_task trusted project_host bin
agent_rollback trusted project_host bindings async
agent_rollback_changes trusted project_host bindings async
agent_send_queued_now trusted project_host bindings async
agent_session_schedule_create trusted project_host bindings async
agent_session_schedule_delete trusted project_host bindings async
agent_session_schedule_run_now trusted project_host bindings async
agent_session_schedule_set_paused trusted project_host bindings async
agent_set_additional_args trusted project_host bindings sync
agent_set_auto_resume_once trusted project_host bindings async
agent_set_command trusted project_host bindings sync
@@ -319,6 +341,7 @@ flutter_devices_refresh trusted project_host bin
flutter_devtools_url trusted project_host bindings async
flutter_emulator_launch trusted project_host bindings async
flutter_widget_preview_url trusted project_host bindings async
fs_canonicalize always project_host bindings async
fs_compare_directories always project_host bindings async
fs_copy always project_host bindings async
fs_copy_merge always project_host bindings async
File diff suppressed because it is too large. Load diff
+1
Переглянути файл
@@ -42,6 +42,7 @@ import { rootOfPath } from "@/platform/projectRoots";
import { isVirtualUri } from "@/platform/virtualDocs";
import { cornerInset } from "@/editor/core/cm/cornerInset";
export { iconAreaSource, mapLineStart, type IconAreaSource } from "@/editor/core/cm/iconArea";
export { lineNumberOption, setLineNumberOptions, type LineNumberOptions } from "@/editor/core/cm/lineNumberOptions";
export {
invalidateNavigationProviders,
navigationEpoch,
+10
Переглянути файл
@@ -175,6 +175,7 @@ const EXT_LANG: Record<string, string> = {
go: "go",
json: "json",
md: "markdown",
mdx: "mdx",
adoc: "asciidoc",
asciidoc: "asciidoc",
rst: "restructuredtext",
@@ -304,6 +305,15 @@ const MEM_LANGUAGES: LanguageInfo[] = [
blockComment: ["<!--", "-->"],
indent: null,
},
{
id: "mdx",
name: "MDX",
extensions: ["mdx"],
uiMode: "Markdown",
lineComment: null,
blockComment: ["{/*", "*/}"],
indent: { tabSize: 2, insertSpaces: true },
},
{
id: "yaml",
name: "YAML",
+140 -2
Переглянути файл
@@ -7,7 +7,8 @@ import { buildParserFile } from "@lezer/generator";
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
import { findLanguageDescription, loadSupport } from "../languages";
import { pasteReindentFilter } from "../prefs";
import { astro, astroLanguage } from "./index";
import { TreeFragment, type Tree } from "@lezer/common";
import { astro, astroLanguage, maskTagExpressions } from "./index";
const highlighter = tagHighlighter([
{ tag: t.processingInstruction, class: "fence" },
@@ -36,6 +37,32 @@ function tokens(doc: string): string[] {
return out;
}
/** The text of each HTML attribute in `tree` of `doc`, expressions' trees left out. */
function attributesOf(tree: Tree, doc: string): string[] {
const out: string[] = [];
tree.iterate({
enter: (n) => {
if (n.name === "Attribute") out.push(doc.slice(n.from, n.to));
return n.name !== "Script";
},
});
return out;
}
const attributes = (doc: string) => attributesOf(astroLanguage.parser.parse(doc), doc);
/** Whether HTML marked anything in `doc` as an error. */
function htmlErrors(doc: string): boolean {
let found = false;
astroLanguage.parser.parse(doc).iterate({
enter: (n) => {
if (n.type.isError) found = true;
return n.name !== "Script";
},
});
return found;
}
/** A layout with what made HTML mode misread Astro components. */
const LAYOUT = `---
import '@/styles/global.css'
@@ -126,6 +153,114 @@ describe("Astro components", () => {
expect(out).toContain('"{literal}":value');
});
// Each case: the component, its HTML attributes, and tokens it must have.
const TAG_EXPRESSIONS: [string, string, string[], string[]][] = [
[
"the issue's multi-line class:list",
'<div\n class:list={[\n "relative flex w-full flex-col",\n card.textClass,\n ]}\n>\n <b>x</b>\n</div>',
['class:list={[\n "relative flex w-full flex-col",\n card.textClass,\n ]}'],
['"relative flex w-full flex-col":str', "card:var", "textClass:prop", "b:tag"],
],
[
"class:list and set:html in one tag",
'<h3 class:list={["font-bold", card.titleClass]} set:html={card.title} />\n<p>{card.lead}</p>',
['class:list={["font-bold", card.titleClass]}', "set:html={card.title}"],
['"font-bold":str', "titleClass:prop", "title:prop", "p:tag", "lead:prop"],
],
[
"a call with a quoted string",
'<a href={f("x y")} title="t">z</a>',
['href={f("x y")}', 'title="t"'],
["f:call", '"x y":str', '"t":value'],
],
[
"a spread and a shorthand",
"<C {...props} {name} client:load />",
["{...props}", "{name}", "client:load"],
["props:var", "name:var", "client:load:attr"],
],
[
"nested braces and brackets",
'<C a={{ b: [1, { c: "d e" }] }} f="g" />',
['a={{ b: [1, { c: "d e" }] }}', 'f="g"'],
['"d e":str', '"g":value'],
],
["a brace in a string", '<C a={"} >"} b={x} />', ['a={"} >"}', "b={x}"], ['"} >":str', "x:var"]],
[
"a brace in a template literal",
"<C a={`} ${b + '}'} >`} c={d} />",
["a={`} ${b + '}'} >`}", "c={d}"],
["b:var", "'}':str", "d:var"],
],
["an escaped quote", '<C a={"x \\" }"} b={y} />', ['a={"x \\" }"}', "b={y}"], ["y:var"]],
[
"a comment with a quote",
"<C a={/* it's } */ x} b={y} />",
["a={/* it's } */ x}", "b={y}"],
["/* it's } */:comment", "x:var", "y:var"],
],
[
"an arrow function with markup",
"<C render={(i) => <li class={i}>{i > 1}</li>} />\n<p>ok</p>",
["render={(i) => <li class={i}>{i > 1}</li>}"],
["li:tag", "class:attr", ">:op", "p:tag"],
],
[
"an expression among quoted attributes",
'<img src="a b.png" alt={t("img alt")} loading=\'lazy\' />',
['src="a b.png"', 'alt={t("img alt")}', "loading='lazy'"],
['"a b.png":value', '"img alt":str', "'lazy':value"],
],
[
"a tag expression in a text expression",
'{ok && <b class:list={["x y", c]}>{n}</b>}',
['class:list={["x y", c]}'],
["ok:var", '"x y":str', "c:var", "n:var"],
],
["braces in a comment", '<!-- <a b={"x y"}> -->\n<p>t</p>', [], ["p:tag"]],
];
it.each(TAG_EXPRESSIONS)("parses tag expressions: %s", (_, doc, attrs, toks) => {
expect(attributes(doc)).toEqual(attrs);
expect(tokens(doc)).toEqual(expect.arrayContaining(toks));
expect(htmlErrors(doc)).toBe(false);
});
it("leaves an unclosed tag expression to HTML, so the markup after it stays markup", () => {
const doc = '<div a={\n<p class="x">{t}</p>\n<b c={"y z"}>w</b>';
expect(attributes(doc)).toEqual(["a={", 'class="x"', 'c={"y z"}']);
expect(tokens(doc)).toEqual(expect.arrayContaining(["p:tag", "t:var", '"y z":str', "b:tag"]));
});
it("leaves script, style and attribute text unmasked", () => {
const doc = '<script>\n const s = "<a b={c d}>"\n</script>\n<style>a{b:c}</style>\n<p title="{x y}">';
expect(maskTagExpressions(doc)).toBe(doc);
expect(maskTagExpressions('<a b={c "d"}>')).toBe("<a b={c__d_}>");
});
it("reparses an edited tag expression like a fresh parse", () => {
const before = '<h3 class:list={["a", c]} />\n<p>{x}</p>\n<b>y</b>';
const parse = (doc: string) => astroLanguage.parser.parse(doc);
let tree = parse(before);
let doc = before;
// Type `{"m n"` then `}` after `<p `, then delete them again.
for (const [from, to, insert] of [
[before.indexOf("<p") + 2, before.indexOf("<p") + 2, ' a={"m n"'],
[before.indexOf("<p") + 11, before.indexOf("<p") + 11, "}"],
[before.indexOf("<p") + 2, before.indexOf("<p") + 12, ""],
] as const) {
const next = doc.slice(0, from) + insert + doc.slice(to);
const fragments = TreeFragment.applyChanges(TreeFragment.addTree(tree), [
{ fromA: from, toA: to, fromB: from, toB: from + insert.length },
]);
tree = astroLanguage.parser.parse(next, fragments);
doc = next;
expect(attributesOf(tree, doc)).toEqual(attributes(doc));
expect(tree.toString()).toBe(parse(doc).toString());
}
expect(doc).toBe(before);
});
it("parses scripts as TypeScript and leaves styles to CSS", () => {
const out = tokens("<script>\n const n: number = 1\n</script>\n<style>\n p { color: red; }\n</style>");
expect(out).toEqual(expect.arrayContaining(["const:def-kw", "number:type", "script:tag", "style:tag"]));
@@ -139,7 +274,10 @@ describe("Astro components", () => {
const state = EditorState.create({
extensions: [astro(), indentUnit.of(" "), EditorState.tabSize.of(2), pasteReindentFilter("indentEachLine")],
});
const pasted = state.update({ changes: { from: 0, insert: LAYOUT }, userEvent: "input.paste" }).state;
const pasted = state.update({
changes: { from: 0, insert: LAYOUT },
userEvent: "input.paste",
}).state;
expect(pasted.doc.toString()).toBe(LAYOUT);
} finally {
vi.useRealTimers();
+157 -8
Переглянути файл
@@ -7,7 +7,16 @@ import { LRLanguage, LanguageSupport } from "@codemirror/language";
import { html } from "@codemirror/lang-html";
import { tsxLanguage, typescriptLanguage } from "@codemirror/lang-javascript";
import { styleTags, tags as t } from "@lezer/highlight";
import { IterMode, parseMixed, type Input, type NestedParse, type SyntaxNodeRef } from "@lezer/common";
import {
IterMode,
Parser,
parseMixed,
type Input,
type NestedParse,
type PartialParse,
type SyntaxNodeRef,
type TreeFragment,
} from "@lezer/common";
import { JS_TAGS } from "../jsTags";
import { parser } from "./parser";
@@ -46,17 +55,16 @@ function pushRange(out: Range[], from: number, to: number) {
/**
* Appends to `out` the parts of `text`, which starts at `from`, inside `{…}`,
* braces included. Strings count only inside braces, so prose apostrophes
* stay text; in a tag (`attrQuotes`), quotes outside braces delimit attribute
* values, whose braces are literal.
* stay text.
*/
function scanBraces(text: string, from: number, scan: Scan, out: Range[], attrQuotes = false) {
function scanBraces(text: string, from: number, scan: Scan, out: Range[]) {
let start = scan.depth > 0 ? 0 : -1;
for (let i = 0; i < text.length; i++) {
const ch = text.charCodeAt(i);
if (scan.quote) {
if (ch === BACKSLASH && scan.depth > 0) i++;
else if (ch === scan.quote) scan.quote = 0;
} else if (QUOTES.has(ch) && (scan.depth > 0 || attrQuotes)) {
} else if (QUOTES.has(ch) && scan.depth > 0) {
scan.quote = ch;
} else if (ch === BRACE_L) {
if (scan.depth++ === 0) start = i;
@@ -95,10 +103,74 @@ function textExpressions(node: SyntaxNodeRef, input: Input): Range[] | null {
return out.length ? out : null;
}
/** The expressions in a tag: values, shorthands and spreads, also with spaces, which split HTML attributes. */
const SLASH = 47,
STAR = 42,
DOLLAR = 36,
BACKTICK = 96,
NEWLINE = 10;
/** What ends an HTML attribute name or unquoted value. */
const ATTR_BREAK = /[\s"'<>`=/]/g;
const TAG_NAME = /\/?([a-zA-Z][^\s/>]*)/y;
const RAW_TEXT = new Set(["script", "style", "textarea"]);
/**
* The end of the expression whose `{` is at `start`, past its `}`, or -1
* when it isn't closed. Strings and comments may hold braces; quoted strings
* end with their line, so an unclosed one doesn't run on.
*/
function expressionEnd(s: string, start: number): number {
// Open braces, and the template literals that `${` nests in.
const open: number[] = [];
for (let i = start; i < s.length; i++) {
const ch = s.charCodeAt(i);
if (open[open.length - 1] === BACKTICK) {
if (ch === BACKSLASH) i++;
else if (ch === BACKTICK) open.pop();
else if (ch === DOLLAR && s.charCodeAt(i + 1) === BRACE_L) {
open.push(BRACE_L);
i++;
}
} else if (ch === BRACE_L || ch === BACKTICK) {
open.push(ch);
} else if (ch === BRACE_R) {
open.pop();
if (!open.length) return i + 1;
} else if (ch === 34 || ch === 39) {
for (i++; i < s.length && s.charCodeAt(i) !== ch && s.charCodeAt(i) !== NEWLINE; i++) {
if (s.charCodeAt(i) === BACKSLASH) i++;
}
} else if (ch === SLASH && s.charCodeAt(i + 1) === SLASH) {
i = s.indexOf("\n", i);
if (i < 0) return -1;
} else if (ch === SLASH && s.charCodeAt(i + 1) === STAR) {
i = s.indexOf("*/", i + 2) + 1;
if (i <= 0) return -1;
}
}
return -1;
}
/**
* The expressions in a tag: values, shorthands and spreads. Quotes outside
* braces delimit attribute values, whose braces are literal; an unclosed
* expression runs to the end of the tag.
*/
function tagExpressions(node: SyntaxNodeRef, input: Input): Range[] | null {
const out: Range[] = [];
scanBraces(input.read(node.from, node.to), node.from, { depth: 0, quote: 0 }, out, true);
const text = input.read(node.from, node.to);
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (ch === '"' || ch === "'") {
i = text.indexOf(ch, i + 1);
if (i < 0) break;
} else if (ch === "{") {
const end = expressionEnd(text, i);
out.push({ from: node.from + i, to: node.from + (end < 0 ? text.length : end) });
if (end < 0) break;
i = end - 1;
}
}
return out.length ? out : null;
}
@@ -116,7 +188,84 @@ function mixExpressions(node: SyntaxNodeRef, input: Input): NestedParse | null {
return null;
}
const templateParser = (templateHTML.language as LRLanguage).parser.configure({ wrap: parseMixed(mixExpressions) });
/**
* `text` with each `{…}` in a tag made one HTML attribute name or value: the
* characters that would end one become `_`, keeping offsets. HTML would end
* `class:list={["a b"]}` at the quote and read the rest of the tag as text.
* An unclosed `{` is left alone, so typing one doesn't swallow the file.
*/
export function maskTagExpressions(text: string): string {
let out = "",
copied = 0;
for (let i = text.indexOf("<"); i >= 0; i = text.indexOf("<", i)) {
i++;
if (text.startsWith("!--", i)) {
i = text.indexOf("-->", i + 3);
if (i < 0) break;
continue;
}
TAG_NAME.lastIndex = i;
const name = TAG_NAME.exec(text);
if (!name) continue;
for (i = TAG_NAME.lastIndex; i < text.length; i++) {
const ch = text[i];
if (ch === ">" || ch === "<") break;
if (ch === '"' || ch === "'") {
i = text.indexOf(ch, i + 1);
if (i < 0) i = text.length;
} else if (ch === "{") {
const end = expressionEnd(text, i);
if (end < 0) continue;
out += text.slice(copied, i) + text.slice(i, end).replace(ATTR_BREAK, "_");
copied = end;
i = end - 1;
}
}
// Script, style and textarea text holds no tags; `<script />` holds none at all.
const tag = name[1]!.toLowerCase();
if (text[i] === ">" && text[i - 1] !== "/" && !name[0].startsWith("/") && RAW_TEXT.has(tag)) {
const close = text.toLowerCase().indexOf("</" + tag, i);
if (close < 0) break;
i = close;
}
}
return copied ? out + text.slice(copied) : text;
}
/** `base` with `text`, its masked template from `from`, in place of the template. */
function maskedInput(base: Input, from: number, text: string): Input {
const to = from + text.length;
return {
length: base.length,
lineChunks: false,
chunk: (pos) => (pos >= from && pos < to ? text.slice(pos - from) : base.chunk(pos)),
read: (a, b) => (a >= from && b <= to ? text.slice(a - from, b - from) : base.read(a, b)),
};
}
const htmlParser = (templateHTML.language as LRLanguage).parser;
const mixer = parseMixed(mixExpressions);
/**
* HTML reads the masked template, so expressions in tags are whole attributes,
* and the expressions mounted on its tree read the real text.
*/
class TemplateParser extends Parser {
createParse(
input: Input,
fragments: readonly TreeFragment[],
ranges: readonly { from: number; to: number }[],
): PartialParse {
// Masks the whole template on each parse, which is linear in its length.
const from = ranges[0]!.from,
text = input.read(from, ranges[ranges.length - 1]!.to),
masked = maskTagExpressions(text);
const htmlInput = masked === text ? input : maskedInput(input, from, masked);
return mixer(htmlParser.startParse(htmlInput, fragments, ranges), input, fragments, ranges);
}
}
const templateParser = new TemplateParser();
const componentParser = parser.configure({
props: [styleTags({ FrontmatterFence: t.processingInstruction })],
+44 -1
Переглянути файл
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent } from "@testing-library/react";
import { EditorState, RangeSet, StateEffect, StateField } from "@codemirror/state";
import { EditorView, GutterMarker } from "@codemirror/view";
import { SETTLE_MS, iconAreaExtension, iconAreaSource, mapLineStart } from "./iconArea";
import { GUTTER_ICON_SIZE, SETTLE_MS, iconAreaExtension, iconAreaSource, mapLineStart } from "./iconArea";
class Dot extends GutterMarker {
constructor(readonly name: string) {
@@ -169,3 +169,46 @@ it("moves a line's marker down with its text when Enter is pressed at the line's
// Joined into the line above, it goes with its text.
expect(after(1, "", lineB)).toBe(0);
});
describe("icon size under font zoom", () => {
// The px the CSS resolves to for an editor font of `font` px.
function sizeAt(font: number): number {
const m =
/^clamp\((\d+)px, calc\(var\(--openidea-editor-font-size, var\(--fs-code\)\) \+ (\d+)px\), (\d+)px\)$/.exec(
GUTTER_ICON_SIZE,
);
if (!m) throw new Error(`unexpected size: ${GUTTER_ICON_SIZE}`);
return Math.min(Number(m[3]), Math.max(Number(m[1]), font + Number(m[2])));
}
it.each([
[13, 14], // default font: the 14px icons
[7, 10], // zoomed out to the smallest font: kept clickable
[9, 10],
[10, 11],
[16, 17],
[20, 21],
[31, 32],
[49, 32], // zoomed in to the largest font: capped
])("a %ipx font gives %ipx icons", (font, size) => {
expect(sizeAt(font)).toBe(size);
});
const css = () => [...document.querySelectorAll("style")].map((s) => s.textContent).join("\n");
it("sets the size on the editor and sizes the spacer, so lines with and without icons stay aligned", () => {
open([{ order: 10, markers: (view) => RangeSet.of([new Dot("run").range(lineStart(view.state, 1))]) }]);
expect(css()).toContain(`--openidea-gutter-icon-size: ${GUTTER_ICON_SIZE}`);
expect(css()).toMatch(/\.cm-openidea-iconSpacer \{[^}]*width: var\(--openidea-gutter-icon-size, 14px\)/);
});
it("scales the 14px and 12px icon markup in the icon gutters, keeping the play glyph's ratio", () => {
open([]);
expect(css()).toMatch(
/\.cm-openidea-iconArea svg\[width="14"\][^{]*\{[^}]*width: var\(--openidea-gutter-icon-size, 14px\)/,
);
expect(css()).toMatch(
/\.cm-openidea-db-gutter svg\[width="12"\][^{]*\{[^}]*width: calc\(var\(--openidea-gutter-icon-size, 14px\) \* 6 \/ 7\)/,
);
});
});
+22 -1
Переглянути файл
@@ -138,7 +138,28 @@ const areaGutter = gutter({
},
});
/**
* The size of a gutter icon, as IDEA scales its gutter icons with the editor font: 14px at the
* default 13px font, one px larger than the font when zoomed, within 10..32px so icons stay
* clickable when zoomed out and don't crowd the code when zoomed in. Whole px, so SVGs stay crisp.
*/
export const GUTTER_ICON_SIZE = "clamp(10px, calc(var(--openidea-editor-font-size, var(--fs-code)) + 1px), 32px)";
const iconSize = "var(--openidea-gutter-icon-size, 14px)";
const smallIcon = `calc(${iconSize} * 6 / 7)`;
/** The gutters of icons: this area, and the run columns of `.http`, GraphQL and database consoles. */
const iconGutters = [
".cm-openidea-iconArea",
".cm-openidea-gutter-http",
".cm-openidea-gutter-graphql",
".cm-openidea-db-gutter",
];
const areaTheme = EditorView.baseTheme({
// On the editor, so every gutter (and the icons' wrappers in feature CSS) reads one size.
"&": { "--openidea-gutter-icon-size": GUTTER_ICON_SIZE },
// Icon markup carries a fixed 14px (12px for the plain play glyph, see `gutterIconMarkup`).
[iconGutters.map((g) => `${g} svg[width="14"]`).join(", ")]: { width: iconSize, height: iconSize },
[iconGutters.map((g) => `${g} svg[width="12"]`).join(", ")]: { width: smallIcon, height: smallIcon },
".cm-openidea-iconArea .cm-gutterElement": {
display: "flex",
alignItems: "center",
@@ -152,7 +173,7 @@ const areaTheme = EditorView.baseTheme({
},
// The spacer's icons are laid out as the line's own.
".cm-openidea-iconAreaSpacer": { display: "contents" },
".cm-openidea-iconSpacer": { display: "inline-block", width: "14px" },
".cm-openidea-iconSpacer": { display: "inline-block", width: iconSize },
});
/** Installed in every editor; empty (no width) while no source has markers or reserves room. */
+42
Переглянути файл
@@ -0,0 +1,42 @@
/**
* Vim's `number` / `relativenumber` over Settings › Editor › General › Appearance ›
* Show line numbers, as IdeaVim maps them onto every editor: an option the rc file
* (or `:set`) leaves alone keeps following Settings, and nothing is written back to
* Settings. Vim mode publishes the options it set here; null while it is off.
*/
import { create } from "zustand";
export interface LineNumberOptions {
number?: boolean;
relativenumber?: boolean;
}
export const useLineNumberOptions = create<{ options: LineNumberOptions | null }>(() => ({ options: null }));
export function setLineNumberOptions(options: LineNumberOptions | null) {
const empty = !options || (options.number === undefined && options.relativenumber === undefined);
useLineNumberOptions.setState({ options: empty ? null : { ...options } });
}
interface ShownLineNumbers {
lineNumbers: boolean;
lineNumberMode: string;
}
/** Vim's view of Settings: `number` is on for absolute and hybrid numbers, `relativenumber` for relative and hybrid. */
export function lineNumberOption(name: keyof LineNumberOptions, settings: ShownLineNumbers): boolean {
const set = useLineNumberOptions.getState().options?.[name];
if (set !== undefined) return set;
return settings.lineNumbers && settings.lineNumberMode !== (name === "number" ? "relative" : "absolute");
}
/** The line numbers editors show: Settings, unless Vim set `number` or `relativenumber` (both on: hybrid, as in Vim). */
export function shownLineNumbers(settings: ShownLineNumbers): ShownLineNumbers {
if (!useLineNumberOptions.getState().options) return settings;
const number = lineNumberOption("number", settings);
const relative = lineNumberOption("relativenumber", settings);
return {
lineNumbers: number || relative,
lineNumberMode: number && relative ? "hybrid" : relative ? "relative" : "absolute",
};
}
+2 -1
Переглянути файл
@@ -81,6 +81,7 @@ export {
type LocalAppearanceOverride,
} from "./localAppearance";
import { GUTTER_ICON_GROUPS, type EffectiveAppearance, type LocalAppearanceOverride } from "./localAppearance";
import { shownLineNumbers } from "./lineNumberOptions";
// --- soft wraps ---------------------------------------------------------------
@@ -619,7 +620,7 @@ export function effectiveAppearance(
override?: LocalAppearanceOverride | null,
): EffectiveAppearance {
return {
lineNumbers: override?.lineNumbers ?? prefs.appearance.lineNumbers,
lineNumbers: override?.lineNumbers ?? shownLineNumbers(prefs.appearance).lineNumbers,
whitespaces: override?.whitespaces ?? !!showWhitespace,
gutterIcons: override?.gutterIcons ?? prefs.showGutterIcons,
indentGuides: override?.indentGuides ?? prefs.appearance.indentGuides,
+1 -1
Переглянути файл
@@ -916,7 +916,7 @@ const docsTheme = EditorView.theme({
alignItems: "center",
justifyContent: "center",
// An icon's width, like the other icons of the area, so showing it doesn't widen the area.
width: "14px",
width: "var(--openidea-gutter-icon-size, 14px)",
height: "var(--openidea-editor-line-height, var(--lh-code))",
padding: "0",
border: "none",
+2 -1
Переглянути файл
@@ -68,6 +68,7 @@ import { overwriteField } from "./overwrite";
import { imeSyllableSpaces } from "./imeCommit";
import { stickySelectionField } from "./stickySelection";
import { horizontalScrollHold } from "./horizontalScrollHold";
import { shownLineNumbers } from "./lineNumberOptions";
import { relativeLineNumbers } from "./relativeLineNumbers";
import { clipboardDocumentPath, clipboardFilesExtension } from "./clipboard";
import { primarySelectionYield } from "./primarySelection";
@@ -281,7 +282,7 @@ export function heavyExtension(
}
export function lineNumbersExtension(settings: EditorSettings | undefined, override?: boolean | null): Extension {
const a = prefsOf(settings).appearance;
const a = shownLineNumbers(prefsOf(settings).appearance);
if (!(override ?? a.lineNumbers) || isDistractionFree()) return [];
return a.lineNumberMode === "relative" || a.lineNumberMode === "hybrid"
? relativeLineNumbers(a.lineNumberMode === "hybrid")
+3
Переглянути файл
@@ -52,6 +52,7 @@ import {
type TextEditorWrapperContribution,
} from "@/workbench/contributions";
import { useDistractionFree } from "@/workbench/distractionFree";
import { useLineNumberOptions } from "./cm/lineNumberOptions";
import { restoreMaximizedToolWindow } from "@/workbench/toolwindows/store";
import { ask, confirm } from "@/workbench/messages";
import { t, tx } from "@/platform/i18n";
@@ -507,6 +508,8 @@ export class EditorController implements SlotHost {
);
// Gutter, centred column and sticky lines follow Distraction Free Mode.
this.disposers.push(useDistractionFree.subscribe(() => this.manager.applySettings()));
// Vim's `number` / `relativenumber` change every editor's line numbers.
this.disposers.push(useLineNumberOptions.subscribe(() => this.manager.applySettings()));
this.disposers.push(
useTextEditorWrappers.subscribe(({ wrappers }) => {
this.upgradeWrappedImageTabs(wrappers);
+77 -15
Переглянути файл
@@ -40,8 +40,10 @@ import {
type GotoKind,
type Highlight,
type Location,
type OutlineItem,
type Pos,
type RequestId,
type SymbolKind,
type WebReferenceKind,
} from "@/platform/ipc";
import {
@@ -211,31 +213,91 @@ async function indexContainers(
const SYMBOL_LIMIT = 500;
/** Popup items for locations: icon + name, the container, and `path:line` (IDEA's chooser rows). */
export async function locationItems(locs: readonly DeclarationTarget[]): Promise<ListPopupItem[]> {
const INTERFACE_KINDS = new Set<SymbolKind>(["interface", "trait"]);
/** Most target files whose outline is read for the interface markers. */
const MAX_OUTLINE_FILES = 8;
/**
* Which targets are an interface / trait or a method declared in one. LSP implementation
* answers carry no symbol kind, so the target document's outline supplies it: the symbol
* itself for types, its parent for methods. Unresolvable targets (outline missing, a server
* without document symbols, a file outside the project) simply get no marker.
*/
async function interfaceFlags(locs: readonly DeclarationTarget[]): Promise<boolean[]> {
const outlines = new Map<string, OutlineItem[]>();
const paths = [...new Set(locs.map((l) => l.path))];
// Reading an outline opens the file in the language server: past a few files the chooser
// would wait for the server to analyse each one, so it opens with the kinds already known.
if (paths.length > MAX_OUTLINE_FILES) return locs.map((l) => !!l.kind && INTERFACE_KINDS.has(l.kind));
await Promise.all(
paths.map(async (path) => {
try {
outlines.set(path, await withDocument(path, (doc) => lspRequest(() => commands.docOutline(doc))));
} catch {
outlines.set(path, []);
}
}),
);
return locs.map((l) => {
if (l.kind && INTERFACE_KINDS.has(l.kind)) return true;
const line = l.range.start.line;
const col = l.range.start.col;
let found = false;
const walk = (items: readonly OutlineItem[], parent: SymbolKind | null) => {
for (const it of items) {
const s = it.selection_range.start;
const r = it.range.start;
if (s.line === line && (s.col === col || (r.line === line && col >= r.col && col <= it.range.end.col))) {
found = INTERFACE_KINDS.has(it.kind) || (parent !== null && INTERFACE_KINDS.has(parent));
return;
}
walk(it.children, it.kind);
}
};
walk(outlines.get(l.path) ?? [], null);
return found;
});
}
/**
* Popup items for locations: icon + name, the container, and `path:line` (IDEA's chooser rows).
* `markInterfaces` shows the editor's interface / trait badge in place of the file icon for a
* target that is one, so it is told apart from the implementations beside it.
*/
export async function locationItems(
locs: readonly DeclarationTarget[],
markInterfaces = false,
): Promise<ListPopupItem[]> {
const files = await readManyFileLines(locs.map((l) => l.path));
const root = useProject.getState().project?.root ?? "";
const names = locs.map((l) => targetLabel(files.get(l.path)?.[l.range.start.line] ?? "", l.range.start.col));
const indexed = await indexContainers(locs, names);
const [indexed, interfaces] = await Promise.all([
indexContainers(locs, names),
markInterfaces ? interfaceFlags(locs) : Promise.resolve([] as boolean[]),
]);
const rows = locs.map((l, i) => {
const where = chooserWhere(root, l.path, l.range.start.line + 1);
// Index symbols carry their container; server targets take the index's answer or the enclosing type.
const indexSymbol = !!(l.kind && l.name);
const label = indexSymbol ? l.name! : (l.name ?? names[i] ?? basename(l.path));
const container = indexSymbol ? l.container : (indexed.get(i) ?? enclosingType(files.get(l.path), l));
return { l, where, label, container: container || null, indexSymbol };
return { l, where, label, container: container || null, indexSymbol, isInterface: interfaces[i] ?? false };
});
// Targets that all share one name (the implementations of a method) are told apart, and
// speed-searched, by their containers, which become the rows' text.
const byContainer = rows.length > 1 && rows.every((r) => r.container && r.label === rows[0]!.label);
return rows.map(({ l, where, label, container, indexSymbol }, i) => ({
id: `${i}`,
label: byContainer ? container! : label,
target: { container: byContainer ? null : container, path: where },
...(indexSymbol ? { symbol: l.kind! } : { icon: fileIconName(basename(l.path), l.path) }),
location: { path: l.path, line: l.range.start.line },
run: () => navigateTo(l),
}));
return rows.map(({ l, where, label, container, indexSymbol, isInterface }, i) => {
// The outline is what knows an implementation answer points at an interface.
const symbol = isInterface ? "interface" : indexSymbol ? l.kind! : undefined;
return {
id: `${i}`,
label: byContainer ? container! : label,
target: { container: byContainer ? null : container, path: where },
...(symbol ? { symbol } : { icon: fileIconName(basename(l.path), l.path) }),
location: { path: l.path, line: l.range.start.line },
run: () => navigateTo(l),
};
});
}
/** "Choose Implementation of foo (3 found)". */
@@ -279,7 +341,7 @@ function streamedImplementations(view: EditorView, offset: number, onOpen: () =>
if (finished || opened || current !== request || !locs.length || superseded()) return;
opened = true;
first = dedupeLocations(locs);
showing = locationItems(first).then((items) => {
showing = locationItems(first, true).then((items) => {
// All of them arrived meanwhile: shown as usual.
if (finished || superseded()) {
opened = false;
@@ -313,7 +375,7 @@ function streamedImplementations(view: EditorView, offset: number, onOpen: () =>
async complete(locs: readonly DeclarationTarget[]) {
if (closed || superseded()) return;
const all = dedupeLocations([...first, ...locs]);
const items = await locationItems(all);
const items = await locationItems(all, true);
if (closed || superseded()) return;
updatePopup("list", {
title: chooserTitle("implementation", name, all.length),
@@ -778,7 +840,7 @@ async function gotoResolved(
return;
}
const name = nameAt(view, offset);
const items = await locationItems(locs);
const items = await locationItems(locs, kind === "implementation");
if (superseded()) return;
openPopup({
kind: "list",
+134
Переглянути файл
@@ -0,0 +1,134 @@
/** Interface markers in the implementation chooser (`locationItems(..., true)`). */
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { OutlineItem } from "@/bindings";
const { readManyFileLines, withDocument, docOutline } = vi.hoisted(() => ({
readManyFileLines: vi.fn<() => Promise<Map<string, string[] | null>>>(async () => new Map()),
withDocument: vi.fn<(path: string, fn: (doc: number) => Promise<unknown>) => Promise<unknown>>(async (_path, fn) =>
fn(1),
),
docOutline: vi.fn<(doc: number) => Promise<OutlineItem[]>>(async () => []),
}));
vi.mock("./files", async (orig) => {
const real = await orig<typeof import("./files")>();
return { ...real, readManyFileLines, withDocument };
});
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return { ...real, call: (p: Promise<unknown>) => p, commands: { ...real.commands, docOutline } };
});
vi.mock("./lsp", async (orig) => {
const real = await orig<typeof import("./lsp")>();
return { ...real, lspRequest: (run: () => Promise<unknown>) => run() };
});
const { locationItems } = await import("./navigation");
const { useProject } = await import("@/platform/project");
const PATH = "/p/svc.go";
const item = (
name: string,
kind: OutlineItem["kind"],
line: number,
col: number,
children: OutlineItem[] = [],
): OutlineItem => ({
name,
detail: null,
kind,
range: { start: { line, col }, end: { line, col: col + name.length } },
selection_range: { start: { line, col }, end: { line, col: col + name.length } },
children,
visibility: null,
});
const target = (line: number, col: number): Parameters<typeof locationItems>[0][number] => ({
path: PATH,
uri: null,
range: { start: { line, col }, end: { line, col: col + 11 } },
});
const OUTLINE: OutlineItem[] = [
item("Pet", "interface", 4, 5, [item("Speak", "method", 7, 1)]),
item("(*base).Wake", "method", 12, 18),
item("Cat", "struct", 16, 5, [item("Speak", "method", 19, 25)]),
];
const SOURCE = [
"",
"",
"",
"",
"type Pet interface {",
"",
"",
" Speak(text string) (bool, error)",
"}",
"",
"",
"",
"func (b *base) Wake() error { return nil }",
"",
"",
"",
"type Cat struct{}",
"",
"",
"func (c *Cat) Speak(text string) (bool, error) { return false, nil }",
];
beforeEach(() => {
useProject.setState({ project: { root: "/p" } as never, settings: null });
readManyFileLines.mockResolvedValue(new Map([[PATH, SOURCE]]));
withDocument.mockImplementation(async (_path, fn) => fn(1));
docOutline.mockResolvedValue(OUTLINE);
});
afterEach(() => {
useProject.setState({ project: null, settings: null });
vi.clearAllMocks();
});
describe("implementation chooser interface markers", () => {
it("replaces the file icon with the badge for an interface method", async () => {
const rows = await locationItems([target(7, 1), target(12, 18)], true);
expect(rows.map((r) => r.symbol)).toEqual(["interface", undefined]);
// One icon per row: the badge stands in for the file icon, it does not join it.
expect(rows[0]!.icon).toBeUndefined();
expect(rows[1]!.icon).toBeTruthy();
});
it("marks an interface type itself", async () => {
const rows = await locationItems([target(4, 5)], true);
expect(rows[0]!.symbol).toBe("interface");
expect(rows[0]!.icon).toBeUndefined();
});
it("does not mark a concrete method of a struct", async () => {
const rows = await locationItems([target(19, 25)], true);
expect(rows[0]!.symbol).toBeUndefined();
expect(rows[0]!.icon).toBeTruthy();
});
it("does nothing without the flag (other choosers)", async () => {
const rows = await locationItems([target(7, 1), target(12, 18)]);
expect(rows.map((r) => r.symbol)).toEqual([undefined, undefined]);
expect(rows.map((r) => !!r.icon)).toEqual([true, true]);
expect(docOutline).not.toHaveBeenCalled();
});
it("reads no outlines when the targets span many files", async () => {
const many = Array.from({ length: 9 }, (_, i) => ({ ...target(7, 1), path: `/p/f${i}.go` }));
readManyFileLines.mockResolvedValue(new Map(many.map((t) => [t.path, SOURCE])));
const rows = await locationItems(many, true);
expect(rows.every((r) => r.symbol === undefined && !!r.icon)).toBe(true);
expect(docOutline).not.toHaveBeenCalled();
expect(withDocument).not.toHaveBeenCalled();
});
it("leaves rows unmarked when the target outline is unavailable", async () => {
docOutline.mockRejectedValueOnce(new Error("no document symbols"));
const rows = await locationItems([target(7, 1)], true);
expect(rows[0]!.symbol).toBeUndefined();
expect(rows[0]!.icon).toBeTruthy();
});
});
+165 -2
Переглянути файл
@@ -15,8 +15,15 @@ vi.mock("@/platform/ipc", async (orig) => {
return { ...actual, isTauri: () => true, commands: { ...actual.commands, lspSignatureHelp } };
});
const { signatureExtension, acceptsParameter, argumentSpans, argumentStop, parameterTabKeys, triggerSignatureHelp } =
await import("./signature");
const {
signatureExtension,
acceptsParameter,
argumentSpans,
argumentStop,
parameterInfoOrLeave,
parameterTabKeys,
triggerSignatureHelp,
} = await import("./signature");
const { lspDoc } = await import("./lsp");
const views: EditorView[] = [];
@@ -60,6 +67,162 @@ describe("parameter info auto-popup", () => {
});
});
describe("parameter info replies", () => {
const named = (name: string) => ({
status: "ok" as const,
data: {
signatures: [{ label: `${name}(arg)`, documentation: null, parameters: [[2, 5]] }],
activeSignature: 0,
activeParameter: 0,
},
});
function pending() {
let resolve!: (v: ReturnType<typeof named>) => void;
let reject!: (e: unknown) => void;
const promise = new Promise<ReturnType<typeof named>>((res, rej) => ((resolve = res), (reject = rej)));
return { promise, resolve, reject };
}
function editor(doc = "f(x); g(y)", anchor = 2) {
const view = new EditorView({
state: EditorState.create({
doc,
selection: { anchor },
extensions: [
lspDoc.of({ doc: 1, path: "/a.ts", language: "typescript", uiMode: null, readOnly: false }),
signatureExtension(),
],
}),
parent: document.body,
});
views.push(view);
return view;
}
const shown = (view: EditorView) => view.dom.querySelector(".cm-lsp-signature")?.textContent ?? null;
const settle = () => new Promise((r) => setTimeout(r, 0));
it("keeps a newer reply when the older one arrives after it", async () => {
const first = pending();
lspSignatureHelp.mockReturnValueOnce(first.promise as never).mockResolvedValueOnce(named("g") as never);
const view = editor();
triggerSignatureHelp(view, true);
view.dispatch({ selection: { anchor: 8 } });
triggerSignatureHelp(view, true);
await vi.waitFor(() => expect(shown(view)).toBe("g(arg)"));
first.resolve(named("f"));
await settle();
expect(shown(view)).toBe("g(arg)");
});
it("keeps a newer reply when the older request fails after it", async () => {
const first = pending();
lspSignatureHelp.mockReturnValueOnce(first.promise as never).mockResolvedValueOnce(named("g") as never);
const view = editor();
triggerSignatureHelp(view, true);
view.dispatch({ selection: { anchor: 8 } });
triggerSignatureHelp(view, true);
await vi.waitFor(() => expect(shown(view)).toBe("g(arg)"));
first.reject(new Error("server gone"));
await settle();
expect(shown(view)).toBe("g(arg)");
});
it("still shows an older explicit reply when the newer one was dropped for an edit", async () => {
const first = pending();
const second = pending();
lspSignatureHelp.mockReturnValueOnce(first.promise as never).mockReturnValueOnce(second.promise as never);
const view = editor();
triggerSignatureHelp(view, true);
triggerSignatureHelp(view, false);
view.dispatch({ changes: { from: 3, insert: " " } });
second.resolve(named("g"));
await settle();
expect(shown(view)).toBeNull();
first.resolve(named("f"));
await vi.waitFor(() => expect(shown(view)).toBe("f(arg)"));
});
it.each([
["a signature", () => Promise.resolve(named("g"))],
["no signature", () => Promise.resolve({ status: "ok" as const, data: null })],
["an error", () => Promise.reject(new Error("server gone"))],
])("shows an older reply for the caret when the newer one answered %s for another place", async (_, newer) => {
const first = pending();
lspSignatureHelp.mockReturnValueOnce(first.promise as never).mockReturnValueOnce(newer() as never);
const view = editor();
triggerSignatureHelp(view, true);
view.dispatch({ selection: { anchor: 8 } });
triggerSignatureHelp(view, false);
view.dispatch({ selection: { anchor: 2 } });
await settle();
first.resolve(named("f"));
await vi.waitFor(() => expect(shown(view)).toBe("f(arg)"));
});
it.each([
["no signature", (p: ReturnType<typeof pending>) => p.resolve({ status: "ok", data: null } as never)],
["an error", (p: ReturnType<typeof pending>) => p.reject(new Error("server gone"))],
])("leaves a newer reply alone, without a hint, when an older one brings %s", async (_, settleOlder) => {
const first = pending();
lspSignatureHelp.mockReturnValueOnce(first.promise as never).mockResolvedValueOnce(named("g") as never);
const view = editor();
triggerSignatureHelp(view, true);
view.dispatch({ selection: { anchor: 8 } });
triggerSignatureHelp(view, true);
await vi.waitFor(() => expect(shown(view)).toBe("g(arg)"));
settleOlder(first);
await settle();
expect(shown(view)).toBe("g(arg)");
expect(view.dom.textContent).not.toContain("No parameters");
expect(view.dom.textContent).not.toContain("server gone");
});
it("lets a reply through once another source replaced the newer reply's tooltip", async () => {
const inside = pending();
const a = pending();
lspSignatureHelp
.mockReturnValueOnce(inside.promise as never)
.mockReturnValueOnce(a.promise as never)
.mockResolvedValueOnce(named("g") as never);
const view = editor();
const left = parameterInfoOrLeave(view, 2);
view.dispatch({ selection: { anchor: 8 } });
triggerSignatureHelp(view, true);
triggerSignatureHelp(view, true);
await vi.waitFor(() => expect(shown(view)).toBe("g(arg)"));
view.dispatch({ selection: { anchor: 2 } });
inside.resolve(named("f"));
await left;
await vi.waitFor(() => expect(shown(view)).toBe("f(arg)"));
view.dispatch({ selection: { anchor: 8 } });
a.resolve(named("g2"));
await vi.waitFor(() => expect(shown(view)).toBe("g2(arg)"));
});
it("shows an older reply asked at the same caret after a newer one", async () => {
const first = pending();
lspSignatureHelp.mockReturnValueOnce(first.promise as never).mockResolvedValueOnce(named("f") as never);
const view = editor();
triggerSignatureHelp(view, true);
triggerSignatureHelp(view, true);
await vi.waitFor(() => expect(shown(view)).toBe("f(arg)"));
first.resolve(named("f2"));
await vi.waitFor(() => expect(shown(view)).toBe("f2(arg)"));
});
it("orders replies per editor, so a split's reply doesn't hide another's", async () => {
const left = pending();
lspSignatureHelp.mockReturnValueOnce(left.promise as never).mockResolvedValueOnce(named("g") as never);
const a = editor();
const b = editor("f(x); g(y)", 8);
triggerSignatureHelp(a, true);
triggerSignatureHelp(b, true);
await vi.waitFor(() => expect(shown(b)).toBe("g(arg)"));
left.resolve(named("f"));
await vi.waitFor(() => expect(shown(a)).toBe("f(arg)"));
expect(shown(b)).toBe("g(arg)");
});
});
describe("acceptsParameter", () => {
it("rejects overloads with too few parameters unless the last is variadic", () => {
expect(acceptsParameter({ label: "println() : void", parameters: [] }, 0)).toBe(false);
+27 -2
Переглянути файл
@@ -5,7 +5,7 @@
* ⇥ / ⇧⇥ move to the next / previous argument.
*/
import { hasLinkedSnippetField } from "@/editor/core/cm/linkedSnippet";
import { EditorSelection, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
import { EditorSelection, Prec, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import { completionStatus, hasNextSnippetField, hasPrevSnippetField } from "@codemirror/autocomplete";
import {
EditorView,
@@ -125,22 +125,47 @@ function signatureTooltip(s: SigState): Tooltip {
};
}
/** Per view: requests sent, and the tooltip value the newest shown reply set, with the document and caret it was asked at. */
const requests = new WeakMap<
EditorView,
{ sent: number; shown?: { id: number; value: SigState; doc: Text; head: number } }
>();
async function fetchSignature(view: EditorView, explicit: boolean) {
const doc = docOf(view);
if (!doc) return;
let order = requests.get(view);
if (!order) requests.set(view, (order = { sent: 0 }));
const id = ++order.sent;
const state = view.state;
const head = state.selection.main.head;
// A late reply asked at another caret never overrides what a newer request still shows for this one.
const superseded = () => {
const shown = order.shown;
return (
!!shown &&
shown.id > id &&
(shown.doc !== state.doc || shown.head !== head) &&
shown.value === view.state.field(signatureField, false) &&
shown.doc === view.state.doc &&
shown.head === view.state.selection.main.head
);
};
try {
const help = await lspRequest(() => commands.lspSignatureHelp(doc.doc, offsetToPos(state.doc, head)));
if (view.state.doc !== state.doc && !explicit) return;
if (superseded()) return;
const current = view.state.field(signatureField, false);
if (!help || !help.signatures.length) {
if (current) view.dispatch({ effects: setSignature.of(null) });
if (explicit) showHint(view, "No parameters");
return;
}
view.dispatch({ effects: setSignature.of({ pos: Math.min(head, view.state.doc.length), help }) });
const value = { pos: Math.min(head, view.state.doc.length), help };
view.dispatch({ effects: setSignature.of(value) });
order.shown = { id, value, doc: state.doc, head };
} catch (e) {
if (superseded()) return;
if (view.state.field(signatureField, false)) view.dispatch({ effects: setSignature.of(null) });
reportLspError(view, e, explicit);
}
+4 -4
Переглянути файл
@@ -1,7 +1,7 @@
/* Editor gutter inheritance icons (implemented / overridden / implementing / overriding). */
.marker {
width: 14px;
height: 14px;
width: var(--openidea-gutter-icon-size, 14px);
height: var(--openidea-gutter-icon-size, 14px);
display: flex;
align-items: center;
justify-content: center;
@@ -11,8 +11,8 @@
/* Python stub / implementation icon (a button, so it also works from the keyboard). */
.stubMarker {
width: 14px;
height: 14px;
width: var(--openidea-gutter-icon-size, 14px);
height: var(--openidea-gutter-icon-size, 14px);
display: flex;
align-items: center;
justify-content: center;
+182
Переглянути файл
@@ -0,0 +1,182 @@
.row {
min-height: var(--h-row);
padding-block: 2px;
}
.entryTitle {
flex-shrink: 0;
color: var(--fg-strong);
font-weight: 500;
white-space: nowrap;
}
.subtitle {
flex: 1;
min-width: 0;
color: var(--fg-muted);
font-size: var(--fs-small);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.scopeSelect {
min-width: 120px;
}
.controls {
display: flex;
align-items: center;
gap: var(--space-1-5);
margin-left: auto;
flex-shrink: 0;
}
.summaryBox {
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: 10px 12px;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
}
.summaryHeader {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--space-2);
}
.summaryPills {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
}
.summaryTitle {
font-weight: 600;
color: var(--fg-strong);
}
.projectionLink {
display: inline-flex;
align-items: center;
gap: var(--space-1);
padding: 2px 8px;
border-radius: var(--radius-small);
border: 1px solid var(--border);
background: var(--bg-app);
color: var(--link);
font-size: var(--fs-tiny);
cursor: pointer;
}
.projectionLink:hover {
text-decoration: underline;
}
.marketplaceRow {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--space-2);
}
.marketplaceChips {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
}
.marketplaceChip {
display: inline-flex;
align-items: center;
gap: var(--space-1);
padding: 2px 7px;
border-radius: var(--radius-small);
background: var(--bg-app);
box-shadow: inset 0 0 0 1px var(--border);
font-size: var(--fs-tiny);
color: var(--fg-secondary);
}
.dialogBody {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: var(--space-3) var(--space-4) 0;
}
.field {
display: flex;
flex-direction: column;
gap: var(--space-1);
}
.fieldRow {
display: flex;
align-items: center;
gap: var(--space-2);
}
.fieldLabel {
font-size: var(--fs-small);
color: var(--fg-secondary);
}
.capBox {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
padding: var(--space-2) var(--space-3);
border-radius: var(--radius-control);
background: var(--bg-app);
box-shadow: inset 0 0 0 1px var(--border);
font-size: var(--fs-small);
}
.codeLine {
font-family: var(--font-mono);
font-size: var(--fs-tiny);
color: var(--fg-secondary);
word-break: break-all;
}
.candidateList {
display: flex;
flex-direction: column;
gap: var(--space-1-5);
max-height: 280px;
overflow-y: auto;
}
.candidateRow {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: var(--space-2) var(--space-3);
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
}
.candidateMain {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
min-width: 0;
flex: 1;
}
.hint {
color: var(--fg-muted);
font-size: var(--fs-small);
line-height: 1.4;
}
+315
Переглянути файл
@@ -0,0 +1,315 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type {
AgentPluginCatalog,
AgentPluginPreview,
AgentPluginSource,
AgentPluginState,
InstallAgentPluginRequest,
McpScope,
ProjectInfo,
} from "@/bindings";
import { closeSettings } from "@/features/settings/model/staging";
import * as actions from "@/platform/actions";
import { useProject } from "@/platform/project";
import { AgentPluginsPage, type PluginsBackend } from "./AgentPluginsPage";
function makePlugin(
id: string,
source: AgentPluginSource,
scope: McpScope,
enabled = true,
extraPlugin: Partial<AgentPluginState["plugin"]> = {},
extraState: Partial<AgentPluginState> = {},
): AgentPluginState {
return {
plugin: {
id: `${id}-${source}-${scope}`,
name: id,
displayName: id,
version: "1.0.0",
description: `${id} bundle`,
source,
scope,
formats: ["claude"],
rootPath: `/plugins/${source}/${scope}/${id}`,
defaultEnabled: true,
approxTokens: 480,
capabilities: {
skillCount: 2,
skillNames: ["deploy", "diag"],
mcpCount: 1,
mcpNames: ["cloud-mcp"],
ruleCount: 1,
subagentCount: 0,
commandCount: 0,
requiresConsent: false,
},
valid: true,
...extraPlugin,
},
enabled,
origin: "none",
consentRequired: false,
...extraState,
};
}
const SAMPLE_CATALOG: AgentPluginCatalog = {
projectedSkills: 58,
projectedMcpServers: 3,
projectedRules: 2,
marketplaces: [
{
id: "github/awesome-copilot",
name: "awesome-copilot",
source: "github/awesome-copilot",
scope: "user",
discovered: false,
},
],
plugins: [
makePlugin("azure", "copilotUser", "user", true, {
version: "1.2.106",
formats: ["copilot", "claude"],
capabilities: {
skillCount: 28,
skillNames: ["azure-ai"],
mcpCount: 1,
mcpNames: ["azure"],
ruleCount: 0,
subagentCount: 0,
commandCount: 0,
stdioCommands: ["azure: npx -y @azure/mcp server start"],
requiresConsent: true,
},
}),
makePlugin(
"azure",
"claudeUser",
"workspace",
false,
{
id: "azure-claude-workspace",
formats: ["claude"],
capabilities: {
skillCount: 28,
mcpCount: 1,
ruleCount: 0,
subagentCount: 0,
commandCount: 0,
hookFiles: ["hooks/hooks.json"],
stdioCommands: ["azure: npx -y @azure/mcp server start"],
capabilityHash: "abc123",
requiresConsent: true,
},
},
{ consentRequired: true, origin: "consent" },
),
],
};
function createMockBackend(initial: AgentPluginCatalog = SAMPLE_CATALOG) {
let state = structuredClone(initial);
const calls = {
setEnabled: [] as Array<{ id: string; scope: McpScope; enabled: boolean; approve: boolean }>,
install: [] as InstallAgentPluginRequest[],
};
const backend: PluginsBackend = {
list: async () => structuredClone(state),
setEnabled: async (id, scope, enabled, approveCapabilities = false) => {
calls.setEnabled.push({ id, scope, enabled, approve: approveCapabilities });
state = {
...state,
plugins: state.plugins.map((p) =>
p.plugin.id === id
? {
...p,
enabled,
consentRequired: approveCapabilities ? false : p.consentRequired,
origin: approveCapabilities ? "none" : p.origin,
}
: p,
),
};
return structuredClone(state);
},
browseMarketplace: async (source) => ({
source,
marketplaceName: "acme-mkt",
owner: "acme",
repo: "plugins",
gitRef: "main",
treeSha: "1111111111111111111111111111111111111111",
candidates: [
{
name: "k8s-ops",
displayName: "k8s-ops",
version: "2.1.0",
description: "Kubernetes cluster diagnostics",
marketplace: "acme-mkt",
sourceSpec: "acme/plugins/k8s-ops#main",
subpath: "k8s-ops",
alreadyInstalledUser: false,
alreadyInstalledWorkspace: false,
},
],
}),
preview: async (): Promise<AgentPluginPreview> => ({
sourceKind: "github",
owner: "acme",
repo: "plugins",
gitRef: "main",
treeSha: "1111111111111111111111111111111111111111",
subpath: "k8s-ops",
marketplace: "acme-mkt",
name: "k8s-ops",
displayName: "k8s-ops",
version: "2.1.0",
description: "Kubernetes cluster diagnostics",
formats: ["claude", "copilot", "codex"],
capabilities: {
skillCount: 3,
mcpCount: 1,
ruleCount: 0,
subagentCount: 0,
commandCount: 0,
stdioCommands: ["k8s: npx -y k8s-mcp"],
hookFiles: ["hooks/hooks.json"],
capabilityHash: "hash-k8s",
requiresConsent: true,
},
files: [{ path: "SKILL.md", size: 120, executable: false, symlink: false }],
scanWarnings: [{ kind: "executableScript", file: "scripts/run.sh", message: "Contains executable script" }],
targets: [
{
harness: "claude",
supported: true,
workspaceSupported: true,
installedUser: false,
installedWorkspace: false,
overwriteRequired: false,
},
{
harness: "copilot",
supported: true,
workspaceSupported: true,
installedUser: true,
installedWorkspace: false,
overwriteRequired: true,
},
{
harness: "codex",
supported: false,
reason: "Codex installs only from marketplaces it knows",
workspaceSupported: true,
installedUser: false,
installedWorkspace: false,
overwriteRequired: false,
},
{
harness: "gemini",
supported: false,
reason: "Gemini CLI reads `gemini-extension.json`",
workspaceSupported: true,
installedUser: false,
installedWorkspace: false,
overwriteRequired: false,
},
],
}),
install: async (req) => {
calls.install.push(req);
state = {
...state,
plugins: [...state.plugins, makePlugin("k8s-ops", `${req.harness}User` as AgentPluginSource, req.scope)],
};
return structuredClone(state);
},
};
return { backend, calls };
}
describe("AgentPluginsPage", () => {
afterEach(() => {
closeSettings();
useProject.setState({ project: null });
vi.restoreAllMocks();
});
it("groups by harness and scope, toggles native config, and deep-links projected children", async () => {
useProject.setState({
project: { root: "/repo", name: "repo", trusted: true, isGit: true } as ProjectInfo,
});
const execSpy = vi.spyOn(actions, "executeAction").mockResolvedValue(true);
const { backend, calls } = createMockBackend();
render(<AgentPluginsPage backend={backend} />);
expect(await screen.findByRole("region", { name: "GitHub Copilot · User" })).toBeInTheDocument();
expect(screen.getByRole("region", { name: "Claude Code · Workspace" })).toHaveTextContent(".claude/settings.json");
expect(screen.getAllByText("azure", { exact: true })).toHaveLength(2);
fireEvent.click(screen.getByRole("button", { name: "58 skills → Skills" }));
expect(execSpy).toHaveBeenCalledWith("file.settings", "agents.skills");
fireEvent.click(screen.getByRole("button", { name: "Review & Enable…" }));
const dialog = await screen.findByRole("dialog", { name: /Approve Plugin Capabilities/ });
expect(within(dialog).getByText("azure: npx -y @azure/mcp server start")).toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("button", { name: "Trust & Enable Plugin" }));
await waitFor(() =>
expect(calls.setEnabled).toContainEqual({
id: "azure-claude-workspace",
scope: "workspace",
enabled: true,
approve: true,
}),
);
});
it("targets a supported native harness and keeps capability and scan consent required", async () => {
useProject.setState({
project: { root: "/repo", name: "repo", trusted: true, isGit: true } as ProjectInfo,
});
const { backend, calls } = createMockBackend();
render(<AgentPluginsPage backend={backend} />);
fireEvent.click(await screen.findByRole("button", { name: "Install Plugin…" }));
const installDlg = await screen.findByRole("dialog", { name: "Install Agent Plugin" });
fireEvent.click(within(installDlg).getByRole("button", { name: "awesome-copilot" }));
const previewButton = await within(installDlg).findByRole("button", { name: "Preview…" });
await waitFor(() => expect(previewButton).toBeEnabled());
fireEvent.click(previewButton);
await within(installDlg).findByLabelText("Target harness");
expect(within(installDlg).queryByLabelText("Replace the existing plugin directory")).toBeNull();
const harness = within(installDlg).getByLabelText("Target harness");
fireEvent.click(harness);
const harnessList = await screen.findByRole("listbox", { name: "Target harness" });
expect(within(harnessList).getByText(/Gemini CLI.*gemini-extension\.json/)).toBeInTheDocument();
expect(within(harnessList).getByText(/Codex.*marketplaces it knows/)).toBeInTheDocument();
fireEvent.click(within(harnessList).getByText("GitHub Copilot"));
const install = within(installDlg).getByRole("button", { name: "Trust & Install Plugin" });
expect(install).toBeDisabled();
fireEvent.click(within(installDlg).getByLabelText("Approve bundled MCP server and lifecycle hook execution"));
fireEvent.click(within(installDlg).getByLabelText("Confirm static security scan warnings"));
expect(install).toBeDisabled();
fireEvent.click(within(installDlg).getByLabelText("Replace the existing plugin directory"));
fireEvent.click(install);
await waitFor(() => expect(calls.install).toHaveLength(1));
expect(calls.install[0]).toMatchObject({
sourceKind: "github",
owner: "acme",
repo: "plugins",
treeSha: "1111111111111111111111111111111111111111",
subpath: "k8s-ops",
scope: "workspace",
harness: "copilot",
approveCapabilities: true,
confirmWarnings: true,
});
});
});
File diff suppressed because it is too large. Load diff
+140 -27
Переглянути файл
@@ -1,46 +1,159 @@
/** Status bar widget: tasks waiting for the user / running; opens the most urgent one. */
import { Icon, Spinner, T } from "@/ui";
/** Status bar widget: tasks waiting for the user / running, plus active scheduler host popover. */
import { useRef, useState } from "react";
import { useTx } from "@/platform/i18n";
import { Button, Icon, Popup, Spinner, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import {
defaultAutomationsBackend,
formatShortTimestamp,
openAutomations,
refreshAutomations,
useAutomations,
useAutomationsSync,
} from "./automationsModel";
import { isInterrupted } from "./model";
import { openTask, useAgents } from "./store";
import styles from "./Agents.module.css";
import autoStyles from "./Automations.module.css";
export function AgentsStatus() {
useAutomationsSync();
const tx = useTx();
const tasks = useAgents((s) => s.tasks);
const unread = useAgents((s) => s.unread);
const host = useAutomations((s) => s.snapshot.host);
const schedulerBtnRef = useRef<HTMLButtonElement>(null);
const [popoverOpen, setPopoverOpen] = useState(false);
const list = [...tasks.values()];
const unseen = list.filter((t) => unread.has(t.id)).sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
const input = list.filter((t) => t.status === "needsInput");
const interrupted = list.filter(isInterrupted).sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
const running = list.filter((t) => t.status === "running" || t.status === "starting").length;
if (!input.length && !interrupted.length && !running && !unseen.length) return null;
const hasTasks = !!(input.length || interrupted.length || running || unseen.length);
const hasSchedules = host.activeSchedules > 0 || host.unreadRuns > 0 || host.needsInputRuns > 0;
if (!hasTasks && !hasSchedules) return null;
const target =
input[0] ?? interrupted[0] ?? unseen[0] ?? list.find((t) => t.status === "running" || t.status === "starting");
return (
<button type="button" className={styles.statusItem} onClick={() => target && openTask(target.id)}>
{input.length > 0 && (
<span className={styles.statusPart}>
<Icon name="warning" size={13} />
{input.length} <T>needs input</T>
</span>
<>
{hasTasks && (
<button type="button" className={styles.statusItem} onClick={() => target && openTask(target.id)}>
{input.length > 0 && (
<span className={styles.statusPart}>
<Icon name="warning" size={13} />
{input.length} <T>needs input</T>
</span>
)}
{interrupted.length > 0 && (
<span className={styles.statusPart}>
<Icon name="pause" size={13} className={styles.interrupted} />
{interrupted.length} <T>interrupted</T>
</span>
)}
{running > 0 && (
<span className={styles.statusPart}>
<Spinner size={10} />
{running} <T>running</T>
</span>
)}
{unseen.length > 0 && (
<span className={styles.statusPart}>
<span className={styles.unreadDot} aria-hidden="true" />
{unseen.length} <T>unread</T>
</span>
)}
</button>
)}
{interrupted.length > 0 && (
<span className={styles.statusPart}>
<Icon name="pause" size={13} className={styles.interrupted} />
{interrupted.length} <T>interrupted</T>
</span>
{hasSchedules && (
<>
<button
ref={schedulerBtnRef}
type="button"
className={styles.statusItem}
data-testid="status-scheduler-button"
aria-haspopup="dialog"
aria-expanded={popoverOpen}
onClick={() => setPopoverOpen((v) => !v)}
>
<span className={styles.statusPart}>
<Icon name="clock" size={13} />
{host.activeSchedules > 0 ? (
<>
{host.activeSchedules} <T>scheduled</T>
</>
) : (
<>
{host.unreadRuns} <T>automation unread</T>
</>
)}
</span>
</button>
<Popup
open={popoverOpen}
anchor={schedulerBtnRef}
onClose={() => setPopoverOpen(false)}
aria-label={tx("Agent Automations Scheduler")}
>
<div className={autoStyles.statusPopover} data-testid="status-scheduler-popover">
<div className={autoStyles.statusPopoverHeader}>
<span>{host.remote ? tx("Remote Daemon Scheduler") : tx("Local Host Scheduler")}</span>
<span className={autoStyles.tag}>
{host.activeSchedules === 1 ? tx("1 active") : tx`${host.activeSchedules} active`}
</span>
</div>
<div className={autoStyles.statusPopoverMeta}>
<span>
<T>Login auto-start:</T> {host.bootServiceRegistered ? tx("Registered") : tx("Idle")}
</span>
{host.nextRunMs ? (
<span>
<T>Next scheduled run:</T> {formatShortTimestamp(host.nextRunMs)}
</span>
) : null}
{host.unreadRuns > 0 ? (
<span>{host.unreadRuns === 1 ? tx("1 unread run") : tx`${host.unreadRuns} unread runs`}</span>
) : null}
</div>
<div className={autoStyles.statusPopoverActions}>
{host.activeSchedules > 0 && (
<Button
size="small"
icon="pause"
onClick={() => {
void defaultAutomationsBackend
.pauseAll(true)
.then(() => refreshAutomations())
.catch((e: unknown) => {
notifications().notify({
level: "error",
title: tx("Couldn't pause automations"),
body: String(e),
});
});
setPopoverOpen(false);
}}
>
<T>Pause All</T>
</Button>
)}
<Button
size="small"
variant="primary"
onClick={() => {
setPopoverOpen(false);
openAutomations();
}}
>
<T>Open Automations</T>
</Button>
</div>
</div>
</Popup>
</>
)}
{running > 0 && (
<span className={styles.statusPart}>
<Spinner size={10} />
{running} <T>running</T>
</span>
)}
{unseen.length > 0 && (
<span className={styles.statusPart}>
<span className={styles.unreadDot} aria-hidden="true" />
{unseen.length} <T>unread</T>
</span>
)}
</button>
</>
);
}
+30
Переглянути файл
@@ -279,6 +279,36 @@ describe("Agents docked view", () => {
{ kind: "action", action: "agents.useToolWindow", icon: "", checked: true },
{ kind: "action", action: "agents.useEditor", icon: "", checked: false },
{ kind: "separator" },
{ kind: "action", action: "agents.automations", label: "Automations…", icon: "clock" },
{
kind: "item",
id: "automated-runs-filter",
label: "Automated Runs",
submenu: [
{
kind: "action",
action: "agents.automatedRunsAttention",
label: "Active & Needs Input",
icon: "",
checked: true,
},
{
kind: "action",
action: "agents.automatedRunsAll",
label: "Show All",
icon: "",
checked: false,
},
{
kind: "action",
action: "agents.automatedRunsHidden",
label: "Hide All",
icon: "",
checked: false,
},
],
},
{ kind: "separator" },
{ kind: "action", action: "agents.newTaskGroup", label: "New Group…", icon: "plus" },
{ kind: "action", action: "agents.importSessions", icon: "download" },
]);
+53 -2
Переглянути файл
@@ -62,7 +62,15 @@ import { setFocusedTaskList } from "./taskListFocus";
import { matchTask } from "./taskSearch";
import { SessionEditor } from "./SessionEditor";
import { HomeEditor } from "./HomeEditor";
import {
automatedTaskVisible,
openAutomationDialog,
openAutomations,
useAutomations,
useAutomationsSync,
} from "./automationsModel";
import styles from "./Agents.module.css";
import autoStyles from "./Automations.module.css";
import { basename, useProject } from "@/platform/project";
import { useTx } from "@/platform/i18n";
import { executeAction } from "@/platform/actions";
@@ -71,6 +79,7 @@ export function AgentsHeaderActions() {
return (
<>
<IconButton icon="plus" action="agents.newTask" />
<IconButton icon="clock" action="agents.automations" />
<IconButton icon="settings" action="agents.mcpServers" />
</>
);
@@ -160,6 +169,7 @@ function TaskStatusIcon({ task }: { task: AgentTask }) {
}
export function AgentsView() {
useAutomationsSync();
const project = useProject((s) => s.project);
const tx = useTx();
const loaded = useAgents((s) => s.loaded);
@@ -169,6 +179,9 @@ export function AgentsView() {
const providers = useAgents((s) => s.providers);
const docked = useAgents((s) => s.docked);
const homeOpen = useAgents((s) => s.homeOpen);
const automationHost = useAutomations((s) => s.snapshot.host);
const automationCount = useAutomations((s) => s.snapshot.automations.length);
const automatedRunFilter = useAutomations((s) => s.automatedRunFilter);
const inline = docked !== null || homeOpen;
const historyRef = useRef<HTMLButtonElement>(null);
const [historyOpen, setHistoryOpen] = useState(false);
@@ -218,7 +231,9 @@ export function AgentsView() {
return found;
}, [tasks, query]);
const roots = useMemo<Node[]>(() => {
const all = [...tasks.values()].filter((t) => !matches || matches.has(t.id));
const all = [...tasks.values()].filter((t) =>
matches ? matches.has(t.id) : automatedTaskVisible(t, unread, automatedRunFilter),
);
const pinned = pinnedMembers(all, organize);
return [
...(pinned.length ? [{ kind: "pinned", tasks: pinned } as Node] : []),
@@ -228,7 +243,7 @@ export function AgentsView() {
}),
...statusGroups(all, organize).map((group): Node => ({ kind: "group", group })),
];
}, [tasks, organize, matches]);
}, [tasks, organize, matches, unread, automatedRunFilter]);
const expanded = useMemo(
() => new Set(roots.map(nodeKey).filter((k) => matches || !collapsed.has(k))),
[roots, collapsed, matches],
@@ -520,6 +535,42 @@ export function AgentsView() {
setFocusedTaskList(null);
}}
>
<div className={autoStyles.hubBar} data-testid="agents-automations-hub">
<button
type="button"
className={autoStyles.hubBtn}
onClick={() => {
setHistoryOpen(false);
openAutomations();
}}
>
<Icon name="clock" size={14} />
<span>
<T>Automations</T>
</span>
<span className={autoStyles.hubMeta}>
{automationHost.activeSchedules > 0 ? (
<span>
{automationHost.activeSchedules === 1 ? tx("1 active") : tx`${automationHost.activeSchedules} active`}
</span>
) : automationCount > 0 ? (
<span>{automationCount}</span>
) : null}
{automationHost.unreadRuns > 0 && (
<span className={clsx(autoStyles.tag, autoStyles.tagUnread)}>{automationHost.unreadRuns}</span>
)}
</span>
</button>
<IconButton
icon="plus"
size="small"
title="New Automation"
onClick={() => {
setHistoryOpen(false);
openAutomationDialog();
}}
/>
</div>
{tasks.size > 0 && (
<SearchField
className={styles.taskSearch}
+699
Переглянути файл
@@ -0,0 +1,699 @@
/**
* Modal dialog for creating or editing a host-owned Agent Automation.
*/
import clsx from "clsx";
import { useEffect, useMemo, useState } from "react";
import type {
AgentConfigChoice,
AgentMemoryOverrides,
AgentSkillMode,
AutomationContinuity,
AutomationMisfirePolicy,
AutomationPermissionMode,
AutomationTrigger,
Branch,
Isolation,
} from "@/bindings";
import { useTx } from "@/platform/i18n";
import { call, commands, isTauri } from "@/platform/ipc";
import { basename, useProject } from "@/platform/project";
import { Checkbox, Dialog, Icon, Input, Select, T, type SelectOption } from "@/ui";
import { ConfigPickers } from "./ConfigPickers";
import { McpPicker } from "./McpPicker";
import { MemoryPicker } from "./MemoryPicker";
import { SkillsPicker } from "./SkillsPicker";
import {
closeAutomationDialog,
defaultAutomationsBackend,
formatShortTimestamp,
refreshAutomations,
useAutomations,
type AutomationsBackend,
} from "./automationsModel";
import { useAgentSettings } from "./agentSettings";
import { providerIcon } from "./model";
import { providerOptions as buildProviderOptions } from "./providerOptions";
import { useAgents } from "./store";
import styles from "./Automations.module.css";
type TriggerKind = AutomationTrigger["kind"];
const SCHEDULE_KIND_OPTIONS: ReadonlyArray<SelectOption<TriggerKind>> = [
{ value: "weekdays", label: "Weekdays" },
{ value: "daily", label: "Daily" },
{ value: "weekly", label: "Weekly" },
{ value: "hourly", label: "Hourly" },
{ value: "cron", label: "Cron expression" },
{ value: "oneShot", label: "One-shot" },
{ value: "manual", label: "Manual only" },
];
const PERMISSION_OPTIONS: ReadonlyArray<SelectOption<AutomationPermissionMode>> = [
{ value: "assisted", label: "Accept edits (edit workspace files without asking; ask before commands)" },
{ value: "allowAll", label: "Allow all (capped by your interactive approval setting)" },
{ value: "default", label: "Ask for approval (ask before edits and commands)" },
];
const CONTINUITY_OPTIONS: ReadonlyArray<SelectOption<AutomationContinuity>> = [
{ value: "newTask", label: "Fresh session on each run" },
{ value: "sameTask", label: "Reuse rolling session" },
];
const MISFIRE_OPTIONS: ReadonlyArray<SelectOption<string>> = [
{ value: "default", label: "Use global setting" },
{ value: "runOnce", label: "Run once on wake" },
{ value: "skip", label: "Skip missed runs" },
];
const WEEKDAYS = [
{ day: 1, label: "Mon" },
{ day: 2, label: "Tue" },
{ day: 3, label: "Wed" },
{ day: 4, label: "Thu" },
{ day: 5, label: "Fri" },
{ day: 6, label: "Sat" },
{ day: 0, label: "Sun" },
] as const;
const EMPTY_BRANCHES: Branch[] = [];
function pad2(n: number): string {
return String(n).padStart(2, "0");
}
function toDatetimeLocalValue(ms: number): string {
const d = new Date(ms);
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}T${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
}
export function AutomationDialog({ backend = defaultAutomationsBackend }: { backend?: AutomationsBackend }) {
const dialog = useAutomations((s) => s.dialog);
if (!dialog.open) return null;
const formKey = `${dialog.editing?.id ?? "new"}:${dialog.editing?.updatedMs ?? 0}:${dialog.prefillName}:${dialog.prefillPrompt}:${dialog.prefillTask?.id ?? ""}`;
return <AutomationDialogBody key={formKey} backend={backend} />;
}
function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) {
const tx = useTx();
const agentSettings = useAgentSettings();
const dialog = useAutomations((s) => s.dialog);
const project = useProject((s) => s.project);
const providers = useAgents((s) => s.providers);
const draftProvider = useAgents((s) => s.draft.provider);
const editing = dialog.editing;
const preTask = dialog.prefillTask;
const defaultRoot = project?.root ?? "";
const fallbackProvider = providers[0]?.id ?? draftProvider ?? "claude";
const [name, setName] = useState(() => editing?.name ?? (dialog.prefillName || ""));
const [enabled, setEnabled] = useState(() => editing?.enabled ?? true);
const [promptText, setPromptText] = useState(() => editing?.prompt.text ?? (dialog.prefillPrompt || ""));
const [workspaceMode, setWorkspaceMode] = useState<"project" | "chatOnly">(() => {
if (editing) return editing.workspace.kind === "chatOnly" ? "chatOnly" : "project";
return defaultRoot ? "project" : "chatOnly";
});
const [projectRoot, setProjectRoot] = useState(() => {
if (editing && editing.workspace.kind === "project") return editing.workspace.root || defaultRoot;
return preTask?.projectRoot ?? defaultRoot;
});
const [isolation, setIsolation] = useState<Isolation>(() => {
if (editing && editing.workspace.kind === "project") return editing.workspace.isolation;
return preTask?.isolation ?? "worktree";
});
const [baseBranch, setBaseBranch] = useState<string>(() => {
if (editing && editing.workspace.kind === "project") return editing.workspace.base ?? "";
return preTask?.base ?? "";
});
const [autoCleanWorktree, setAutoCleanWorktree] = useState(() =>
editing && editing.workspace.kind === "project" ? editing.workspace.autoCleanWorktree : true,
);
const [continuity, setContinuity] = useState<AutomationContinuity>(() => editing?.continuity ?? "newTask");
const [providerId, setProviderId] = useState(() => editing?.provider || preTask?.provider || fallbackProvider);
const [configMap, setConfigMap] = useState<Record<string, string>>(() => {
if (editing) return Object.fromEntries(editing.config.map((c) => [c.id, c.value]));
if (preTask) return Object.fromEntries(preTask.config.filter((c) => c.current).map((c) => [c.id, c.current!]));
return {};
});
const [permissions, setPermissions] = useState<AutomationPermissionMode>(() => editing?.permissions ?? "assisted");
const [mcpOverrides, setMcpOverrides] = useState<Record<string, boolean>>(() => ({
...(editing?.mcpOverrides ?? preTask?.mcpOverrides ?? {}),
}));
const [skillOverrides, setSkillOverrides] = useState<Record<string, AgentSkillMode>>(() => ({
...(editing?.skillOverrides ?? preTask?.skillOverrides ?? {}),
}));
const [memoryOverrides, setMemoryOverrides] = useState<AgentMemoryOverrides | null>(
() => editing?.memoryOverrides ?? preTask?.memoryOverrides ?? null,
);
const [triggerKind, setTriggerKind] = useState<TriggerKind>(() => editing?.trigger.kind ?? "weekdays");
const [timeStr, setTimeStr] = useState(() => {
const t = editing?.trigger;
if (t && (t.kind === "daily" || t.kind === "weekdays" || t.kind === "weekly")) {
return `${pad2(t.hour)}:${pad2(t.minute)}`;
}
return "09:00";
});
const [hourlyMinute, setHourlyMinute] = useState(() =>
editing?.trigger.kind === "hourly" ? String(editing.trigger.minute) : "0",
);
const [weeklyDays, setWeeklyDays] = useState<number[]>(() =>
editing?.trigger.kind === "weekly" && editing.trigger.days.length ? [...editing.trigger.days] : [1, 3, 5],
);
const [cronExpr, setCronExpr] = useState(() =>
editing?.trigger.kind === "cron" ? editing.trigger.expression : "0 9 * * MON-FRI",
);
const [timeZone, setTimeZone] = useState(() => {
const t = editing?.trigger;
if (t && "timeZone" in t && t.timeZone) return t.timeZone;
return "local";
});
const [oneShotValue, setOneShotValue] = useState(() =>
editing?.trigger.kind === "oneShot" && editing.trigger.runAtMs
? toDatetimeLocalValue(editing.trigger.runAtMs)
: toDatetimeLocalValue(Date.now() + 3_600_000),
);
const [misfirePolicy, setMisfirePolicy] = useState<string>(() => editing?.misfirePolicy ?? "default");
const [maxRunsStr, setMaxRunsStr] = useState(() => (editing?.maxRuns != null ? String(editing.maxRuns) : ""));
const [disableAfterStr, setDisableAfterStr] = useState(() =>
editing?.disableAfterMs ? toDatetimeLocalValue(editing.disableAfterMs).slice(0, 10) : "",
);
const [fetchedBranches, setFetchedBranches] = useState<{ root: string; list: Branch[] }>({ root: "", list: [] });
const [previewState, setPreviewState] = useState<{ runs: number[]; error: string | null }>({
runs: [],
error: null,
});
const [saveError, setSaveError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
useEffect(() => {
if (workspaceMode !== "project" || !projectRoot || !isTauri()) return;
let active = true;
void call(commands.vcsBranches(project?.workspace ? projectRoot : null))
.then((list) => {
if (active) setFetchedBranches({ root: projectRoot, list: list.filter((b) => !b.remote) });
})
.catch(() => {
if (active) setFetchedBranches({ root: projectRoot, list: [] });
});
return () => {
active = false;
};
}, [workspaceMode, projectRoot, project?.workspace]);
const currentTrigger = useMemo<AutomationTrigger>(() => {
const [hRaw, mRaw] = timeStr.split(":");
const hour = Math.max(0, Math.min(23, Number(hRaw) || 0));
const minute = Math.max(0, Math.min(59, Number(mRaw) || 0));
const tz = timeZone.trim() || "local";
switch (triggerKind) {
case "manual":
return { kind: "manual" };
case "hourly":
return { kind: "hourly", minute: Math.max(0, Math.min(59, Number(hourlyMinute) || 0)), timeZone: tz };
case "daily":
return { kind: "daily", hour, minute, timeZone: tz };
case "weekdays":
return { kind: "weekdays", hour, minute, timeZone: tz };
case "weekly":
return { kind: "weekly", days: weeklyDays, hour, minute, timeZone: tz };
case "cron":
return { kind: "cron", expression: cronExpr.trim(), timeZone: tz };
case "oneShot": {
const parsed = Date.parse(oneShotValue);
return { kind: "oneShot", runAtMs: Number.isFinite(parsed) ? parsed : null };
}
}
}, [triggerKind, timeStr, hourlyMinute, weeklyDays, cronExpr, timeZone, oneShotValue]);
useEffect(() => {
if (currentTrigger.kind === "manual") return;
let live = true;
void backend
.previewSchedule(currentTrigger, 3)
.then((runs) => {
if (live) setPreviewState({ runs, error: null });
})
.catch((e: unknown) => {
if (live) setPreviewState({ runs: [], error: e instanceof Error ? e.message : String(e) });
});
return () => {
live = false;
};
}, [currentTrigger, backend]);
const branches =
workspaceMode === "project" && fetchedBranches.root === projectRoot ? fetchedBranches.list : EMPTY_BRANCHES;
const previewRuns = currentTrigger.kind === "manual" ? [] : previewState.runs;
const previewError = currentTrigger.kind === "manual" ? null : previewState.error;
const selectedProvider = providers.find((p) => p.id === providerId) ?? providers[0];
const providerConfig = useMemo(
() =>
(selectedProvider?.config ?? []).map((opt) => ({
...opt,
current: configMap[opt.id] ?? opt.current,
})),
[selectedProvider, configMap],
);
const providerSelectOptions = useMemo<SelectOption[]>(() => {
const built = buildProviderOptions(providers, tx, providerIcon).filter((o) => o.value !== "__add__");
if (built.length) return built;
return [
{ value: "claude", label: "Claude Code" },
{ value: "codex", label: "Codex" },
{ value: "copilot", label: "GitHub Copilot" },
{ value: "gemini", label: "Gemini CLI" },
];
}, [providers, tx]);
const workspaceProjects = project?.workspace?.projects ?? (project?.root ? [project.root] : []);
const branchOptions = useMemo<SelectOption[]>(
() => [{ value: "", label: tx("Current HEAD") }, ...branches.map((b) => ({ value: b.name, label: b.name }))],
[branches, tx],
);
const toggleWeekday = (day: number) => {
setWeeklyDays((cur) =>
cur.includes(day) ? (cur.length > 1 ? cur.filter((d) => d !== day) : cur) : [...cur, day].sort(),
);
};
const handleSave = async () => {
if (!name.trim()) {
setSaveError(tx("Enter a name for the automation."));
return;
}
if (!promptText.trim()) {
setSaveError(tx("Enter instructions for the agent."));
return;
}
if (previewError) {
setSaveError(previewError);
return;
}
setSaving(true);
setSaveError(null);
try {
const choices: AgentConfigChoice[] = Object.entries(configMap)
.filter(([, val]) => !!val)
.map(([id, value]) => ({ id, value }));
const maxRunsNum = maxRunsStr.trim() ? Number(maxRunsStr.trim()) : null;
const disableAfterMs = disableAfterStr.trim() ? Date.parse(`${disableAfterStr.trim()}T23:59:59`) : null;
await backend.save({
id: editing?.id ?? null,
name: name.trim(),
enabled,
prompt: { text: promptText.trim(), files: [], images: [] },
workspace:
workspaceMode === "chatOnly" || !projectRoot
? { kind: "chatOnly" }
: {
kind: "project",
root: projectRoot,
isolation,
base: isolation === "worktree" && baseBranch ? baseBranch : null,
autoCleanWorktree: isolation === "worktree" && continuity === "newTask" ? autoCleanWorktree : false,
},
continuity,
provider: providerId,
config: choices,
permissions,
mcpOverrides,
skillOverrides,
memoryOverrides,
trigger: currentTrigger,
misfirePolicy: misfirePolicy === "default" ? null : (misfirePolicy as AutomationMisfirePolicy),
maxRuns: maxRunsNum && maxRunsNum > 0 ? Math.round(maxRunsNum) : null,
disableAfterMs: disableAfterMs && Number.isFinite(disableAfterMs) ? disableAfterMs : null,
});
await refreshAutomations(backend);
closeAutomationDialog();
} catch (e: unknown) {
setSaveError(e instanceof Error ? e.message : String(e));
} finally {
setSaving(false);
}
};
return (
<Dialog
open={dialog.open}
onClose={closeAutomationDialog}
title={editing ? tx("Edit Automation") : tx("New Automation")}
width={620}
maxHeight={760}
resizable="both"
footerStart={<Checkbox checked={enabled} onChange={setEnabled} label="Active schedule" />}
buttons={[
{ label: "Cancel", role: "cancel" },
{
label: editing ? "Save Changes" : "Create Automation",
role: "default",
disabled: saving || !!previewError,
onClick: () => void handleSave(),
},
]}
>
<div className={styles.dialogForm}>
{saveError && (
<div className={styles.errorBox} role="alert">
<Icon name="error" size={14} />
<span>{saveError}</span>
</div>
)}
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-name-input">
<T>Name</T>
</label>
<Input
id="automation-name-input"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Morning PR & CI Triage"
/>
</div>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Agent</T>
</span>
<Select
aria-label={tx("Agent")}
value={providerId}
options={providerSelectOptions}
onChange={setProviderId}
/>
</div>
</div>
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-prompt-input">
<T>Prompt Instructions</T>
</label>
<textarea
id="automation-prompt-input"
className={styles.promptTextarea}
value={promptText}
onChange={(e) => setPromptText(e.target.value)}
placeholder={tx("Describe what the agent should inspect, verify, or report on each run…")}
/>
<div className={styles.pickerBar}>
<ConfigPickers
config={providerConfig}
onChange={(id, val) => setConfigMap((prev) => ({ ...prev, [id]: val }))}
/>
<McpPicker provider={providerId} overrides={mcpOverrides} onChange={setMcpOverrides} />
<SkillsPicker provider={providerId} overrides={skillOverrides} onChange={setSkillOverrides} />
<MemoryPicker provider={providerId} overrides={memoryOverrides} onChange={setMemoryOverrides} />
</div>
</div>
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Workspace Target</T>
</span>
<Select
aria-label={tx("Workspace Target")}
value={workspaceMode}
options={[
...(projectRoot ? [{ value: "project", label: tx("Project workspace") }] : []),
{ value: "chatOnly", label: tx("No workspace (chat only)") },
]}
onChange={(v) => setWorkspaceMode(v as "project" | "chatOnly")}
/>
</div>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Session Continuity</T>
</span>
<Select
aria-label={tx("Session Continuity")}
value={continuity}
options={CONTINUITY_OPTIONS}
onChange={(v) => setContinuity(v)}
/>
</div>
</div>
{workspaceMode === "project" && projectRoot && (
<div className={styles.fieldRow}>
{workspaceProjects.length > 1 ? (
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Repository</T>
</span>
<Select
aria-label={tx("Repository")}
value={projectRoot}
options={workspaceProjects.map((p) => ({ value: p, label: basename(p) }))}
onChange={setProjectRoot}
/>
</div>
) : null}
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Checkout Isolation</T>
</span>
<Select
aria-label={tx("Checkout Isolation")}
value={isolation}
options={[
{ value: "worktree", label: tx("Isolated Git worktree (Recommended)") },
{ value: "local", label: tx("Local checkout") },
]}
onChange={(v) => setIsolation(v as Isolation)}
/>
</div>
{isolation === "worktree" && (
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Base Branch</T>
</span>
<Select
aria-label={tx("Base Branch")}
value={baseBranch}
options={branchOptions}
onChange={setBaseBranch}
/>
</div>
)}
</div>
)}
{workspaceMode === "project" && isolation === "worktree" && continuity === "newTask" && (
<Checkbox
checked={autoCleanWorktree}
onChange={setAutoCleanWorktree}
label="Auto-delete temporary worktree when the run makes zero file changes"
/>
)}
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Schedule</T>
</span>
<Select
aria-label={tx("Schedule")}
value={triggerKind}
options={SCHEDULE_KIND_OPTIONS}
onChange={(v) => setTriggerKind(v)}
/>
</div>
{(triggerKind === "daily" || triggerKind === "weekdays" || triggerKind === "weekly") && (
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-time-input">
<T>Run Time</T>
</label>
<Input
id="automation-time-input"
type="time"
value={timeStr}
onChange={(e) => setTimeStr(e.target.value)}
/>
</div>
)}
{triggerKind === "hourly" && (
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-minute-input">
<T>Minute Past Hour (0–59)</T>
</label>
<Input
id="automation-minute-input"
type="number"
min={0}
max={59}
value={hourlyMinute}
onChange={(e) => setHourlyMinute(e.target.value)}
/>
</div>
)}
{triggerKind === "oneShot" && (
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-oneshot-input">
<T>Run Once At</T>
</label>
<Input
id="automation-oneshot-input"
type="datetime-local"
value={oneShotValue}
onChange={(e) => setOneShotValue(e.target.value)}
/>
</div>
)}
</div>
{triggerKind === "weekly" && (
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Days of Week</T>
</span>
<div className={styles.weekdayRow}>
{WEEKDAYS.map((w) => (
<button
key={w.day}
type="button"
className={clsx(styles.dayBtn, weeklyDays.includes(w.day) && styles.dayBtnActive)}
aria-pressed={weeklyDays.includes(w.day)}
onClick={() => toggleWeekday(w.day)}
>
{tx(w.label)}
</button>
))}
</div>
</div>
)}
{triggerKind === "cron" && (
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-cron-input">
<T>Cron Expression (5-field)</T>
</label>
<Input
id="automation-cron-input"
value={cronExpr}
onChange={(e) => setCronExpr(e.target.value)}
placeholder="0 9,15 * * MON-FRI"
/>
</div>
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-tz-input">
<T>Time Zone</T>
</label>
<Input
id="automation-tz-input"
value={timeZone}
onChange={(e) => setTimeZone(e.target.value)}
placeholder="America/Los_Angeles"
/>
</div>
</div>
)}
{triggerKind !== "manual" && (
<div className={styles.previewBox} data-testid="automation-schedule-preview">
{previewError ? (
<span style={{ color: "var(--danger)" }}>{previewError}</span>
) : previewRuns.length > 0 ? (
<>
<strong>
<T>Upcoming runs:</T>
</strong>
<span>{previewRuns.map((ms) => formatShortTimestamp(ms)).join(" · ")}</span>
</>
) : (
<span>
<T>No future runs match this schedule.</T>
</span>
)}
</div>
)}
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Unattended Permissions</T>
</span>
<Select
aria-label={tx("Unattended Permissions")}
value={permissions}
options={PERMISSION_OPTIONS}
onChange={(v) => setPermissions(v)}
/>
</div>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Missed Schedule Policy</T>
</span>
<Select
aria-label={tx("Missed Schedule Policy")}
value={misfirePolicy}
options={MISFIRE_OPTIONS}
onChange={setMisfirePolicy}
/>
</div>
</div>
{agentSettings.newTaskApprovals === "ask" && permissions !== "default" && (
<div className={styles.fieldHint}>
<T>
Your interactive New Tasks setting is Asking for approval, so scheduled turns are capped to ask before
edits and commands.
</T>
</div>
)}
{permissions === "allowAll" && workspaceMode === "project" && isolation === "local" && (
<div className={styles.fieldHint} style={{ color: "var(--warning)" }}>
<T>
Warning: Autonomous mode on a local checkout can modify your working files directly. Prefer an isolated
Git worktree.
</T>
</div>
)}
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-max-runs-input">
<T>Stop After Runs (optional)</T>
</label>
<Input
id="automation-max-runs-input"
type="number"
min={1}
value={maxRunsStr}
onChange={(e) => setMaxRunsStr(e.target.value)}
placeholder="50"
/>
</div>
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-disable-after-input">
<T>Disable After Date (optional)</T>
</label>
<Input
id="automation-disable-after-input"
type="date"
value={disableAfterStr}
onChange={(e) => setDisableAfterStr(e.target.value)}
/>
</div>
</div>
</div>
</Dialog>
);
}
Loaded 100 of 199 files, more files were not shown because too many files have changed in this diff. Show more