diff --git a/GLOSSARY.md b/GLOSSARY.md index 16546179f..dcfe72b12 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -38,8 +38,9 @@ _Avoid_: System prompt — that is the Character Prompt, which carries this and **Character Prompt**: The opening turn of the Director session: Personality Prompt, Instance Prompt, -the Behaviors it may propose, and this moment. Later wakes send a short -follow-up (what just happened, recent Behaviors, time of day, State, what the +the Behaviors it may propose, the Instance's own id for its tool calls, and this +moment. Later wakes send a short +follow-up (the Instance's id, what just happened, recent Behaviors, time of day, State, what the user is doing) in the same conversation. Assembled rather than written: two of its layers are authored, the whole is never hand-authored. The Prompt tab shows the three concatenated layers — app-level instructions, Personality Prompt, @@ -58,7 +59,8 @@ The Director mode that empties the built-in prompt layers — the package Personality Prompt and the app-level instructions (voice rules, Behavior roster, reply contract) — and still sends an Instance Prompt the user wrote. Off by default. The Prompt tab shows those emptied fields as Empty: what you see is -what is sent. With no contract the reply is prose, so the character talks and plays +what is sent, apart from the Instance id line, which stays so tool calls still +reach this Instance. With no contract the reply is prose, so the character talks and plays no Behavior unless the Instance Prompt asks for one. That is the control run for telling a model's misbehaviour apart from the shipped prompt, and for iterating a prompt under Fidget's conditions. #657, #680. diff --git a/README.md b/README.md index f9d26f4fc..752e6b6b6 100644 --- a/README.md +++ b/README.md @@ -333,9 +333,11 @@ Fidget attaches to a Harness over ACP on stdio. The Harness calls back over MCP, | `describe_screen` | Sensing | Describe screen (v1: window metadata only) | | `recall` | Memory | Read everything Memory holds | | `remember` | Memory | Write one fact under a heading | -| `list_instances` | Identity | List Character Instances and their names | +| `list_instances` | Identity | List Character Instances: id, name, and the three Character Prompt layers | | `whereabouts` | Placement | Which display each Instance is on, the other displays, and its feet in that display. Each display includes its name when the platform has one, its origin, and its size, in logical points | +Every tool takes an optional `instance_id`. Each Character Instance has its own Harness session, and that session's opening turn names its id, so `speak` and `play_behavior` land on the Instance whose session called them. An id no running Instance has is refused. + **Three readonly resources** (`resources/list`, `resources/read`; no write, no subscribe): | URI | What it is | diff --git a/crates/core/src/director.rs b/crates/core/src/director.rs index 0b8e9d16d..d02a72648 100644 --- a/crates/core/src/director.rs +++ b/crates/core/src/director.rs @@ -26,8 +26,10 @@ use crate::sensing::Activity; mod prompt; mod recency; +#[cfg(test)] +use prompt::follow_up; pub use prompt::{app_instructions, happened_word, typed_line}; -pub(crate) use prompt::{character_prompt, follow_up}; +pub(crate) use prompt::{character_prompt, named_moment}; pub use recency::{Doing, Lately, Recency, Step}; /// How long the Static Director goes unwoken when nothing notable happens. @@ -351,9 +353,9 @@ impl ModelDirector { /// The user turn for this wake. Settings shows this string. pub fn prompt(&self, context: &Context) -> String { if self.opened.load(Ordering::SeqCst) { - follow_up(context) + named_moment(context, &self.instance) } else { - character_prompt(context, self.behaviors.iter(), self.blank) + character_prompt(context, &self.instance, self.behaviors.iter(), self.blank) } } @@ -1844,7 +1846,7 @@ mod tests { fn the_completer_is_sent_the_character_prompt() { let director = directing(Scripted::says("wave"), ["wave"]); let moment = context(working(), &["nap"]); - let expected = character_prompt(&moment, ["wave"], false); + let expected = character_prompt(&moment, "buddy-1", ["wave"], false); director.wake(&moment); @@ -2145,7 +2147,7 @@ mod tests { caffeinate: None, }; - let payload = character_prompt(&moment, ["greet", "stroll", "wave"], false); + let payload = character_prompt(&moment, "buddy-1", ["greet", "stroll", "wave"], false); assert!( payload.contains("Blip is cheerful."), @@ -2208,7 +2210,7 @@ mod tests { fn an_empty_instance_prompt_assembles_the_payload_it_always_did() { let moment = context(working(), &["nap"]); - let payload = character_prompt(&moment, ["wave"], false); + let payload = character_prompt(&moment, "buddy-1", ["wave"], false); assert!( payload.starts_with("a shy robot.\n\nYou may propose one of these behaviors: wave"), @@ -2226,7 +2228,7 @@ mod tests { ..context(working(), &["nap"]) }; - let payload = character_prompt(&moment, ["wave"], false); + let payload = character_prompt(&moment, "buddy-1", ["wave"], false); let personality = payload.find("a shy robot.").expect("the author's layer"); let instance = payload.find("Answer in haiku.").expect("the user's layer"); @@ -2250,12 +2252,15 @@ mod tests { ..context(working(), &["nap"]) }; - let shaped = character_prompt(&moment, ["wave"], false); - let blank = character_prompt(&moment, ["wave"], true); + let shaped = character_prompt(&moment, "buddy-1", ["wave"], false); + let blank = character_prompt(&moment, "buddy-1", ["wave"], true); assert!( - blank.starts_with("Answer in haiku.\n\nwhat just happened:"), - "the Instance Prompt is still in front of the moment: {blank}" + blank.starts_with( + "Answer in haiku.\n\nYour instance_id is buddy-1. \ + Pass it to every Fidget tool you call.\n\nwhat just happened:" + ), + "the Instance Prompt and the id are still in front of the moment: {blank}" ); assert!( !blank.contains("a shy robot."), @@ -2298,7 +2303,7 @@ mod tests { #[test] fn a_request_invites_the_tools_without_naming_them() { let moment = context(working(), &["nap"]); - let opening = character_prompt(&moment, ["wave"], false); + let opening = character_prompt(&moment, "buddy-1", ["wave"], false); assert!( opening.contains( @@ -2348,10 +2353,42 @@ mod tests { } #[test] - fn blank_mode_without_an_instance_prompt_is_the_moment() { + fn blank_mode_without_an_instance_prompt_is_the_id_and_the_moment() { let moment = context(working(), &["nap"]); - let blank = character_prompt(&moment, ["wave"], true); - assert_eq!(blank, follow_up(&moment)); + let blank = character_prompt(&moment, "buddy-1", ["wave"], true); + assert_eq!( + blank, + format!( + "Your instance_id is buddy-1. Pass it to every Fidget tool you call.\n\n{}", + follow_up(&moment) + ) + ); + } + + /// Each session's opening names its own Instance, so a tool call made + /// from it lands there and not on another Instance. + #[test] + fn every_turn_names_this_instance() { + let moment = context(working(), &["nap"]); + let pip = character_prompt(&moment, "pip", ["wave"], false); + let rex = character_prompt(&moment, "rex", ["wave"], false); + + assert!(pip.contains("Your instance_id is pip."), "{pip}"); + assert!(rex.contains("Your instance_id is rex."), "{rex}"); + assert!(!pip.contains("rex"), "{pip}"); + + // A session the Harness opened mid-run hears only follow-ups, so they + // carry the id too. + let director = directing(Scripted::says("wave"), ["wave"]); + director.wake(&moment); + let later = director.prompt(&moment); + assert!( + later.starts_with( + "Your instance_id is buddy-1. Pass it to every Fidget tool you call.\n\n" + ), + "{later}" + ); + assert!(!later.contains("always in character"), "{later}"); } /// Each rule the opening turn must carry, and that later wakes do not @@ -2359,7 +2396,7 @@ mod tests { #[test] fn the_character_prompt_carries_the_voice_rules_once() { let moment = context(working(), &["nap"]); - let payload = character_prompt(&moment, ["wave"], false); + let payload = character_prompt(&moment, "buddy-1", ["wave"], false); assert!( payload.contains("always in character"), @@ -2405,7 +2442,7 @@ mod tests { .completer .seen_prompt() .expect("a follow-up was sent"); - assert_eq!(sent, follow_up(&later)); + assert_eq!(sent, named_moment(&later, "buddy-1")); assert!( !sent.contains("a shy robot."), "personality is the opening only: {sent}" @@ -2517,7 +2554,7 @@ mod tests { Some(line), "follow-up: {line:?}" ); - let opening = character_prompt(&moment, ["wave"], false); + let opening = character_prompt(&moment, "buddy-1", ["wave"], false); assert_eq!(typed_line(&opening), Some(line), "opening: {line:?}"); } } @@ -2531,7 +2568,7 @@ mod tests { }; assert_eq!(typed_line(&follow_up(&ambient)), None); assert_eq!( - typed_line(&character_prompt(&ambient, ["wave"], false)), + typed_line(&character_prompt(&ambient, "buddy-1", ["wave"], false)), None ); assert_eq!(typed_line("an ordinary prompt"), None); @@ -2546,7 +2583,7 @@ mod tests { ..typed("hello?") }; assert_eq!( - typed_line(&character_prompt(&moment, ["wave"], false)), + typed_line(&character_prompt(&moment, "buddy-1", ["wave"], false)), Some("hello?") ); } @@ -2909,7 +2946,7 @@ mod tests { .completer .seen_prompt() .expect("a follow-up was sent"); - assert_eq!(sent, follow_up(&asked)); + assert_eq!(sent, named_moment(&asked, "buddy-1")); assert!( !sent.contains("a shy robot."), "personality is the opening only: {sent}" diff --git a/crates/core/src/director/prompt.rs b/crates/core/src/director/prompt.rs index c9f4cd84b..927304b52 100644 --- a/crates/core/src/director/prompt.rs +++ b/crates/core/src/director/prompt.rs @@ -1,14 +1,16 @@ use super::{Context, Doing, Happened, Lately, State, Step, CHAT_LIMIT}; -/// The opening turn: Personality Prompt, Instance Prompt (ADR-0012), roster -/// and moment; later wakes send `follow_up`. `blank` empties the built-in -/// layers for the control run, keeping the rest; its reply is prose. +/// The opening turn: Personality Prompt, Instance Prompt (ADR-0012), roster, +/// the Instance's own id and moment; later wakes send `named_moment`. `blank` +/// empties the built-in layers for the control run, keeping the rest; its +/// reply is prose. pub(crate) fn character_prompt( context: &Context, + instance: &str, behaviors: impl IntoIterator>, blank: bool, ) -> String { - let moment = follow_up(context); + let moment = named_moment(context, instance); // Empty, not `(no personality)`: that placeholder is a Character with an // empty file, which still gets the voice rules. Blank AI is the emptied @@ -40,6 +42,17 @@ pub(crate) fn character_prompt( } } +/// The moment, led by this Instance's id. Every turn carries the id, and +/// blank mode keeps it: it routes tool calls to this Instance, which is +/// plumbing rather than voice, and a session the Harness opened mid-run hears +/// only follow-ups. +pub(crate) fn named_moment(context: &Context, instance: &str) -> String { + format!( + "Your instance_id is {instance}. Pass it to every Fidget tool you call.\n\n{}", + follow_up(context) + ) +} + /// The app layer of the Character Prompt: voice rules, roster, reply contract. /// Empty under Blank AI, which the Prompt tab shows frozen. Paid every wake, /// so the tools describe themselves over MCP; a copy here would drift. diff --git a/crates/core/src/dispatch.rs b/crates/core/src/dispatch.rs index fe27a543b..1e365710e 100644 --- a/crates/core/src/dispatch.rs +++ b/crates/core/src/dispatch.rs @@ -80,11 +80,44 @@ fn parse_args Deserialize<'de>>( }) } +fn unknown_instance(id: &str, roster: &[InstanceInfo]) -> String { + if roster.is_empty() { + return format!("No Character Instance has id {id}. No Character Instance is running."); + } + let running = roster + .iter() + .map(|info| format!("{} ({})", info.id, info.name)) + .collect::>() + .join(", "); + format!( + "No Character Instance has id {id}. Running: {running}. \ + Pass your own instance_id from your prompt, or call list_instances to find it." + ) +} + pub fn dispatch( tool_name: &str, arguments: Value, context: &mut DispatchContext, ) -> Result { + // One gate for every tool, so a tool added later refuses a stray id too. + if let Some(given) = arguments + .get("instance_id") + .filter(|given| !given.is_null()) + { + let Some(id) = given.as_str() else { + return Err(DispatchError { + code: ErrorCode::InvalidArguments, + message: "instance_id must be a string".to_string(), + }); + }; + if !context.roster.iter().any(|info| info.id == id) { + return Err(DispatchError { + code: ErrorCode::InvalidArguments, + message: unknown_instance(id, context.roster), + }); + } + } match tool_name { "speak" => { #[derive(Deserialize)] @@ -233,7 +266,7 @@ pub struct ToolInfo { /// The tools in `tools`, and none that post input events. pub fn list_tools() -> Vec { - vec![ + let mut tools = vec![ ToolInfo { name: "speak".to_string(), description: "Make the Character speak a line of dialogue".to_string(), @@ -243,10 +276,6 @@ pub fn list_tools() -> Vec { "message": { "type": "string", "description": "The message to speak" - }, - "instance_id": { - "type": "string", - "description": "Optional instance ID to target" } }, "required": ["message"] @@ -261,10 +290,6 @@ pub fn list_tools() -> Vec { "behavior": { "type": "string", "description": "The name of the Behavior to play" - }, - "instance_id": { - "type": "string", - "description": "Optional instance ID to target" } }, "required": ["behavior"] @@ -314,7 +339,7 @@ pub fn list_tools() -> Vec { }, ToolInfo { name: "list_instances".to_string(), - description: "List Character Instances and their names".to_string(), + description: "List Character Instances: each one's instance_id, name, and the three layers of its Character Prompt (app_instructions, personality_prompt, instance_prompt). Read it when your session did not open with your instance_id or prompt.".to_string(), input_schema: serde_json::json!({ "type": "object", "properties": {} @@ -341,7 +366,14 @@ pub fn list_tools() -> Vec { } }), }, - ] + ]; + for tool in &mut tools { + tool.input_schema["properties"]["instance_id"] = serde_json::json!({ + "type": "string", + "description": "Your Character Instance id, named in your prompt. speak and play_behavior act on that Instance. Optional while only one Instance runs." + }); + } + tools } #[cfg(test)] @@ -467,10 +499,14 @@ mod tests { InstanceInfo { id: "inst-1".to_string(), name: "Clippy".to_string(), + app_instructions: "Reply with behavior: ".to_string(), + personality_prompt: "a paperclip".to_string(), + instance_prompt: "Answer in haiku.".to_string(), }, InstanceInfo { id: "inst-2".to_string(), name: "Ferris".to_string(), + ..Default::default() }, ]; let source = fake_source(vec![]); @@ -483,6 +519,13 @@ mod tests { assert_eq!(instances.len(), 2); assert_eq!(instances[0]["id"], "inst-1"); assert_eq!(instances[0]["name"], "Clippy"); + assert_eq!( + instances[0]["app_instructions"], + "Reply with behavior: " + ); + assert_eq!(instances[0]["personality_prompt"], "a paperclip"); + assert_eq!(instances[0]["instance_prompt"], "Answer in haiku."); + assert_eq!(instances[1]["instance_prompt"], ""); } #[test] @@ -847,7 +890,11 @@ mod tests { .borrow() .list() .into_iter() - .map(|(id, name)| InstanceInfo { id, name }) + .map(|(id, name)| InstanceInfo { + id, + name, + ..Default::default() + }) .collect::>(); let mut expression = SharedRoster(Rc::clone(&shared)); @@ -894,7 +941,11 @@ mod tests { let roster_info = roster .list() .into_iter() - .map(|(id, name)| InstanceInfo { id, name }) + .map(|(id, name)| InstanceInfo { + id, + name, + ..Default::default() + }) .collect::>(); let mut context = DispatchContext { @@ -933,7 +984,11 @@ mod tests { let roster_info = roster .list() .into_iter() - .map(|(id, name)| InstanceInfo { id, name }) + .map(|(id, name)| InstanceInfo { + id, + name, + ..Default::default() + }) .collect::>(); let mut context = DispatchContext { @@ -998,7 +1053,11 @@ mod tests { let roster_info = roster .list() .into_iter() - .map(|(id, name)| InstanceInfo { id, name }) + .map(|(id, name)| InstanceInfo { + id, + name, + ..Default::default() + }) .collect::>(); let mut context = DispatchContext { @@ -1040,10 +1099,12 @@ mod tests { InstanceInfo { id: "instance-1".to_string(), name: "First".to_string(), + ..Default::default() }, InstanceInfo { id: "instance-2".to_string(), name: "Second".to_string(), + ..Default::default() }, ]; let mut context = test_context(&temp, &source, &infos); @@ -1055,31 +1116,106 @@ mod tests { assert_eq!(result["message"], "Hello"); assert_eq!( result["reason"], - "Several Character Instances are running; name one with instance_id" + "Several Character Instances are running; name one with instance_id. \ + Call list_instances to find each one's instance_id." ); } + /// Every tool, not only the Expression ones, refuses an id no Instance + /// carries, and the refusal names the ids that would work. #[test] - fn unknown_instance_id_is_failure() { + fn every_tool_refuses_an_unknown_instance_id_and_names_the_running_ones() { let temp = tempfile::tempdir().expect("temp dir is creatable"); let source = fake_source(vec![]); - let infos = [InstanceInfo { - id: "known-instance".to_string(), - name: "Known".to_string(), - }]; + let infos = [ + InstanceInfo { + id: "pip".to_string(), + name: "Pip".to_string(), + ..Default::default() + }, + InstanceInfo { + id: "rex".to_string(), + name: "Rex".to_string(), + ..Default::default() + }, + ]; let mut context = test_context(&temp, &source, &infos); - let args = json!({"message": "Hello", "instance_id": "unknown-instance"}); - let result = dispatch("speak", args, &mut context).expect("dispatch succeeds"); + for tool in list_tools() { + let refused = dispatch( + &tool.name, + json!({"message": "hi", "behavior": "wave", "instance_id": "nope"}), + &mut context, + ) + .expect_err(&format!("{} accepted an unknown instance_id", tool.name)); + assert_eq!(refused.code, ErrorCode::InvalidArguments, "{}", tool.name); + assert_eq!( + refused.message, + "No Character Instance has id nope. Running: pip (Pip), rex (Rex). \ + Pass your own instance_id from your prompt, or call list_instances to find it.", + "{}", + tool.name + ); + } + } + + #[test] + fn an_instance_id_with_nothing_running_says_so() { + let temp = tempfile::tempdir().expect("temp dir is creatable"); + let source = fake_source(vec![]); + let mut context = test_context(&temp, &source, &[]); + + let refused = dispatch("recall", json!({"instance_id": "nope"}), &mut context) + .expect_err("an id is refused when no Instance runs"); - assert_eq!(result["success"], false); - assert_eq!(result["message"], "Hello"); assert_eq!( - result["reason"], - "No Character Instance has id unknown-instance" + refused.message, + "No Character Instance has id nope. No Character Instance is running." ); } + /// A known id is accepted by a tool that does not target anything. + #[test] + fn a_known_instance_id_passes_through_a_sensing_tool() { + let temp = tempfile::tempdir().expect("temp dir is creatable"); + let source = fake_source(vec![window("Terminal", 0.0, 0.0, 10.0, 10.0)]); + let infos = [InstanceInfo { + id: "pip".to_string(), + name: "Pip".to_string(), + ..Default::default() + }]; + let mut context = test_context(&temp, &source, &infos); + + let result = dispatch("list_windows", json!({"instance_id": "pip"}), &mut context) + .expect("a known id is accepted"); + + assert_eq!(result["windows"][0]["owner"], "Terminal"); + let refused = dispatch("list_windows", json!({"instance_id": 5}), &mut context) + .expect_err("an id that is not a string slipped past the check"); + assert_eq!(refused.code, ErrorCode::InvalidArguments); + assert_eq!(refused.message, "instance_id must be a string"); + } + + /// Optional, so the stdio shim in the user's own sessions keeps working + /// with one Instance (ADR-0026). + #[test] + fn every_tool_advertises_an_optional_instance_id() { + for tool in list_tools() { + let schema = &tool.input_schema; + assert_eq!( + schema["properties"]["instance_id"]["type"], "string", + "{}", + tool.name + ); + let required = schema["required"].as_array().cloned().unwrap_or_default(); + assert!( + !required.contains(&json!("instance_id")), + "{} requires instance_id", + tool.name + ); + } + } + /// Break: success on an empty roster lets a stdio verification pass /// against nothing at all. #[test] @@ -1137,6 +1273,7 @@ mod tests { let infos = [InstanceInfo { id: "instance-1".to_string(), name: "Buddy".to_string(), + ..Default::default() }]; // `test_context` carries `expression: None`, which is the shipped // stdio shape. @@ -1167,6 +1304,7 @@ mod tests { let roster_info = [InstanceInfo { id: "retired-instance".to_string(), name: "Gone".to_string(), + ..Default::default() }]; let mut live = crate::roster::Roster::new(); @@ -1199,7 +1337,11 @@ mod tests { let roster_info = roster .list() .into_iter() - .map(|(id, name)| InstanceInfo { id, name }) + .map(|(id, name)| InstanceInfo { + id, + name, + ..Default::default() + }) .collect::>(); let mut context = DispatchContext { diff --git a/crates/core/src/roster.rs b/crates/core/src/roster.rs index 41ec2a766..0afd4828d 100644 --- a/crates/core/src/roster.rs +++ b/crates/core/src/roster.rs @@ -976,6 +976,7 @@ mod tests { instance_prompt: instance.prompt().to_string(), ..crate::director::Context::quiet() }, + &id, wolf.behaviors.keys(), false, ); diff --git a/crates/core/src/tools.rs b/crates/core/src/tools.rs index d2e9c79d0..d8c11c355 100644 --- a/crates/core/src/tools.rs +++ b/crates/core/src/tools.rs @@ -77,11 +77,19 @@ pub struct RememberResult { pub recorded: String, } -/// Tool result for the `list_instances` tool. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +/// Tool result for the `list_instances` tool. The three prompts are the +/// Character Prompt layers the Prompt tab shows, so a session that never +/// heard its opening can read them back (ADR-0012). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct InstanceInfo { pub id: String, pub name: String, + #[serde(default)] + pub app_instructions: String, + #[serde(default)] + pub personality_prompt: String, + #[serde(default)] + pub instance_prompt: String, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -252,12 +260,10 @@ mod helpers { "No Character Instance is running, so nothing changed on screen".to_string(), ); } - TargetResolution::UnknownInstance(id) => { - return Err(format!("No Character Instance has id {id}")); - } TargetResolution::AmbiguousTarget => { return Err( - "Several Character Instances are running; name one with instance_id" + "Several Character Instances are running; name one with instance_id. \ + Call list_instances to find each one's instance_id." .to_string(), ); } @@ -288,24 +294,17 @@ mod helpers { enum TargetResolution { Resolved(String), NoInstances, - /// The caller named an id no Instance in the roster carries. - UnknownInstance(String), AmbiguousTarget, } /// Target resolution against roster for both speak and play_behavior. + /// `dispatch` already refused an id the roster does not carry. fn resolve_target_instance( instance_id: Option<&str>, roster: &[InstanceInfo], ) -> TargetResolution { match instance_id { - Some(id) => { - if roster.iter().any(|info| info.id == id) { - TargetResolution::Resolved(id.to_string()) - } else { - TargetResolution::UnknownInstance(id.to_string()) - } - } + Some(id) => TargetResolution::Resolved(id.to_string()), None => match roster.len() { 0 => TargetResolution::NoInstances, 1 => TargetResolution::Resolved(roster[0].id.clone()), diff --git a/src-tauri/src/frame_loop.rs b/src-tauri/src/frame_loop.rs index dd801413b..cf8eee34f 100644 --- a/src-tauri/src/frame_loop.rs +++ b/src-tauri/src/frame_loop.rs @@ -1159,6 +1159,7 @@ pub(crate) fn run_frame_loop( answer_tool_call( call, &mut roster, + &characters, assembler.source(), excluded, &displays, @@ -2925,16 +2926,43 @@ fn replace_session( fn answer_tool_call( call: mcp_http::Call, roster: &mut Roster, + characters: &std::collections::BTreeMap>, source: &dyn WindowSource, excluded_applications: Vec, displays: &platform::Displays, caffeinate: Option<&mut dyn fidget_core::caffeinate::CaffeinateHandle>, ) { let watched = crate::names_hint::live().watching(source); + // The layers the Prompt tab shows, so a session opened mid-run can read + // what its opening turn would have told it. Only list_instances returns + // them, so no other call pays for building them. + let with_prompts = call.tool == "list_instances"; + let blank = model::blank(); let live: Vec = roster .list() .into_iter() - .map(|(id, name)| InstanceInfo { id, name }) + .map(|(id, name)| { + let Some(instance) = roster.get(&id).filter(|_| with_prompts) else { + return InstanceInfo { + id, + name, + ..Default::default() + }; + }; + InstanceInfo { + app_instructions: director::app_instructions( + super::behavior_names_of(characters, instance), + blank, + ), + personality_prompt: match blank { + true => String::new(), + false => super::personality_of(characters, instance), + }, + instance_prompt: instance.prompt().to_string(), + id, + name, + } + }) .collect(); let spots: Vec = live .iter() @@ -3153,6 +3181,7 @@ mod tests { reply, }, &mut roster, + &std::collections::BTreeMap::new(), &EmptyDesktop, Vec::new(), &platform::Displays::default(), @@ -3175,6 +3204,53 @@ mod tests { std::fs::remove_dir_all(&dir).ok(); } + /// A session the Harness opened mid-run never heard its opening turn. It + /// reads its id and the three prompt layers back from the live Instance. + #[test] + fn a_list_instances_call_carries_the_live_prompt_layers() { + let mut roster = Roster::new(); + let id = roster.spawn(&character(), "Pip".to_string(), Point { x: 0.0, y: 0.0 }); + roster + .get_mut(&id) + .expect("just spawned") + .set_prompt("Answer in haiku.".to_string()); + let characters = std::collections::BTreeMap::from([( + "Buddy".to_string(), + Arc::new(Character { + personality: "a shy robot.".to_string(), + ..character() + }), + )]); + + let (reply, answers) = mpsc::channel(); + answer_tool_call( + mcp_http::Call { + tool: "list_instances".to_string(), + arguments: json!({}), + reply, + }, + &mut roster, + &characters, + &EmptyDesktop, + Vec::new(), + &platform::Displays::default(), + None, + ); + let result = answers + .recv() + .expect("the call is answered") + .expect("dispatch succeeds"); + + let pip = &result["instances"][0]; + assert_eq!(pip["id"], json!(id)); + assert_eq!( + pip["app_instructions"], + json!(director::app_instructions(["wave"], false)) + ); + assert_eq!(pip["personality_prompt"], json!("a shy robot.")); + assert_eq!(pip["instance_prompt"], json!("Answer in haiku.")); + } + /// The Harness reads placement from the live Instances and the displays /// the frame loop already holds. #[test] @@ -3215,6 +3291,7 @@ mod tests { reply, }, &mut roster, + &std::collections::BTreeMap::new(), &EmptyDesktop, Vec::new(), &displays, diff --git a/src-tauri/src/harness.rs b/src-tauri/src/harness.rs index 90244a1ec..a6263ad7c 100644 --- a/src-tauri/src/harness.rs +++ b/src-tauri/src/harness.rs @@ -6618,25 +6618,29 @@ mod tests { } /// Two Character Instances never share an ACP session, even when they - /// are the same Character. One Harness child throughout. + /// are the same Character, and turns that alternate between them each go + /// back to their own. One Harness child throughout. #[test] fn two_character_instances_do_not_share_an_acp_session() { let (fx, session) = Fixture::new("happy"); - assert_eq!( - session.complete(&asking_as("buddy-1", "bmo", "hi"), &|_| {}), - Ok(Reply::whole("Hello")) - ); - assert_eq!( - session.complete(&asking_as("buddy-2", "bmo", "hi"), &|_| {}), - Ok(Reply::whole("Hello")) - ); + for instance in ["buddy-1", "buddy-2", "buddy-1", "buddy-2"] { + assert_eq!( + session.complete(&asking_as(instance, "bmo", "hi"), &|_| {}), + Ok(Reply::whole("Hello")) + ); + } session.shutdown(); - let prompts = fx.events("prompt"); - assert_eq!(prompts.len(), 2, "{prompts:?}"); - assert_ne!( - prompts[0]["session_id"], prompts[1]["session_id"], - "Instance B continued Instance A's session: {prompts:?}" + let sessions = prompt_sessions(&fx); + assert_eq!( + sessions, + [ + json!("fresh-id"), + json!("fresh-id-2"), + json!("fresh-id"), + json!("fresh-id-2") + ], + "a turn went to another Instance's session" ); assert_eq!(fx.count("spawn"), 1, "a second Completer was spawned"); let saved: SavedSession =