Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ Rust workspace, key crates in root dir:
- n00n-lua: Lua plugin system (API mirrored from neovim for plugin compatibility), built-in plugins in ./plugins dir
- n00n-acp: ACP ndjson stdio server

Built-in lua plugins in ./plugins: index (return a compact skeleton of a source file using tree-sitter), bash, glob, question, skill, memory, webfetch, websearch, todo_write, read, write, edit, task, workflow (Lua script orchestration of subagents), code_execution (python sandbox), batch, almas.
Built-in lua plugins in ./plugins: index (return a compact skeleton of a source file using tree-sitter), bash, glob, question, skill, memory, webfetch, websearch, todo_write, read, write, edit, task, workflow (Lua script orchestration of subagents), code_execution (python sandbox), batch, team.

## Docs

Expand Down
3 changes: 2 additions & 1 deletion n00n-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ pub const MIN_LOW_SPEED_TIMEOUT_SECS: u64 = 1;
pub const MIN_STREAM_TIMEOUT_SECS: u64 = 10;

pub const DEFAULT_BUILTINS: &[&str] = &[
"almas",
"agent_control",
"bash",
"batch",
"code_execution",
Expand All @@ -67,6 +67,7 @@ pub const DEFAULT_BUILTINS: &[&str] = &[
"sessions",
"skill",
"task",
"team",
"todo_write",
"view_image",
"webfetch",
Expand Down
10 changes: 9 additions & 1 deletion n00n-docgen/src/gen_tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,15 @@ const SECTIONS: &[(&str, &[&str])] = &[
),
(
"Agent & Knowledge",
&["almas", "task", "workflow", "todo_write", "memory", "skill"],
&[
"agent_control",
"team",
"task",
"workflow",
"todo_write",
"memory",
"skill",
],
),
("Web", &["webfetch", "websearch"]),
];
Expand Down
2 changes: 1 addition & 1 deletion n00n-lua/src/api/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ async fn resolve_model(

/// Estimate the dollar cost of a completion from its model spec and token
/// counts. Uses the provider's published pricing (input/output/cache write/
/// read), so orchestrators like ALMAS can report cost without bundling a
/// read), so orchestrators like Team can report cost without bundling a
/// price table.
///
/// @param spec string Model spec, e.g. `"anthropic/claude-haiku-4-5"`.
Expand Down
37 changes: 36 additions & 1 deletion n00n-lua/src/api/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,19 @@ async fn prompt(
roundtrip(lua, tx, SessionRequest::Prompt { id, text }).await
}

/// Cancels the current turn in a live session without deleting the session.
///
/// @param id string Live session id.
/// @return (boolean|nil, string|nil) true on success, or nil and an error.
#[lua_fn]
async fn cancel(
lua: Lua,
#[ctx] tx: Option<flume::Sender<UiAction>>,
id: String,
) -> LuaResult<Pair> {
roundtrip(lua, tx, SessionRequest::Cancel { id }).await
}

/// Renames a session, live or stored.
///
/// @param opts table Required fields: id (string) session to rename;
Expand Down Expand Up @@ -170,7 +183,7 @@ lua_table! {
/// the pair `(value, err)`. Without an interactive UI attached, every
/// call returns `nil, "no interactive UI attached"`.
"n00n.session" => pub(crate) fn create_session_table(tx: Option<flume::Sender<UiAction>>),
DOCS [list(tx), live(tx), current(tx), focus(tx), delete(tx), new(tx), prompt(tx), set_title(tx)]
DOCS [list(tx), live(tx), current(tx), focus(tx), delete(tx), new(tx), prompt(tx), cancel(tx), set_title(tx)]
}

#[cfg(test)]
Expand Down Expand Up @@ -215,6 +228,28 @@ mod tests {
assert_eq!(val.get::<String>("focused").unwrap(), "abc");
}

#[test]
fn cancel_forwards_session_id() {
let (tx, rx) = flume::unbounded::<UiAction>();
let lua = lua_with_session(Some(tx));
let checker = std::thread::spawn(move || {
let Ok(UiAction::Session {
req: SessionRequest::Cancel { id },
reply_tx,
}) = rx.recv()
else {
panic!("expected cancel request");
};
assert_eq!(id, "abc");
reply_tx.send(Ok(json!(true))).unwrap();
});
let (val, err): (bool, Option<String>) =
smol::block_on(lua.load("return session.cancel('abc')").eval_async()).unwrap();
checker.join().unwrap();
assert_eq!(err, None);
assert!(val);
}

#[test_case("return session.prompt('hi', { session = 'abc' })", Some("abc") ; "explicit_session_id")]
#[test_case("return session.prompt('hi')", None ; "defaults_to_focused")]
fn prompt_forwards_text_and_session_id(code: &str, expected_id: Option<&str>) {
Expand Down
1 change: 1 addition & 0 deletions n00n-lua/src/api/util/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,7 @@ pub enum SessionRequest {
Current,
New { prompt: Option<String>, focus: bool },
Prompt { id: Option<String>, text: String },
Cancel { id: String },
Focus { id: String },
Delete { id: String },
SetTitle { id: String, title: String },
Expand Down
17 changes: 15 additions & 2 deletions n00n-lua/src/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ struct BundledPlugin {
/// `lib` is not a default builtin; it exists so plugins can
/// `require()` shared modules across boundaries.
static BUNDLED_PLUGINS: &[BundledPlugin] = &[
BundledPlugin {
name: "agent_control",
dir: include_dir!("$CARGO_MANIFEST_DIR/../plugins/agent_control"),
},
BundledPlugin {
name: "sessions",
dir: include_dir!("$CARGO_MANIFEST_DIR/../plugins/sessions"),
Expand Down Expand Up @@ -96,8 +100,8 @@ static BUNDLED_PLUGINS: &[BundledPlugin] = &[
dir: include_dir!("$CARGO_MANIFEST_DIR/../plugins/workflow"),
},
BundledPlugin {
name: "almas",
dir: include_dir!("$CARGO_MANIFEST_DIR/../plugins/almas"),
name: "team",
dir: include_dir!("$CARGO_MANIFEST_DIR/../plugins/team"),
},
BundledPlugin {
name: "code_execution",
Expand Down Expand Up @@ -660,6 +664,15 @@ mod tests {
assert!(contents(&slots, PromptId::System, Slot::ToolUsage).is_empty());
}

#[test]
fn task_and_team_builtins_coexist() {
let reg = Arc::new(ToolRegistry::new());
let _host = PluginHost::with_all_builtins(Arc::clone(&reg)).unwrap();
assert!(reg.has("agent_control"));
assert!(reg.has("task"));
assert!(reg.has("team"));
}

#[test]
fn pipelined_load_registers_every_builtin() {
let reg = Arc::new(ToolRegistry::new());
Expand Down
14 changes: 7 additions & 7 deletions n00n-lua/tests/plugin_host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3432,17 +3432,17 @@ fn bundled_todo_ctrl_t_keybind_dispatches() {
}

#[test]
fn almas_launcher_collects_goal_and_submits_configured_prompt() {
fn team_launcher_collects_goal_and_submits_configured_prompt() {
let (_reg, host) = builtins_host();
let rx = host.ui_action_rx().unwrap();
let handle = host.event_handle().unwrap();
handle.run_command(Arc::from("almas"), Arc::from("/almas"), String::new());
handle.run_command(Arc::from("team"), Arc::from("/team"), String::new());

let action = rx
.recv_timeout(Duration::from_secs(5))
.expect("ALMAS launcher did not open");
.expect("Team launcher did not open");
let n00n_lua::UiAction::OpenWin { event_tx, .. } = action else {
panic!("expected ALMAS launcher window");
panic!("expected Team launcher window");
};
event_tx
.send(n00n_lua::WinEvent::Paste {
Expand All @@ -3457,9 +3457,9 @@ fn almas_launcher_collects_goal_and_submits_configured_prompt() {

let action = rx
.recv_timeout(Duration::from_secs(5))
.expect("ALMAS launcher did not submit a session prompt");
.expect("Team launcher did not submit a session prompt");
let n00n_lua::UiAction::Session { req, reply_tx } = action else {
panic!("expected ALMAS session prompt");
panic!("expected Team session prompt");
};
let n00n_lua::SessionRequest::Prompt { id, text } = req else {
panic!("expected a prompt request");
Expand All @@ -3474,7 +3474,7 @@ fn almas_launcher_collects_goal_and_submits_configured_prompt() {
"submitted prompt: {text}"
);
assert!(
text.contains("Use the almas tool now"),
text.contains("Use the team tool now"),
"submitted prompt: {text}"
);
assert!(text.contains("thinking: max"), "submitted prompt: {text}");
Expand Down
2 changes: 1 addition & 1 deletion n00n-lua/tests/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use n00n_agent::tools::ToolRegistry;
use n00n_lua::PluginHost;
use test_case::test_case;

#[test_case("almas", include_str!("../../plugins/almas/tests/spec.lua") ; "almas_plugin_spec")]
#[test_case("team", include_str!("../../plugins/team/tests/spec.lua") ; "team_plugin_spec")]
#[test_case("edit", include_str!("../../plugins/edit/tests/spec.lua") ; "edit_plugin_spec")]
#[test_case("index", include_str!("../../plugins/index/tests/spec.lua") ; "index_plugin_spec")]
#[test_case("lib", include_str!("../../plugins/lib/tests/spec.lua") ; "lib_spec")]
Expand Down
30 changes: 25 additions & 5 deletions n00n-lua/tests/task_policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ end
behaviors.happy = function(sess, msg)
local h = sess.opts.local_tools.structured_output.handler
recorder.first_ack, recorder.first_err = h({ answer = "42" })
return { text = "raw text ignored" }
return { text = "" }
end

behaviors.invalid_then_valid = function(sess, msg)
Expand Down Expand Up @@ -403,11 +403,8 @@ fn raising_prompt_does_not_leak_semaphore_permit() {
assert_eq!(out, PLAIN_TEXT);
}

/// A task handler that uses `n00n.async.run` with an `on_finish` callback must
/// be able to finish after `DISPATCH_POLL_INTERVAL` even when no OS jobs are
/// visible to the parent task.
#[test]
fn slow_async_callback_finishes() {
fn slow_nested_tool_finishes() {
let (reg, _host) = load_task_host();
let out = exec_tool(&reg, TASK_TOOL, task_input(SCENARIO_SLOW, None))
.expect("slow async callback should finish");
Expand All @@ -417,3 +414,26 @@ fn slow_async_callback_finishes() {
assert_eq!(snap["prompt_count"], json!(1));
assert_eq!(snap["closed"], json!(1));
}

#[test]
fn three_concurrent_tasks_return_results_without_nil_lifecycle_errors() {
let (reg, _host) = load_task_host();
let calls: Vec<_> = (0..3)
.map(|_| {
let reg = Arc::clone(&reg);
std::thread::spawn(move || exec_tool(&reg, TASK_TOOL, task_input(SCENARIO_PLAIN, None)))
})
.collect();

for call in calls {
let out = call
.join()
.expect("task thread panicked")
.expect("concurrent task failed");
assert_eq!(out, PLAIN_TEXT);
}

let snap = probe(&reg);
assert_eq!(snap["sessions"], json!(3));
assert_eq!(snap["closed"], json!(3));
}
33 changes: 23 additions & 10 deletions n00n-ui/src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ const IMPLEMENT_PARALLEL_HINT: &str = "Use batch+task to parallelize, assign eac
const TASK_DONE_DETAIL: &str = "✓ done";
const TASK_ERROR_DETAIL: &str = "✗ error";
const TASK_RUNNING_DETAIL: &str = "◈ running";
const TASK_PANEL_FOOTER: &[(&str, &str)] = &[("enter", "attach"), ("esc", "close")];
const TASK_PANEL_FOOTER: &[(&str, &str)] =
&[("enter", "open"), ("ctrl+x", "toggle"), ("esc", "close")];

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum TaskStatus {
Expand Down Expand Up @@ -485,23 +486,31 @@ impl App {
} else {
TaskStatus::Running
};
let usage = (c.token_usage.total_input() + c.token_usage.output > 0).then(|| {
format!(
"{} in / {} out",
c.token_usage.total_input(),
c.token_usage.output
)
});
let usage = if i == 0 {
Some("main session".to_owned())
} else {
let model = c.model_id.as_deref().unwrap_or("model pending");
let tokens = c.token_usage.total_input() + c.token_usage.output;
Some(if tokens > 0 {
format!("{model} · {tokens} tokens")
} else {
model.to_owned()
})
};
TaskEntry {
name: c.name.clone(),
name: if i == 0 {
"Main chat".to_owned()
} else {
format!("Agent: {}", c.name)
},
status,
usage,
}
})
.collect();
self.task_picker_original = Some(self.active_chat);
self.task_picker.set_footer(TASK_PANEL_FOOTER);
self.task_picker.open(entries, " Tasks ");
self.task_picker.open(entries, " Agents & Teams ");
self.task_picker.select(self.active_chat);
}

Expand Down Expand Up @@ -962,6 +971,10 @@ impl App {
self.submit_or_queue(sub.into())
}

pub(crate) fn cancel_current_run(&mut self) -> Vec<Action> {
self.handle_cancel()
}

fn handle_cancel(&mut self) -> Vec<Action> {
let cancelled_run = self.run_id;
self.run_id += 1;
Expand Down
11 changes: 11 additions & 0 deletions n00n-ui/src/app/mouse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,17 @@ impl App {
{
self.copy_text(&text, format!("Copied {label}"));
} else {
let session = self.chats[self.active_chat]
.tool_id_at(event.row, area)
.and_then(|id| {
self.chats.iter().position(|chat| {
chat.tool_use_id.as_deref() == Some(id)
})
});
if let Some(idx) = session {
self.active_chat = idx;
return;
}
self.chats[self.active_chat].handle_click(event.row, area);
}
}
Expand Down
28 changes: 28 additions & 0 deletions n00n-ui/src/app/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -797,13 +797,41 @@ fn batch_subagent_done_marker(is_error: bool, expected_text: &str, expected_role
assert_eq!(app.chats[1].last_message_role(), Some(expected_role));
}

#[test]
fn completed_subagent_chat_remains_discoverable_by_tool_id() {
let mut app = app_with_subagent();
finish_subagent_task(&mut app, false);
app.chat_index.clear();

let idx = app
.chats
.iter()
.position(|chat| chat.tool_use_id.as_deref() == Some("task1"));
assert_eq!(idx, Some(1));
}

fn open_tasks_picker(app: &mut App) {
for c in "/tasks".chars() {
app.update(Msg::Key(key(KeyCode::Char(c))));
}
app.update(Msg::Key(key(KeyCode::Enter)));
}

#[test]
fn agent_picker_exposes_names_models_and_status() {
let mut app = app_with_subagent();
app.chats[1].model_id = Some("openai/test-model".into());
open_tasks_picker(&mut app);

let main = app.task_picker.item(0).unwrap();
assert_eq!(main.label(), "Main chat");
assert_eq!(main.suffix(), Some("main session"));
let agent = app.task_picker.item(1).unwrap();
assert_eq!(agent.label(), "Agent: research");
assert_eq!(agent.suffix(), Some("openai/test-model"));
assert_eq!(agent.detail(), Some(TASK_RUNNING_DETAIL));
}

#[test]
fn ctrl_x_toggles_tasks_picker() {
let mut app = test_app();
Expand Down
4 changes: 4 additions & 0 deletions n00n-ui/src/chat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,10 @@ impl Chat {
self.messages_panel.copy_at(row, col, area)
}

pub fn tool_id_at(&self, row: u16, area: Rect) -> Option<&str> {
self.messages_panel.tool_id_at(row, area)
}

pub fn handle_click(&mut self, row: u16, area: Rect) {
self.messages_panel.handle_click(row, area);
}
Expand Down
2 changes: 1 addition & 1 deletion n00n-ui/src/components/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub struct BuiltinCommand {
pub const BUILTIN_COMMANDS: &[BuiltinCommand] = &[
BuiltinCommand {
name: "/tasks",
description: "Browse and search tasks",
description: "Browse running and completed agents and teams",
max_args: 0,
},
BuiltinCommand {
Expand Down
Loading
Loading