Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-driver): route background text through Hyprland input (#3877)
Francesco Bonacci42d764bb19e9
diff --git a/libs/cua-driver/hyprland-plugin/tests/production_app_smoke.py b/libs/cua-driver/hyprland-plugin/tests/production_app_smoke.pyindex 231a0637f9..6ea503ff3b 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_app_smoke.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_app_smoke.py@@ -288,9 +288,9 @@ def verify_calc(before, after):cell = row.find('table:table-cell', NS)assert cell is not Noneassert cell.get(f"{{{NS['office']}}}value-type") == 'string'- assert ''.join(cell.itertext()) == 'a', 'saved A1 does not contain the expected letter'+ assert ''.join(cell.itertext()) == 'abc', 'saved A1 does not contain the expected text'assert cell.get(f"{{{NS['table']}}}formula") is None- return {'cell': 'A1', 'text': 'a', 'verified': True}+ return {'cell': 'A1', 'text': 'abc', 'verified': True}def rectangle(content):@@ -569,7 +569,7 @@ def run_app(mcp, app, document, directory):try:require_background_target(target, directory)if app == 'calc':- steps = [('insert', 'press_key', {'key': 'a'}),+ steps = [('insert', 'type_text', {'text': 'abc'}),('commit', 'press_key', {'key': 'Return'}),('save', 'hotkey', {'keys': ['ctrl', 's']})]else:diff --git a/libs/cua-driver/hyprland-plugin/tests/production_app_smoke_test.py b/libs/cua-driver/hyprland-plugin/tests/production_app_smoke_test.pyindex 304c9dbb4d..aa738e07c0 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_app_smoke_test.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_app_smoke_test.py@@ -50,7 +50,7 @@ INKSCAPE_SELECTED = {}-def changed_ods(original, text='a', empty_first=False):+def changed_ods(original, text='abc', empty_first=False):destination = io.BytesIO()with zipfile.ZipFile(io.BytesIO(original)) as source, zipfile.ZipFile(destination, 'w') as target:for name in source.namelist():@@ -345,17 +345,17 @@ class InputTests(unittest.TestCase):mcp = Mock()mcp.tool.side_effect = [{'structuredContent': CALC}, WINDOWS, GOOD_DELIVERY,{'structuredContent': CALC}, WINDOWS]- input_step(mcp, TARGET, 'cua-smoke-calc.ods', 'calc', 'insert', 'press_key', {'key': 'a'})+ input_step(mcp, TARGET, 'cua-smoke-calc.ods', 'calc', 'insert', 'type_text', {'text': 'abc'})calls = mcp.tool.call_args_listself.assertEqual([call.args[0] for call in calls],- ['get_window_state', 'list_windows', 'press_key', 'get_window_state', 'list_windows'])- self.assertEqual(calls[2].args[1], {**TARGET, 'key': 'a', 'delivery_mode': 'background'})+ ['get_window_state', 'list_windows', 'type_text', 'get_window_state', 'list_windows'])+ self.assertEqual(calls[2].args[1], {**TARGET, 'text': 'abc', 'delivery_mode': 'background'})def test_missing_grounding_sends_no_input(self):mcp = Mock()mcp.tool.side_effect = [{'structuredContent': {**CALC, 'elements': []}}, WINDOWS]with self.assertRaises(GroundingUnavailable):- input_step(mcp, TARGET, 'cua-smoke-calc.ods', 'calc', 'insert', 'press_key', {'key': 'a'})+ input_step(mcp, TARGET, 'cua-smoke-calc.ods', 'calc', 'insert', 'type_text', {'text': 'abc'})self.assertEqual(mcp.tool.call_count, 2)def test_partial_delivery_stays_failure_even_if_dialog_appears(self):@@ -365,7 +365,7 @@ class InputTests(unittest.TestCase):mcp.tool.side_effect = [{'structuredContent': CALC}, WINDOWS, partial,{'structuredContent': dialog}, WINDOWS]with self.assertRaises(AssertionError):- input_step(mcp, TARGET, 'cua-smoke-calc.ods', 'calc', 'insert', 'press_key', {'key': 'a'})+ input_step(mcp, TARGET, 'cua-smoke-calc.ods', 'calc', 'insert', 'type_text', {'text': 'abc'})self.assertEqual(mcp.tool.call_count, 5)def test_unknown_transport_outcome_is_not_replayed(self):@@ -373,7 +373,7 @@ class InputTests(unittest.TestCase):mcp.tool.side_effect = [{'structuredContent': CALC}, WINDOWS, TimeoutError('unknown')]with patch('production_app_smoke.read', side_effect=OSError('unavailable')):with self.assertRaises(TimeoutError):- input_step(mcp, TARGET, 'cua-smoke-calc.ods', 'calc', 'insert', 'press_key', {'key': 'a'})+ input_step(mcp, TARGET, 'cua-smoke-calc.ods', 'calc', 'insert', 'type_text', {'text': 'abc'})self.assertEqual(mcp.tool.call_count, 3)diff --git a/libs/cua-driver/hyprland-plugin/tests/production_policy_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_policy_proof.pyindex bb7c3ea0c2..218eb0f941 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_policy_proof.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_policy_proof.py@@ -52,7 +52,7 @@ from production_realapp_proof import (CASES = ('no_manifest_allow', 'resource_allow', 'resource_wrong_pid', 'resource_wrong_window','managed_allow', 'managed_deny')DENIALS = frozenset(('resource_wrong_pid', 'resource_wrong_window', 'managed_deny'))-TOOLS = ['get_window_state', 'press_key', 'hotkey']+TOOLS = ['get_window_state', 'type_text', 'press_key', 'hotkey']MANAGED_ENV = 'CUA_DRIVER_MANAGED_POLICY_FILE'POLICY_ENV = (MANAGED_ENV, 'CUA_DRIVER_POLICY_FILE')# Bound Inkscape observations except before select and move: their groundingdiff --git a/libs/cua-driver/hyprland-plugin/tests/production_policy_proof_test.py b/libs/cua-driver/hyprland-plugin/tests/production_policy_proof_test.pyindex 6db277048e..76056aa04b 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_policy_proof_test.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_policy_proof_test.py@@ -394,7 +394,7 @@ class OrchestrationTests(unittest.TestCase):self.assertEqual(observed['observer'],[default, bounded] if case == 'managed_deny' else [])for index, (name, tool) in enumerate(calls):- if tool not in ('press_key', 'hotkey'):+ if tool not in ('type_text', 'press_key', 'hotkey'):continueobserver = 'observer' if name == 'denied' else nameself.assertEqual(calls[index - 1], (observer, 'get_window_state'))@@ -411,7 +411,7 @@ class OrchestrationTests(unittest.TestCase):self.assertEqual(status, 1)self.assertEqual(report['error']['type'], 'GroundingUnavailable')self.assertEqual([(name, tool) for name, tool in calls- if tool in ('press_key', 'hotkey')], expected_actions)+ if tool in ('type_text', 'press_key', 'hotkey')], expected_actions)self.assertNotIn('response', report['actions'][-1])def test_inkscape_missing_selection_status_refuses_before_right_without_retry(self):@@ -424,7 +424,7 @@ class OrchestrationTests(unittest.TestCase):'type': 'GroundingUnavailable','message': 'cannot prove the single rectangle is selected before Right'})self.assertEqual([(name, tool) for name, tool in calls- if tool in ('press_key', 'hotkey')], [('control', 'hotkey')])+ if tool in ('type_text', 'press_key', 'hotkey')], [('control', 'hotkey')])default = {**report['plan']['target'], 'session': 'policy-proof'}control = next(client for client in clients if client.name == 'control')self.assertEqual(control.snapshots,@@ -440,14 +440,15 @@ class OrchestrationTests(unittest.TestCase):with tempfile.TemporaryDirectory() as temporary:status, report, calls, clients = self.exercise(Path(temporary))self.assertEqual(status, 0, report.get('error'))- self.assertEqual(report['verification']['positive_control']['text'], 'a')+ self.assertEqual(report['verification']['positive_control']['text'], 'abc')self.assertEqual([client.name for client in clients], ['observer', 'denied', 'control'])self.assertTrue(all(client.profile['mode'] == 'unrestricted' for client in clients))- actions = [(name, tool) for name, tool in calls if tool in ('press_key', 'hotkey')]- self.assertEqual(actions, [('denied', 'press_key'), ('control', 'press_key'),+ actions = [(name, tool) for name, tool in calls+ if tool in ('type_text', 'press_key', 'hotkey')]+ self.assertEqual(actions, [('denied', 'type_text'), ('control', 'type_text'),('control', 'press_key'), ('control', 'hotkey')])for index, (name, tool) in enumerate(calls):- if tool not in ('press_key', 'hotkey'):+ if tool not in ('type_text', 'press_key', 'hotkey'):continueobserver = 'observer' if name == 'denied' else nameself.assertEqual(calls[index - 1], (observer, 'get_window_state'))@@ -460,7 +461,7 @@ class OrchestrationTests(unittest.TestCase):status, report, calls, clients = self.exercise(Path(temporary), failure)self.assertEqual(status, 1)self.assertEqual([client.name for client in clients], ['observer', 'denied'])- self.assertEqual(sum(tool == 'press_key' for _, tool in calls), 1)+ self.assertEqual(sum(tool == 'type_text' for _, tool in calls), 1)self.assertIn('after', report['actions'][0])self.assertEqual(calls[-1], ('trace', 'TRACE_STOP'))if failure == 'unknown':@@ -472,7 +473,7 @@ class OrchestrationTests(unittest.TestCase):with tempfile.TemporaryDirectory() as temporary:status, report, calls, clients = self.exercise(Path(temporary), 'foreground_target')self.assertEqual(status, 1)- self.assertFalse(any(tool in ('press_key', 'hotkey') for _, tool in calls))+ self.assertFalse(any(tool in ('type_text', 'press_key', 'hotkey') for _, tool in calls))self.assertIn('target is the primary client', report['error']['message'])diff --git a/libs/cua-driver/hyprland-plugin/tests/production_realapp_proof.py b/libs/cua-driver/hyprland-plugin/tests/production_realapp_proof.pyindex 56130f62e9..b5fd87b813 100644--- a/libs/cua-driver/hyprland-plugin/tests/production_realapp_proof.py+++ b/libs/cua-driver/hyprland-plugin/tests/production_realapp_proof.py@@ -29,12 +29,12 @@ import production_pointer_grounding as pointer_groundingfrom realapp_proof import cleanup_all, rect_position, released_synthetic_input-TOOLS = {'click', 'press_key', 'hotkey', 'scroll', 'drag'}+TOOLS = {'click', 'type_text', 'press_key', 'hotkey', 'scroll', 'drag'}RESERVED = {'pid', 'window_id', 'session', 'delivery_mode'}POINTER_EPISODES = ('clicks', 'scroll-away', 'scroll-back', 'drags', 'save')PRIMARY_LIFETIME_MS = 60000SMOKE_STEPS = {- 'calc': {'insert': ('press_key', {'key': 'a'}),+ 'calc': {'insert': ('type_text', {'text': 'abc'}),'commit': ('press_key', {'key': 'Return'}),'save': ('hotkey', {'keys': ['ctrl', 's']})},'inkscape': {'select': ('hotkey', {'keys': ['ctrl', 'a']}),@@ -294,7 +294,8 @@ def capacity_lane(before, after, tool):lanes = {row[5] for row in synthetic}assert len(lanes) == 1, 'capacity action must exercise exactly one compositor lane'input_kind = {'click': 'pointer_button', 'drag': 'pointer_button',- 'scroll': 'pointer_axis', 'press_key': 'keyboard_key', 'hotkey': 'keyboard_key'}[tool]+ 'scroll': 'pointer_axis', 'type_text': 'keyboard_key',+ 'press_key': 'keyboard_key', 'hotkey': 'keyboard_key'}[tool]completion = 'agent_drag_end' if tool == 'drag' else 'agent_action_end'admissions = [row[0] for row in synthetic if row[2] == 'agent_admitted']inputs = [row[0] for row in synthetic if row[2] == input_kind]diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rsindex 693f6265f7..d835bf1fc7 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs@@ -2549,6 +2549,33 @@ fn isolated_background_routes_do_not_reprobe_availability_before_primary_fallbac}}+#[cfg(test)]+#[test]+fn type_text_routes_isolated_background_before_generic_wayland_refusal() {+ let source = include_str!("impl_.rs");+ let invoke = source+ .rsplit_once("impl Tool for TypeTextTool {")+ .unwrap()+ .1+ .split_once("impl Tool for PressKeyTool {")+ .unwrap()+ .0+ .split_once("async fn invoke")+ .unwrap()+ .1;+ let isolated = invoke+ .find("isolated_hyprland_background(delivery)")+ .expect("type_text must select isolated Hyprland background delivery");+ let generic = invoke+ .find("unavailable_wayland_focused_input_background")+ .expect("type_text must retain the generic Wayland refusal");+ assert!(+ isolated < generic,+ "the plugin route must run before the generic focused-input refusal"+ );+ assert!(invoke.contains("execute_background_text"));+}+#[cfg(test)]#[test]fn isolated_hyprland_refused_partial_and_unknown_outcomes_stay_distinct() {@@ -4067,6 +4094,40 @@ impl Tool for TypeTextTool {}};let delivery = crate::input::delivery::DeliveryMode::from_args(&args);+ if isolated_hyprland_background(delivery)+ && resolved_elem_idx.is_none()+ && args.get("x").is_none()+ && args.get("y").is_none()+ {+ if xid_opt.is_none() {+ return isolated_hyprland_refusal(+ "an exact window_id is required for isolated text",+ );+ }+ match crate::wayland::hyprland_input::text_actions(&text) {+ Ok(actions) if !actions.is_empty() => {}+ Ok(_) => return isolated_hyprland_refusal("background text must not be empty"),+ Err(error) => return isolated_hyprland_refusal(error.to_string()),+ }+ let owner = named_session_cursor_key(&args);+ let (_cancellation, dispatch) =+ match spawn_isolated_hyprland(&args, move |cancellation| {+ crate::wayland::hyprland_input::execute_background_text(+ owner,+ pid,+ xid,+ &text,+ cancellation,+ )+ }) {+ Ok(dispatch) => dispatch,+ Err(refusal) => return refusal,+ };+ return match dispatch.await {+ Ok(result) => isolated_hyprland_result(result),+ Err(error) => isolated_hyprland_task_error(error, false),+ };+ }if let Some(refusal) = unavailable_chromium_background(pid, delivery) {return refusal;}@@ -4110,7 +4171,7 @@ impl Tool for TypeTextTool {}}}- match crate::wayland::hyprland_input::foreground_text_actions(&text) {+ match crate::wayland::hyprland_input::text_actions(&text) {Ok(actions) if !actions.is_empty() => {}Ok(_) => return foreground_hyprland_refusal("foreground text must not be empty"),Err(error) => return foreground_hyprland_refusal(error.to_string()),diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland_input.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland_input.rsindex 7d1056217c..9aa784c2ad 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland_input.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/hyprland_input.rs@@ -53,10 +53,10 @@ fn validate_target_route(target: &Value, route: DeliveryRoute) -> Result<()> {/// Validate the whole string before dispatching any keys. Physical key delivery/// uses the compositor's keyboard layout; these codes describe US ASCII keys.-pub(crate) fn foreground_text_actions(text: &str) -> Result<Vec<Action>> {+pub(crate) fn text_actions(text: &str) -> Result<Vec<Action>> {ensure!(text.len() <= 4096 && text.is_ascii(),- "foreground text requires at most 4096 ASCII bytes"+ "Hyprland text requires at most 4096 ASCII bytes");text.bytes().map(|byte| {@@ -101,7 +101,7 @@ pub(crate) fn foreground_text_actions(text: &str) -> Result<Vec<Action>> {b'*' => (9, true),b'(' => (10, true),b')' => (11, true),- _ => bail!("unsupported foreground text control character"),+ _ => bail!("unsupported Hyprland text control character"),};Ok(Action::TextKey { keycode, shift })})@@ -585,8 +585,7 @@ impl Client {ensure!(self.lane.is_some(), "isolated input lane is not claimed");self.check_route(route)?;ensure!(- route == DeliveryRoute::Foreground- || !matches!(&action, Action::Activate | Action::TextKey { .. }),+ route == DeliveryRoute::Foreground || !matches!(&action, Action::Activate),"action requires foreground input");ensure!(@@ -1053,8 +1052,47 @@ pub(crate) fn execute_foreground_text(text: &str,cancellation: ActionCancellation,) -> Result<Value> {- let actions = foreground_text_actions(text)?;- ensure!(!actions.is_empty(), "foreground text must not be empty");+ execute_text_routed(+ owner,+ pid,+ address,+ text,+ cancellation,+ DeliveryRoute::Foreground,+ )+}++pub(crate) fn execute_background_text(+ owner: Option<String>,+ pid: u32,+ address: u64,+ text: &str,+ cancellation: ActionCancellation,+) -> Result<Value> {+ execute_text_routed(+ owner,+ pid,+ address,+ text,+ cancellation,+ DeliveryRoute::Background,+ )+}++fn execute_text_routed(+ owner: Option<String>,+ pid: u32,+ address: u64,+ text: &str,+ cancellation: ActionCancellation,+ route: DeliveryRoute,+) -> Result<Value> {+ let actions = text_actions(text)?;+ ensure!(+ !actions.is_empty(),+ "{} text must not be empty",+ route.mode()+ );execute_actions_routed(owner,pid,@@ -1062,7 +1100,7 @@ pub(crate) fn execute_foreground_text(actions,None,cancellation,- DeliveryRoute::Foreground,+ route,true,)}@@ -1149,7 +1187,7 @@ fn dispatch_actions_in_slot(attest,);}- execute_text_actions(actions, |action| {+ execute_text_actions(actions, route, |action| {client.execute_routed_with_attest(action, None, route, attest)})},@@ -1158,9 +1196,9 @@ fn dispatch_actions_in_slot(fn execute_text_actions(actions: Vec<Action>,+ route: DeliveryRoute,mut dispatch: impl FnMut(Action) -> Result<Value>,) -> Result<Value> {- let route = DeliveryRoute::Foreground;let mut delivered = 0u32;for action in actions {match dispatch(action) {@@ -1356,9 +1394,11 @@ mod tests {Ok(())},|client| {- execute_text_actions(foreground_text_actions(text).unwrap(), |action| {- client.execute_routed(action, None, DeliveryRoute::Foreground)- })+ execute_text_actions(+ text_actions(text).unwrap(),+ DeliveryRoute::Foreground,+ |action| client.execute_routed(action, None, DeliveryRoute::Foreground),+ )},).unwrap();@@ -1369,6 +1409,55 @@ mod tests {server.join().unwrap();}+ #[test]+ fn text_result_reports_the_selected_delivery_route() {+ for route in [DeliveryRoute::Background, DeliveryRoute::Foreground] {+ let result = execute_text_actions(text_actions("abc").unwrap(), route, |_| {+ Ok(json!({+ "ok": true,+ "effect": "unverifiable",+ "route": route.acknowledgement()+ }))+ })+ .unwrap();+ assert_eq!(result["route"], route.acknowledgement());+ assert_eq!(result["delivery"]["mode"], route.mode());+ assert_eq!(result["delivery"]["delivered_count"], 3);+ }+ }++ #[test]+ fn background_text_binds_each_key_to_the_exact_target() {+ reset_test_attestations();+ let (client, peer) = production_test_client();+ let server = std::thread::spawn(move || {+ for sequence in 1..=3 {+ serve_key_target(&peer, DeliveryRoute::Background, sequence, sequence);+ peer.send(br#"{"ok":true,"effect":"unverifiable","route":"synthetic_events"}"#)+ .unwrap();+ }+ });+ let mut slot = Some(client);+ let result = dispatch_actions_in_slot(+ &mut slot,+ text_actions("aaa").unwrap(),+ None,+ DeliveryRoute::Background,+ true,+ record_test_attestation,+ )+ .unwrap();+ assert_eq!(result["route"], "synthetic_events");+ assert_eq!(+ result["delivery"],+ json!({"mode":"background","delivered_count":3})+ );+ assert_eq!(test_attestations(), 3);+ assert!(slot.is_some());+ drop(slot);+ server.join().unwrap();+ }+#[test]fn failed_call_attestation_discards_reused_slot_without_sending_packets() {let (mut client, peer) = test_connection();@@ -1437,9 +1526,11 @@ mod tests {&mut slot,|_| Ok(()),|client| {- execute_text_actions(foreground_text_actions("abc").unwrap(), |action| {- client.execute_routed(action, None, DeliveryRoute::Foreground)- })+ execute_text_actions(+ text_actions("abc").unwrap(),+ DeliveryRoute::Foreground,+ |action| client.execute_routed(action, None, DeliveryRoute::Foreground),+ )},).unwrap();@@ -1488,9 +1579,11 @@ mod tests {&mut slot,|_| Ok(()),|client| {- execute_text_actions(foreground_text_actions("abc").unwrap(), |action| {- client.execute_routed(action, None, DeliveryRoute::Foreground)- })+ execute_text_actions(+ text_actions("abc").unwrap(),+ DeliveryRoute::Foreground,+ |action| client.execute_routed(action, None, DeliveryRoute::Foreground),+ )},).unwrap();@@ -1782,9 +1875,11 @@ mod tests {0);});- let error = execute_text_actions(foreground_text_actions("abc").unwrap(), |_| {- client.dispatch_routed("KEY synthetic", false, None, DeliveryRoute::Foreground)- })+ let error = execute_text_actions(+ text_actions("abc").unwrap(),+ DeliveryRoute::Foreground,+ |_| client.dispatch_routed("KEY synthetic", false, None, DeliveryRoute::Foreground),+ ).unwrap_err();assert_eq!(error@@ -1811,16 +1906,13 @@ mod tests {}#[test]- fn foreground_text_is_bounded_and_fully_prevalidated() {+ fn hyprland_text_is_bounded_and_fully_prevalidated() {for text in ["valid prefix\u{00e9}", "valid prefix\0", "\r", "\u{007f}"] {- assert!(foreground_text_actions(text).is_err());+ assert!(text_actions(text).is_err());}- assert!(foreground_text_actions(&"a".repeat(4097)).is_err());- assert_eq!(- foreground_text_actions(&"a".repeat(4096)).unwrap().len(),- 4096- );- let actions = foreground_text_actions("Aa!? \t\n").unwrap();+ assert!(text_actions(&"a".repeat(4097)).is_err());+ assert_eq!(text_actions(&"a".repeat(4096)).unwrap().len(), 4096);+ let actions = text_actions("Aa!? \t\n").unwrap();let packets: Vec<_> = actions.into_iter().map(|action| action.packet(1, TOKEN, 1, 1.0, 1.0).unwrap())@@ -1832,7 +1924,7 @@ mod tests {assert_eq!(*packet, format!("KEY 1 {TOKEN} 1 {suffix}"));}assert_eq!(- foreground_text_actions(&(32u8..127).map(char::from).collect::<String>())+ text_actions(&(32u8..127).map(char::from).collect::<String>()).unwrap().len(),95@@ -1843,15 +1935,21 @@ mod tests {fn foreground_text_stops_after_refusal_or_cancellation_without_replay() {for cancel in [false, true] {let mut calls = 0;- let reply = execute_text_actions(foreground_text_actions("abc").unwrap(), |_| {- calls += 1;- match calls {- 1 => Ok(json!({"ok":true})),- 2 if cancel => Err(ActionCancelled.into()),- 2 => Ok(json!({"ok":false,"code":"target_changed","detail":"target_changed"})),- _ => panic!("replayed text after interrupted dispatch"),- }- })+ let reply = execute_text_actions(+ text_actions("abc").unwrap(),+ DeliveryRoute::Foreground,+ |_| {+ calls += 1;+ match calls {+ 1 => Ok(json!({"ok":true})),+ 2 if cancel => Err(ActionCancelled.into()),+ 2 => Ok(+ json!({"ok":false,"code":"target_changed","detail":"target_changed"}),+ ),+ _ => panic!("replayed text after interrupted dispatch"),+ }+ },+ ).unwrap();assert_eq!(calls, 2);assert_eq!(reply["ok"], false);@@ -1867,14 +1965,18 @@ mod tests {#[test]fn foreground_text_unknown_delivery_keeps_only_acknowledged_key_count() {let mut calls = 0;- let error = execute_text_actions(foreground_text_actions("abc").unwrap(), |_| {- calls += 1;- if calls == 1 {- Ok(json!({"ok":true}))- } else {- Err(unknown_dispatch(anyhow::anyhow!("peer closed"), 0))- }- })+ let error = execute_text_actions(+ text_actions("abc").unwrap(),+ DeliveryRoute::Foreground,+ |_| {+ calls += 1;+ if calls == 1 {+ Ok(json!({"ok":true}))+ } else {+ Err(unknown_dispatch(anyhow::anyhow!("peer closed"), 0))+ }+ },+ ).unwrap_err();assert_eq!(calls, 2);assert_eq!(