tirea-extension-interaction 0.1.1

Interaction extension for tirea
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
//! Interaction Response Plugin.
//!
//! Handles client responses to pending interactions (approvals/denials).

use super::{INTERACTION_RESPONSE_PLUGIN_ID, RECOVERY_RESUME_TOOL_ID};
use crate::outbox::InteractionOutbox;
use crate::{AGENT_RECOVERY_INTERACTION_ACTION, AGENT_RECOVERY_INTERACTION_PREFIX};
use async_trait::async_trait;
use serde_json::json;
use std::collections::HashMap;
use tirea_contract::event::interaction::{
    FrontendToolInvocation, InvocationOrigin, ResponseRouting,
};
use tirea_contract::plugin::phase::{
    BeforeToolExecuteContext, PluginPhaseContext, RunStartContext,
};
use tirea_contract::plugin::AgentPlugin;
use tirea_contract::runtime::control::{InferenceError, LoopControlState};
use tirea_contract::{Interaction, InteractionResponse};
use tirea_extension_permission::PermissionState;
use tirea_state::{State, TireaError};

/// Plugin that handles interaction responses from client.
///
/// This plugin works with `FrontendToolPlugin` and `PermissionPlugin` to complete
/// the interaction flow:
///
/// 1. A plugin (e.g., PermissionPlugin) creates a pending interaction
/// 2. Agent emits `AgentEvent::Pending` which becomes protocol tool-call events
/// 3. Client responds with a new request containing tool message(s)
/// 4. This plugin checks if the response approves/denies the pending interaction
/// 5. Based on response, tool execution proceeds or is blocked
///
/// # Usage
///
/// ```ignore
/// // Create plugin with approved interaction IDs from client request
/// let approved_ids = request.approved_interaction_ids();
/// let denied_ids = request.denied_interaction_ids();
/// let plugin = InteractionResponsePlugin::new(approved_ids, denied_ids);
///
/// let config = config.with_plugin(Arc::new(plugin));
/// ```
pub(crate) struct InteractionResponsePlugin {
    /// Interaction responses keyed by interaction ID.
    responses: HashMap<String, serde_json::Value>,
}

impl InteractionResponsePlugin {
    /// Create a new plugin with approved and denied interaction IDs.
    pub(crate) fn new(approved_ids: Vec<String>, denied_ids: Vec<String>) -> Self {
        let mut responses = HashMap::new();
        for id in approved_ids {
            responses.insert(id, serde_json::Value::Bool(true));
        }
        for id in denied_ids {
            responses.insert(id, serde_json::Value::Bool(false));
        }
        Self { responses }
    }

    /// Create from explicit interaction response payloads.
    pub(crate) fn from_responses(responses: Vec<InteractionResponse>) -> Self {
        Self {
            responses: responses
                .into_iter()
                .map(|r| (r.interaction_id, r.result))
                .collect(),
        }
    }

    /// Return a raw response payload for an interaction id.
    pub(crate) fn result_for(&self, interaction_id: &str) -> Option<&serde_json::Value> {
        self.responses.get(interaction_id)
    }

    /// Return all configured responses.
    pub(crate) fn responses(&self) -> Vec<InteractionResponse> {
        self.responses
            .iter()
            .map(|(interaction_id, result)| {
                InteractionResponse::new(interaction_id.clone(), result.clone())
            })
            .collect()
    }

    /// Check if an interaction was approved.
    pub(crate) fn is_approved(&self, interaction_id: &str) -> bool {
        self.result_for(interaction_id)
            .map(InteractionResponse::is_approved)
            .unwrap_or(false)
    }

    /// Check if an interaction was denied.
    pub(crate) fn is_denied(&self, interaction_id: &str) -> bool {
        self.result_for(interaction_id)
            .map(InteractionResponse::is_denied)
            .unwrap_or(false)
    }

    /// Check if plugin has any responses to process.
    pub(crate) fn has_responses(&self) -> bool {
        !self.responses.is_empty()
    }

    fn pending_interaction_from_step_thread(step: &impl PluginPhaseContext) -> Option<Interaction> {
        let state = step.snapshot();
        state
            .get(LoopControlState::PATH)
            .and_then(|agent| agent.get("pending_interaction"))
            .cloned()
            .and_then(|v| serde_json::from_value::<Interaction>(v).ok())
    }

    fn persisted_pending_interaction(step: &impl PluginPhaseContext) -> Option<Interaction> {
        Self::pending_interaction_from_step_thread(step).or_else(|| {
            let agent = step.state_of::<LoopControlState>();
            agent.pending_interaction().ok().flatten()
        })
    }

    fn persisted_frontend_invocation(
        step: &impl PluginPhaseContext,
    ) -> Option<FrontendToolInvocation> {
        let state = step.snapshot();
        state
            .get(LoopControlState::PATH)
            .and_then(|lc| lc.get("pending_frontend_invocation"))
            .cloned()
            .and_then(|v| serde_json::from_value::<FrontendToolInvocation>(v).ok())
    }

    fn push_resolution(
        step: &impl PluginPhaseContext,
        interaction_id: String,
        result: serde_json::Value,
    ) -> Result<(), String> {
        let outbox = step.state_of::<InteractionOutbox>();
        outbox
            .interaction_resolutions_push(InteractionResponse::new(interaction_id, result))
            .map_err(|e| format!("failed to persist interaction resolution: {e}"))
    }

    fn queue_replay_call(
        step: &impl PluginPhaseContext,
        call: tirea_contract::thread::ToolCall,
    ) -> Result<(), String> {
        let outbox = step.state_of::<InteractionOutbox>();
        outbox
            .replay_tool_calls_push(call)
            .map_err(|e| format!("failed to persist replay tool call: {e}"))
    }

    fn clear_pending_interaction_state(step: &impl PluginPhaseContext) -> Result<(), String> {
        let state = step.state_of::<LoopControlState>();
        if let Err(err) = state.pending_interaction_none() {
            if !matches!(err, TireaError::PathNotFound { .. }) {
                return Err(format!(
                    "failed to clear loop_control.pending_interaction: {err}"
                ));
            }
        }
        if let Err(err) = state.pending_frontend_invocation_none() {
            if !matches!(err, TireaError::PathNotFound { .. }) {
                return Err(format!(
                    "failed to clear loop_control.pending_frontend_invocation: {err}"
                ));
            }
        }
        Ok(())
    }

    fn report_run_start_error(step: &impl PluginPhaseContext, message: impl Into<String>) {
        let message = message.into();
        tracing::error!(
            plugin = INTERACTION_RESPONSE_PLUGIN_ID,
            error = %message,
            "interaction response run_start handling failed"
        );

        if let Err(err) = Self::clear_pending_interaction_state(step) {
            tracing::error!(
                plugin = INTERACTION_RESPONSE_PLUGIN_ID,
                error = %err,
                "failed to clear pending interaction state after run_start error"
            );
        }

        let state = step.state_of::<LoopControlState>();
        if let Err(err) = state.set_inference_error(Some(InferenceError {
            error_type: "interaction_response_error".to_string(),
            message,
        })) {
            tracing::error!(
                plugin = INTERACTION_RESPONSE_PLUGIN_ID,
                error = %err,
                "failed to persist interaction response error"
            );
        }
    }

    /// During RunStart, detect pending interaction and schedule replay if approved.
    fn on_run_start(&self, step: &mut RunStartContext<'_, '_>) {
        let Some(pending) = Self::persisted_pending_interaction(step) else {
            return;
        };

        // Recovery interaction is not a frontend tool invocation and has its own replay tool.
        if pending.action == AGENT_RECOVERY_INTERACTION_ACTION {
            let pending_id = pending.id.as_str();

            if self.is_denied(pending_id) {
                if let Err(err) = Self::clear_pending_interaction_state(step) {
                    Self::report_run_start_error(step, err);
                    return;
                }
                if let Err(err) = Self::push_resolution(
                    step,
                    pending.id.clone(),
                    self.result_for(pending_id)
                        .cloned()
                        .unwrap_or(serde_json::Value::Bool(false)),
                ) {
                    Self::report_run_start_error(step, err);
                }
                return;
            }

            if !self.is_approved(pending_id) {
                return;
            }

            if let Err(err) = Self::push_resolution(
                step,
                pending.id.clone(),
                self.result_for(pending_id)
                    .cloned()
                    .unwrap_or(serde_json::Value::Bool(true)),
            ) {
                Self::report_run_start_error(step, err);
                return;
            }

            let run_id = pending
                .parameters
                .get("run_id")
                .and_then(|v| v.as_str())
                .map(str::to_string)
                .or_else(|| {
                    pending
                        .id
                        .strip_prefix(AGENT_RECOVERY_INTERACTION_PREFIX)
                        .map(str::to_string)
                });
            let Some(run_id) = run_id else {
                Self::report_run_start_error(
                    step,
                    "missing run_id in recovery interaction payload",
                );
                return;
            };

            let replay_call = tirea_contract::thread::ToolCall::new(
                format!("recovery_resume_{run_id}"),
                RECOVERY_RESUME_TOOL_ID,
                json!({
                    "run_id": run_id,
                    "background": false
                }),
            );
            if let Err(err) = Self::queue_replay_call(step, replay_call) {
                Self::report_run_start_error(step, err);
            }
            return;
        }

        // Frontend tool interactions must use first-class invocation metadata.
        let Some(invocation) = Self::persisted_frontend_invocation(step) else {
            return;
        };

        let pending_id_owned = invocation.call_id.clone();
        let pending_id = pending_id_owned.as_str();

        if self.is_denied(pending_id) {
            if let Err(err) = Self::clear_pending_interaction_state(step) {
                Self::report_run_start_error(step, err);
                return;
            }
            if let Err(err) = Self::push_resolution(
                step,
                pending_id_owned.clone(),
                self.result_for(pending_id)
                    .cloned()
                    .unwrap_or(serde_json::Value::Bool(false)),
            ) {
                Self::report_run_start_error(step, err);
            }
            return;
        }

        let result_payload = self.result_for(pending_id).cloned();
        let is_approved = self.is_approved(pending_id);
        let should_continue_use_as_result = result_payload.is_some()
            && matches!(
                &invocation.routing,
                ResponseRouting::UseAsToolResult | ResponseRouting::PassToLLM
            );
        if !is_approved && !should_continue_use_as_result {
            return;
        }
        if let Err(err) = Self::push_resolution(
            step,
            pending_id_owned.clone(),
            result_payload
                .clone()
                .unwrap_or(serde_json::Value::Bool(true)),
        ) {
            Self::report_run_start_error(step, err);
            return;
        }

        if let Err(err) = self.route_frontend_invocation(step, &invocation, result_payload.as_ref())
        {
            Self::report_run_start_error(step, err);
        }
    }

    /// Route an approved response using the first-class `FrontendToolInvocation` model.
    fn route_frontend_invocation(
        &self,
        step: &impl PluginPhaseContext,
        inv: &FrontendToolInvocation,
        response: Option<&serde_json::Value>,
    ) -> Result<(), String> {
        match &inv.routing {
            ResponseRouting::ReplayOriginalTool => {
                // Queue replay of the original backend tool.
                match &inv.origin {
                    InvocationOrigin::ToolCallIntercepted {
                        backend_call_id,
                        backend_tool_name,
                        backend_arguments,
                    } => {
                        let replay_call = tirea_contract::thread::ToolCall::new(
                            backend_call_id.clone(),
                            backend_tool_name.clone(),
                            backend_arguments.clone(),
                        );
                        let permission = step.state_of::<PermissionState>();
                        let mut approved = permission.approved_calls().ok().unwrap_or_default();
                        approved.insert(backend_call_id.clone(), true);
                        permission
                            .set_approved_calls(approved)
                            .map_err(|e| format!("failed to persist one-shot approval: {e}"))?;
                        Self::queue_replay_call(step, replay_call)?;
                    }
                    InvocationOrigin::PluginInitiated { .. } => {
                        // PluginInitiated with ReplayOriginalTool is unusual but
                        // fallback to replaying the frontend tool itself.
                        let replay_call = tirea_contract::thread::ToolCall::new(
                            inv.call_id.clone(),
                            inv.tool_name.clone(),
                            inv.arguments.clone(),
                        );
                        Self::queue_replay_call(step, replay_call)?;
                    }
                }
            }
            ResponseRouting::UseAsToolResult => {
                // The frontend result is the tool result. Replay the tool call
                // so the result enters LLM message history.
                let replay_call = tirea_contract::thread::ToolCall::new(
                    inv.call_id.clone(),
                    inv.tool_name.clone(),
                    normalize_frontend_tool_result(response, &inv.arguments),
                );
                Self::queue_replay_call(step, replay_call)?;
            }
            ResponseRouting::PassToLLM => {
                // Future: pass the result to LLM as an independent message.
                // For now, fallback to replay.
                let replay_call = tirea_contract::thread::ToolCall::new(
                    inv.call_id.clone(),
                    inv.tool_name.clone(),
                    normalize_frontend_tool_result(response, &inv.arguments),
                );
                Self::queue_replay_call(step, replay_call)?;
            }
        }
        Ok(())
    }
}

fn normalize_frontend_tool_result(
    response: Option<&serde_json::Value>,
    fallback_arguments: &serde_json::Value,
) -> serde_json::Value {
    match response {
        // Backward compatibility: approved/denied channels only carry bool.
        // For use_as_tool_result/pass_to_llm we treat bool as ack and keep original args.
        Some(serde_json::Value::Bool(_)) | None => fallback_arguments.clone(),
        Some(value) => value.clone(),
    }
}

#[async_trait]
impl AgentPlugin for InteractionResponsePlugin {
    fn id(&self) -> &str {
        INTERACTION_RESPONSE_PLUGIN_ID
    }

    async fn run_start(&self, ctx: &mut RunStartContext<'_, '_>) {
        self.on_run_start(ctx);
    }

    async fn before_tool_execute(&self, step: &mut BeforeToolExecuteContext<'_, '_>) {
        // Check if there's a tool context
        let Some(interaction_id) = step.tool_call_id().map(str::to_string) else {
            return;
        };

        // Check both the tool call ID and the frontend invocation call_id.
        // For direct frontend tools, interaction_id == tool.id.
        // For indirect (permission), the frontend invocation has a different call_id.
        let frontend_call_id = Self::persisted_frontend_invocation(step).map(|inv| inv.call_id);

        // The client may respond with either the tool call ID or the frontend call ID.
        let effective_id = if let Some(ref fc_id) = frontend_call_id {
            if self.is_approved(fc_id) || self.is_denied(fc_id) {
                fc_id.clone()
            } else {
                interaction_id.clone()
            }
        } else {
            interaction_id.clone()
        };

        let is_approved = self.is_approved(&effective_id);
        let is_denied = self.is_denied(&effective_id);

        if !is_approved && !is_denied {
            return;
        }

        // Verify that the server actually has a persisted pending interaction whose ID
        // matches the one the client claims to be responding to.  Without this check a
        // malicious client could pre-approve arbitrary tool calls by injecting approved
        // IDs in a fresh request that has no outstanding pending interaction.
        let persisted_id = Self::persisted_pending_interaction(step).map(|i| i.id);

        let id_matches = persisted_id
            .as_deref()
            .is_some_and(|id| id == interaction_id || Some(id) == frontend_call_id.as_deref());

        if !id_matches {
            return;
        }

        if is_denied {
            step.deny("User denied the action".to_string());
            if let Err(err) = Self::clear_pending_interaction_state(step) {
                step.deny(err);
                return;
            }
            let resolved_id = persisted_id.unwrap_or(effective_id);
            if let Err(err) =
                Self::push_resolution(step, resolved_id, serde_json::Value::Bool(false))
            {
                step.deny(err);
            }
        } else if is_approved {
            // Override prior ask/deny state and continue execution.
            step.proceed();
            if let Err(err) = Self::clear_pending_interaction_state(step) {
                step.deny(err);
                return;
            }
            let resolved_id = persisted_id.unwrap_or(effective_id);
            if let Err(err) =
                Self::push_resolution(step, resolved_id, serde_json::Value::Bool(true))
            {
                step.deny(err);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use serde_json::json;
    use std::sync::Arc;
    use tirea_contract::plugin::phase::{
        AfterInferenceContext, AfterToolExecuteContext, BeforeInferenceContext,
        BeforeToolExecuteContext, Phase, RunEndContext, RunStartContext, StepContext,
        StepEndContext, StepStartContext,
    };
    use tirea_contract::plugin::AgentPlugin;
    use tirea_contract::runtime::state_paths::{
        INTERACTION_OUTBOX_STATE_PATH, PERMISSIONS_STATE_PATH,
    };
    use tirea_contract::testing::TestFixture;
    use tirea_contract::thread::{Message, ToolCall};
    use tirea_state::DocCell;

    #[async_trait]
    trait AgentPluginTestDispatch {
        async fn run_phase(&self, phase: Phase, step: &mut StepContext<'_>);
    }

    #[async_trait]
    impl<T> AgentPluginTestDispatch for T
    where
        T: AgentPlugin + ?Sized,
    {
        async fn run_phase(&self, phase: Phase, step: &mut StepContext<'_>) {
            match phase {
                Phase::RunStart => {
                    let mut ctx = RunStartContext::new(step);
                    self.run_start(&mut ctx).await;
                }
                Phase::StepStart => {
                    let mut ctx = StepStartContext::new(step);
                    self.step_start(&mut ctx).await;
                }
                Phase::BeforeInference => {
                    let mut ctx = BeforeInferenceContext::new(step);
                    self.before_inference(&mut ctx).await;
                }
                Phase::AfterInference => {
                    let mut ctx = AfterInferenceContext::new(step);
                    self.after_inference(&mut ctx).await;
                }
                Phase::BeforeToolExecute => {
                    let mut ctx = BeforeToolExecuteContext::new(step);
                    self.before_tool_execute(&mut ctx).await;
                }
                Phase::AfterToolExecute => {
                    let mut ctx = AfterToolExecuteContext::new(step);
                    self.after_tool_execute(&mut ctx).await;
                }
                Phase::StepEnd => {
                    let mut ctx = StepEndContext::new(step);
                    self.step_end(&mut ctx).await;
                }
                Phase::RunEnd => {
                    let mut ctx = RunEndContext::new(step);
                    self.run_end(&mut ctx).await;
                }
            }
        }
    }

    fn replay_calls_from_state(state: &serde_json::Value) -> Vec<ToolCall> {
        state
            .get(INTERACTION_OUTBOX_STATE_PATH)
            .and_then(|agent| agent.get("replay_tool_calls"))
            .cloned()
            .and_then(|v| serde_json::from_value::<Vec<ToolCall>>(v).ok())
            .unwrap_or_default()
    }

    fn interaction_resolutions_from_state(state: &serde_json::Value) -> Vec<InteractionResponse> {
        state
            .get(INTERACTION_OUTBOX_STATE_PATH)
            .and_then(|agent| agent.get("interaction_resolutions"))
            .cloned()
            .and_then(|v| serde_json::from_value::<Vec<InteractionResponse>>(v).ok())
            .unwrap_or_default()
    }

    #[tokio::test]
    async fn run_start_replays_tool_matching_pending_interaction() {
        let state = json!({
            "loop_control": {
                "pending_interaction": {
                    "id": "fc_ask_1",
                    "action": "tool:write_file",
                    "parameters": {
                        "source": "permission"
                    }
                },
                "pending_frontend_invocation": {
                    "call_id": "fc_ask_1",
                    "tool_name": "PermissionConfirm",
                    "arguments": { "tool_name": "write_file", "tool_args": { "path": "b.txt" } },
                    "origin": {
                        "type": "tool_call_intercepted",
                        "backend_call_id": "call_write",
                        "backend_tool_name": "write_file",
                        "backend_arguments": { "path": "b.txt" }
                    },
                    "routing": {
                        "strategy": "replay_original_tool"
                    }
                }
            }
        });
        let fixture = TestFixture {
            doc: DocCell::new(state),
            messages: vec![Arc::new(Message::assistant_with_tool_calls(
                "tools",
                vec![
                    ToolCall::new("call_read", "read_file", json!({"path": "a.txt"})),
                    ToolCall::new("call_write", "write_file", json!({"path": "b.txt"})),
                ],
            ))],
            ..TestFixture::new()
        };
        let plugin = InteractionResponsePlugin::new(vec!["fc_ask_1".to_string()], vec![]);

        let mut step = fixture.step(vec![]);
        plugin.run_phase(Phase::RunStart, &mut step).await;

        let updated = fixture.updated_state();
        let replay_calls = replay_calls_from_state(&updated);
        assert_eq!(replay_calls.len(), 1);
        assert_eq!(replay_calls[0].id, "call_write");
        assert_eq!(replay_calls[0].name, "write_file");

        // One-shot approval should be persisted for the replayed backend call.
        let approved = updated
            .get(PERMISSIONS_STATE_PATH)
            .and_then(|p| p.get("approved_calls"))
            .and_then(|m| m.get("call_write"))
            .and_then(|v| v.as_bool());
        assert!(
            approved == Some(true),
            "approval for replayed call_write should be persisted"
        );
    }

    #[tokio::test]
    async fn run_start_replay_requires_frontend_invocation_channel() {
        let state = json!({
            "loop_control": {
                "pending_interaction": {
                    "id": "call_write",
                    "action": "tool:write_file",
                    "parameters": {
                        "source": "permission",
                        "origin_tool_call": {
                            "id": "call_write",
                            "name": "write_file",
                            "arguments": { "path": "b.txt" }
                        }
                    }
                }
            }
        });
        let fixture = TestFixture {
            doc: DocCell::new(state),
            messages: vec![Arc::new(Message::assistant_with_tool_calls(
                "tools",
                vec![ToolCall::new(
                    "call_write",
                    "write_file",
                    json!({"path": "b.txt"}),
                )],
            ))],
            ..TestFixture::new()
        };
        let plugin = InteractionResponsePlugin::new(vec!["call_write".to_string()], vec![]);

        let mut step = fixture.step(vec![]);
        plugin.run_phase(Phase::RunStart, &mut step).await;

        let updated = fixture.updated_state();
        let replay_after = replay_calls_from_state(&updated);
        assert!(
            replay_after.is_empty(),
            "without pending_frontend_invocation metadata, replay must not happen"
        );
    }

    #[tokio::test]
    async fn run_start_frontend_interaction_replay_works_without_prior_channel() {
        let state = json!({
            "loop_control": {
                "pending_interaction": {
                    "id": "call_copy_1",
                    "action": "tool:copyToClipboard"
                },
                "pending_frontend_invocation": {
                    "call_id": "call_copy_1",
                    "tool_name": "copyToClipboard",
                    "arguments": { "text": "hello" },
                    "origin": {
                        "type": "plugin_initiated",
                        "plugin_id": "agui_frontend_tools"
                    },
                    "routing": {
                        "strategy": "use_as_tool_result"
                    }
                }
            }
        });
        let fixture = TestFixture {
            doc: DocCell::new(state),
            messages: vec![Arc::new(Message::assistant_with_tool_calls(
                "tools",
                vec![
                    ToolCall::new("call_search_1", "search", json!({"query": "x"})),
                    ToolCall::new("call_copy_1", "copyToClipboard", json!({"text": "hello"})),
                ],
            ))],
            ..TestFixture::new()
        };
        let plugin = InteractionResponsePlugin::new(vec!["call_copy_1".to_string()], vec![]);

        let mut step = fixture.step(vec![]);
        plugin.run_phase(Phase::RunStart, &mut step).await;

        let updated = fixture.updated_state();
        let replay_after = replay_calls_from_state(&updated);
        assert_eq!(replay_after.len(), 1);
        assert_eq!(replay_after[0].id, "call_copy_1");
        assert_eq!(replay_after[0].name, "copyToClipboard");
    }

    #[tokio::test]
    async fn run_start_frontend_interaction_replay_without_history_uses_pending_payload() {
        let state = json!({
            "loop_control": {
                "pending_interaction": {
                    "id": "call_copy_1",
                    "action": "tool:copyToClipboard",
                    "parameters": { "text": "hello" }
                },
                "pending_frontend_invocation": {
                    "call_id": "call_copy_1",
                    "tool_name": "copyToClipboard",
                    "arguments": { "text": "hello" },
                    "origin": {
                        "type": "plugin_initiated",
                        "plugin_id": "agui_frontend_tools"
                    },
                    "routing": {
                        "strategy": "use_as_tool_result"
                    }
                }
            }
        });
        let fixture = TestFixture::new_with_state(state);
        let plugin = InteractionResponsePlugin::new(vec!["call_copy_1".to_string()], vec![]);

        let mut step = fixture.step(vec![]);
        plugin.run_phase(Phase::RunStart, &mut step).await;

        let updated = fixture.updated_state();
        let replay_after = replay_calls_from_state(&updated);
        assert_eq!(replay_after.len(), 1);
        assert_eq!(replay_after[0].id, "call_copy_1");
        assert_eq!(replay_after[0].name, "copyToClipboard");
        assert_eq!(replay_after[0].arguments["text"], "hello");
    }

    #[tokio::test]
    async fn run_start_permission_replay_without_history_uses_embedded_tool_call() {
        let state = json!({
            "loop_control": {
                "pending_interaction": {
                    "id": "fc_ask_2",
                    "action": "tool:write_file",
                    "parameters": {
                        "source": "permission"
                    }
                },
                "pending_frontend_invocation": {
                    "call_id": "fc_ask_2",
                    "tool_name": "PermissionConfirm",
                    "arguments": { "tool_name": "write_file", "tool_args": { "path": "a.txt" } },
                    "origin": {
                        "type": "tool_call_intercepted",
                        "backend_call_id": "call_write",
                        "backend_tool_name": "write_file",
                        "backend_arguments": { "path": "a.txt" }
                    },
                    "routing": {
                        "strategy": "replay_original_tool"
                    }
                }
            }
        });
        let fixture = TestFixture::new_with_state(state);
        let plugin = InteractionResponsePlugin::new(vec!["fc_ask_2".to_string()], vec![]);

        let mut step = fixture.step(vec![]);
        plugin.run_phase(Phase::RunStart, &mut step).await;

        let updated = fixture.updated_state();
        let replay_after = replay_calls_from_state(&updated);
        assert_eq!(replay_after.len(), 1);
        assert_eq!(replay_after[0].id, "call_write");
        assert_eq!(replay_after[0].name, "write_file");
        assert_eq!(replay_after[0].arguments["path"], "a.txt");
    }

    #[tokio::test]
    async fn run_start_permission_replay_prefers_origin_tool_call_mapping() {
        let state = json!({
            "loop_control": {
                "pending_interaction": {
                    "id": "fc_ask_3",
                    "action": "tool:write_file",
                    "parameters": {
                        "source": "permission"
                    }
                },
                "pending_frontend_invocation": {
                    "call_id": "fc_ask_3",
                    "tool_name": "PermissionConfirm",
                    "arguments": { "tool_name": "write_file", "tool_args": { "path": "b.txt" } },
                    "origin": {
                        "type": "tool_call_intercepted",
                        "backend_call_id": "call_write",
                        "backend_tool_name": "write_file",
                        "backend_arguments": { "path": "b.txt" }
                    },
                    "routing": {
                        "strategy": "replay_original_tool"
                    }
                }
            }
        });
        let fixture = TestFixture::new_with_state(state);
        let plugin = InteractionResponsePlugin::new(vec!["fc_ask_3".to_string()], vec![]);

        let mut step = fixture.step(vec![]);
        plugin.run_phase(Phase::RunStart, &mut step).await;

        let updated = fixture.updated_state();
        let replay_after = replay_calls_from_state(&updated);
        assert_eq!(replay_after.len(), 1);
        assert_eq!(replay_after[0].id, "call_write");
        assert_eq!(replay_after[0].name, "write_file");
        assert_eq!(replay_after[0].arguments["path"], "b.txt");
    }

    #[tokio::test]
    async fn run_start_routes_via_frontend_invocation_replay_original_tool() {
        let state = json!({
            "loop_control": {
                "pending_interaction": {
                    "id": "call_write",
                    "action": "tool:write_file",
                    "parameters": {}
                },
                "pending_frontend_invocation": {
                    "call_id": "fc_ask_1",
                    "tool_name": "PermissionConfirm",
                    "arguments": { "tool_name": "write_file", "tool_args": { "path": "a.txt" } },
                    "origin": {
                        "type": "tool_call_intercepted",
                        "backend_call_id": "call_write",
                        "backend_tool_name": "write_file",
                        "backend_arguments": { "path": "a.txt" }
                    },
                    "routing": {
                        "strategy": "replay_original_tool"
                    }
                }
            }
        });
        let fixture = TestFixture::new_with_state(state);
        // Client responds with the frontend call_id
        let plugin = InteractionResponsePlugin::new(vec!["fc_ask_1".to_string()], vec![]);

        let mut step = fixture.step(vec![]);
        plugin.run_phase(Phase::RunStart, &mut step).await;

        let updated = fixture.updated_state();
        let replay_calls = replay_calls_from_state(&updated);
        assert_eq!(replay_calls.len(), 1);
        // Should replay the original backend tool, not the frontend tool
        assert_eq!(replay_calls[0].id, "call_write");
        assert_eq!(replay_calls[0].name, "write_file");
        assert_eq!(replay_calls[0].arguments["path"], "a.txt");

        // One-shot approval should be persisted for the replayed backend call.
        let approved = updated
            .get(PERMISSIONS_STATE_PATH)
            .and_then(|p| p.get("approved_calls"))
            .and_then(|m| m.get("call_write"))
            .and_then(|v| v.as_bool());
        assert_eq!(approved, Some(true));
    }

    #[tokio::test]
    async fn run_start_routes_via_frontend_invocation_use_as_tool_result() {
        let state = json!({
            "loop_control": {
                "pending_interaction": {
                    "id": "call_copy",
                    "action": "tool:copyToClipboard",
                    "parameters": { "text": "hello" }
                },
                "pending_frontend_invocation": {
                    "call_id": "call_copy",
                    "tool_name": "copyToClipboard",
                    "arguments": { "text": "hello" },
                    "origin": {
                        "type": "plugin_initiated",
                        "plugin_id": "agui_frontend_tools"
                    },
                    "routing": {
                        "strategy": "use_as_tool_result"
                    }
                }
            }
        });
        let fixture = TestFixture::new_with_state(state);
        let plugin = InteractionResponsePlugin::new(vec!["call_copy".to_string()], vec![]);

        let mut step = fixture.step(vec![]);
        plugin.run_phase(Phase::RunStart, &mut step).await;

        let updated = fixture.updated_state();
        let replay_calls = replay_calls_from_state(&updated);
        assert_eq!(replay_calls.len(), 1);
        assert_eq!(replay_calls[0].id, "call_copy");
        assert_eq!(replay_calls[0].name, "copyToClipboard");
        assert_eq!(replay_calls[0].arguments["text"], "hello");

        // No state patches for UseAsToolResult
        assert!(step.pending_patches.is_empty());
    }

    #[tokio::test]
    async fn run_start_use_as_tool_result_preserves_non_boolean_payload() {
        let state = json!({
            "loop_control": {
                "pending_interaction": {
                    "id": "call_copy",
                    "action": "tool:copyToClipboard",
                    "parameters": { "text": "hello" }
                },
                "pending_frontend_invocation": {
                    "call_id": "call_copy",
                    "tool_name": "copyToClipboard",
                    "arguments": { "text": "hello" },
                    "origin": {
                        "type": "plugin_initiated",
                        "plugin_id": "agui_frontend_tools"
                    },
                    "routing": {
                        "strategy": "use_as_tool_result"
                    }
                }
            }
        });
        let fixture = TestFixture::new_with_state(state);
        let plugin = InteractionResponsePlugin::from_responses(vec![InteractionResponse::new(
            "call_copy",
            json!({
                "ok": true,
                "copied": "hello"
            }),
        )]);

        let mut step = fixture.step(vec![]);
        plugin.run_phase(Phase::RunStart, &mut step).await;

        let updated = fixture.updated_state();
        let replay_calls = replay_calls_from_state(&updated);
        assert_eq!(replay_calls.len(), 1);
        assert_eq!(replay_calls[0].id, "call_copy");
        assert_eq!(replay_calls[0].name, "copyToClipboard");
        assert_eq!(replay_calls[0].arguments["ok"], true);
        assert_eq!(replay_calls[0].arguments["copied"], "hello");

        let resolutions = interaction_resolutions_from_state(&updated);
        assert_eq!(resolutions.len(), 1);
        assert_eq!(resolutions[0].interaction_id, "call_copy");
        assert_eq!(resolutions[0].result["ok"], true);
        assert_eq!(resolutions[0].result["copied"], "hello");
    }

    #[tokio::test]
    async fn run_start_replay_failure_sets_inference_error_and_clears_pending() {
        let state = json!({
            "loop_control": {
                "pending_interaction": {
                    "id": "fc_ask_fail",
                    "action": "tool:write_file",
                    "parameters": {}
                },
                "pending_frontend_invocation": {
                    "call_id": "fc_ask_fail",
                    "tool_name": "PermissionConfirm",
                    "arguments": { "tool_name": "write_file", "tool_args": { "path": "a.txt" } },
                    "origin": {
                        "type": "tool_call_intercepted",
                        "backend_call_id": "call_write",
                        "backend_tool_name": "write_file",
                        "backend_arguments": { "path": "a.txt" }
                    },
                    "routing": {
                        "strategy": "replay_original_tool"
                    }
                }
            },
            "interaction_outbox": {
                "replay_tool_calls": "invalid_type"
            }
        });
        let fixture = TestFixture::new_with_state(state);
        let plugin = InteractionResponsePlugin::new(vec!["fc_ask_fail".to_string()], vec![]);

        let mut step = fixture.step(vec![]);
        plugin.run_phase(Phase::RunStart, &mut step).await;

        let updated = fixture.updated_state();
        assert!(
            updated["loop_control"]["pending_interaction"].is_null(),
            "pending interaction should be cleared on run_start failure"
        );
        assert!(
            updated["loop_control"]["pending_frontend_invocation"].is_null(),
            "pending frontend invocation should be cleared on run_start failure"
        );
        assert_eq!(
            updated["loop_control"]["inference_error"]["type"],
            "interaction_response_error"
        );
        assert!(
            updated["loop_control"]["inference_error"]["message"]
                .as_str()
                .unwrap_or_default()
                .contains("failed to persist replay tool call"),
            "expected queue replay failure message in inference_error"
        );
    }

    #[tokio::test]
    async fn run_start_recovery_approval_schedules_agent_run_replay() {
        let state = json!({
            "loop_control": {
                "pending_interaction": {
                    "id": "agent_recovery_run-1",
                    "action": "recover_agent_run",
                    "parameters": {
                        "run_id": "run-1"
                    }
                }
            }
        });
        let fixture = TestFixture::new_with_state(state);
        let plugin =
            InteractionResponsePlugin::new(vec!["agent_recovery_run-1".to_string()], vec![]);

        let mut step = fixture.step(vec![]);
        plugin.run_phase(Phase::RunStart, &mut step).await;

        let updated = fixture.updated_state();
        let replay_calls = replay_calls_from_state(&updated);
        assert_eq!(replay_calls.len(), 1);
        assert_eq!(replay_calls[0].name, RECOVERY_RESUME_TOOL_ID);
        assert_eq!(replay_calls[0].arguments["run_id"], "run-1");
        assert_eq!(replay_calls[0].arguments["background"], false);
    }

    #[tokio::test]
    async fn run_start_recovery_denial_clears_pending_interaction() {
        let state = json!({
            "loop_control": {
                "pending_interaction": {
                    "id": "agent_recovery_run-1",
                    "action": "recover_agent_run",
                    "parameters": {
                        "run_id": "run-1"
                    }
                }
            }
        });
        let fixture = TestFixture::new_with_state(state);
        let plugin =
            InteractionResponsePlugin::new(vec![], vec!["agent_recovery_run-1".to_string()]);

        let mut step = fixture.step(vec![]);
        plugin.run_phase(Phase::RunStart, &mut step).await;

        assert!(
            fixture.has_changes(),
            "denied recovery must clear pending interaction state"
        );

        let updated = fixture.updated_state();
        let pending = updated
            .get("loop_control")
            .and_then(|a| a.get("pending_interaction"));
        assert!(pending.is_none() || pending == Some(&serde_json::Value::Null));
    }
}