tidev 0.1.0

A terminal-based AI coding agent
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
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
use anyhow::{Context, Result, anyhow, bail};
use async_trait::async_trait;
use chrono::Utc;
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use tokio::time::{Duration, sleep};
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message as WsMessage};
use uuid::Uuid;

use crate::{
    config::{ActiveModel, AppConfig, AuthStore},
    llm::LlmClient,
    session::{AssistantTurn, Conversation, Message, MessageRole, ToolCall, ToolExecutionResult},
    storage::SessionStore,
    tooling::ToolRegistry,
};

use super::channel::Channel;
use super::commands::{CommandInvocation, format_status_summary, gateway_help_text, parse_command};
use super::qq_client::QQClient;
use super::shared;

pub const GATEWAY_PLATFORM_QQ: &str = "qq";

/// Interactive model selection state for a channel.
#[derive(Debug, Clone)]
enum ModelSelectionState {
    /// Waiting for user to select a provider (1, 2, 3, ...)
    WaitingForProvider,
    /// Waiting for user to select a model (1, 2, 3, ...) for the given provider.
    WaitingForModel { provider_id: String },
}

#[derive(Debug, Serialize, Deserialize)]
struct WsPayload {
    op: u8,
    d: Option<serde_json::Value>,
    s: Option<u32>,
    t: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
struct HelloData {
    heartbeat_interval: u64,
}

#[derive(Debug, Serialize, Deserialize)]
struct ReadyData {
    version: u32,
    session_id: String,
    user: serde_json::Value,
}

/// QQ gateway channel implementation.
pub struct QQChannel {
    pub workspace_root: PathBuf,
    pub config: AppConfig,
    pub auth: AuthStore,
    pub store: SessionStore,
    pub llm: LlmClient,
    pub tools: ToolRegistry,
    pub instruction_prompt: String,
    pub allowlist: HashSet<String>,
    pub client: QQClient,
    pub session_id: Option<String>,
    pub last_seq: Option<u32>,
    /// Message sequence number for Markdown messages.
    pub msg_seq: u32,
    /// Gateway start time for uptime calculation.
    pub start_time: Instant,
    /// Cancellation flags per channel_id for /stop command.
    /// When set to true, the current task will be stopped after current streaming completes.
    cancellation_flags: HashMap<String, Arc<AtomicBool>>,
    /// Interactive model selection state per channel_id.
    /// When a user is in this state, their next message is handled as selection input,
    /// not sent to the agent.
    model_selection_states: HashMap<String, ModelSelectionState>,
    /// Sessions that are currently compacting.
    compacting_sessions: HashSet<Uuid>,
}

impl QQChannel {
    /// Create a new QQ channel.
    pub fn new(
        workspace_root: PathBuf,
        config: AppConfig,
        auth: AuthStore,
        store: SessionStore,
        llm: LlmClient,
        tools: ToolRegistry,
        instruction_prompt: String,
        allowlist: HashSet<String>,
        app_id: String,
        app_secret: String,
        sandbox: bool,
    ) -> Self {
        Self {
            workspace_root,
            config,
            auth,
            store,
            llm,
            tools,
            instruction_prompt,
            allowlist,
            client: QQClient::new(app_id, app_secret, sandbox),
            session_id: None,
            last_seq: None,
            msg_seq: 0,
            start_time: Instant::now(),
            cancellation_flags: HashMap::new(),
            model_selection_states: HashMap::new(),
            compacting_sessions: HashSet::new(),
        }
    }

    /// Send a text message with Markdown format.
    async fn send_markdown(
        &mut self,
        channel_id: &str,
        content: &str,
        msg_id: Option<&str>,
    ) -> Result<()> {
        self.msg_seq += 1;
        self.client
            .send_message_markdown(channel_id, content, msg_id, self.msg_seq)
            .await
    }

    async fn run_loop(&mut self) -> Result<()> {
        loop {
            if let Err(e) = self.connect_and_handle().await {
                crate::log_error!("QQ Gateway connection error: {e}. Retrying in 5s...");
                sleep(Duration::from_secs(5)).await;
            }
        }
    }

    async fn connect_and_handle(&mut self) -> Result<()> {
        let gateway_url = self.client.get_gateway_url().await?;
        let (ws_stream, _) = connect_async(gateway_url.as_str()).await?;
        let (mut write, mut read) = ws_stream.split();

        crate::log_info!("QQ Gateway connected to {}", gateway_url);

        let mut heartbeat_interval = 45000;
        let mut _last_heartbeat_ack = Instant::now();

        // Handle Hello
        if let Some(msg) = read.next().await {
            let msg = msg?;
            if let WsMessage::Text(text) = msg {
                let payload: WsPayload = serde_json::from_str(&text)?;
                if payload.op == 10 {
                    let hello: HelloData = serde_json::from_value(payload.d.unwrap())?;
                    heartbeat_interval = hello.heartbeat_interval;
                    crate::log_info!("QQ Hello received, heartbeat: {}ms", heartbeat_interval);
                }
            }
        }

        // Identify or Resume
        let token = self.client.get_access_token().await?;
        let identify = if let (Some(sid), Some(seq)) = (&self.session_id, self.last_seq) {
            crate::log_info!("QQ Attempting resume, session_id: {}, seq: {}", sid, seq);
            serde_json::json!({
                "op": 6,
                "d": {
                    "token": format!("QQBot {}", token),
                    "session_id": sid,
                    "seq": seq,
                }
            })
        } else {
            crate::log_info!("QQ Attempting identify");
            serde_json::json!({
                "op": 2,
                "d": {
                    "token": format!("QQBot {}", token),
                    "intents": 1 << 30, // GUILD_MESSAGES / AT_MESSAGES
                    "shard": [0, 1],
                }
            })
        };

        write
            .send(WsMessage::Text(identify.to_string().into()))
            .await?;

        let mut heartbeat_timer = tokio::time::interval(Duration::from_millis(heartbeat_interval));

        loop {
            tokio::select! {
                _ = heartbeat_timer.tick() => {
                    let hb = serde_json::json!({
                        "op": 1,
                        "d": self.last_seq
                    });
                    write.send(WsMessage::Text(hb.to_string().into())).await?;
                }
                msg = read.next() => {
                    match msg {
                        Some(Ok(WsMessage::Text(text))) => {
                            let payload: WsPayload = serde_json::from_str(&text)?;
                            if let Some(s) = payload.s {
                                self.last_seq = Some(s);
                            }

                            match payload.op {
                                0 => { // Dispatch
                                    if let Some(t) = payload.t.as_deref() {
                                        match t {
                                            "READY" => {
                                                let ready: ReadyData = serde_json::from_value(payload.d.unwrap())?;
                                                self.session_id = Some(ready.session_id);
                                                crate::log_info!("QQ Ready, session_id: {}", self.session_id.as_ref().unwrap());
                                            }
                                            "AT_MESSAGE_CREATE" | "MESSAGE_CREATE" => {
                                                self.handle_message(payload.d.unwrap()).await?;
                                            }
                                            _ => {}
                                        }
                                    }
                                }
                                11 => { // Heartbeat ACK
                                    _last_heartbeat_ack = Instant::now();
                                }
                                _ => {}
                            }
                        }
                        Some(Ok(WsMessage::Close(_))) | None => {
                            return Err(anyhow!("QQ WebSocket closed"));
                        }
                        _ => {}
                    }
                }
            }
        }
    }

    async fn handle_message(&mut self, data: serde_json::Value) -> Result<()> {
        let channel_id = data["channel_id"]
            .as_str()
            .context("missing channel_id")?
            .to_string();
        let author_id = data["author"]["id"].as_str().context("missing author id")?;
        let msg_id = data["id"]
            .as_str()
            .context("missing message id")?
            .to_string();
        let content = data["content"].as_str().unwrap_or_default().trim();

        if !self.allowlist.contains(author_id) {
            crate::log_info!("QQ Message from unauthorized user: {}", author_id);
            return Ok(());
        }

        // Clean @bot if present (QQ mentions are like <@!123456>)
        let clean_content = if let Some(pos) = content.find(' ') {
            &content[pos + 1..]
        } else {
            content
        };

        crate::log_info!("QQ Message from {}: {}", author_id, clean_content);

        // Check if user is in interactive model selection state.
        // If so, handle selection input instead of normal message processing.
        if let Some(state) = self.model_selection_states.get(&channel_id).cloned() {
            crate::log_info!("Handling model selection input: channel_id={}", channel_id);
            return self
                .handle_model_selection(&channel_id, &msg_id, &state, clean_content)
                .await;
        }

        // Check if this is a slash command
        if let Some(command) = parse_command(clean_content) {
            crate::log_info!("QQ Executing command: /{} {:?}", command.name, command.args);
            let mut active_model = self.config.resolve_active_model_for_gateway(&self.auth)?;
            let chat_key = format!("qq:{}", channel_id);
            let mut conversation = self.load_or_create_conversation(&chat_key, &active_model)?;

            let handled = self
                .handle_command(
                    &channel_id,
                    &msg_id,
                    &chat_key,
                    &mut conversation,
                    &mut active_model,
                    command,
                )
                .await?;

            if handled {
                return Ok(());
            }
        }

        let active_model = self.config.resolve_active_model_for_gateway(&self.auth)?;
        let chat_key = format!("qq:{}", channel_id);

        let mut conversation = self.load_or_create_conversation(&chat_key, &active_model)?;

        let user_message = Message::new(MessageRole::User, clean_content.to_string());
        conversation.push(user_message.clone());
        self.store
            .append_message(conversation.session_id, &user_message)?;

        if conversation.messages.len() == 1 || conversation.title == "Untitled session" {
            conversation.update_title_from_prompt(clean_content);
            self.store
                .update_session_title(conversation.session_id, &conversation.title)?;
        }

        if let Err(error) = self
            .run_agent_with_tools(&channel_id, &msg_id, &mut conversation, &active_model)
            .await
        {
            let error_text = format!("Gateway error: {error}");
            let error_message = Message::new(MessageRole::Error, error_text.clone());
            self.store
                .append_message(conversation.session_id, &error_message)?;
            self.send_markdown(&channel_id, &error_text, Some(&msg_id))
                .await?;
        }

        Ok(())
    }

    fn load_or_create_conversation(
        &self,
        chat_key: &str,
        active_model: &crate::config::ActiveModel,
    ) -> Result<Conversation> {
        if let Some(session_id) = self
            .store
            .load_gateway_chat_session(GATEWAY_PLATFORM_QQ, chat_key)?
            && let Some(record) = self.store.load_session_record(session_id)?
        {
            let messages = self.store.load_messages(session_id)?;
            return Ok(Conversation {
                session_id,
                parent_session_id: record.parent_session_id,
                workspace_root: record.workspace_root,
                provider_id: record.provider_id,
                provider_display_name: record.provider_display_name,
                model_id: record.model_id,
                model_display_name: record.model_display_name,
                title: record.title,
                created_at: record.created_at,
                updated_at: record.updated_at,
                context_summary: record.context_summary,
                context_retained_from: record.context_retained_from,
                messages,
                revert_message_id: None,
            });
        }

        let session_id = Uuid::new_v4();
        let title = "Untitled session".to_string();
        self.store.create_session(
            session_id,
            &self.workspace_root,
            &active_model.provider_id,
            &active_model.provider_display_name,
            &active_model.model_id,
            &active_model.display_name,
            &title,
        )?;
        self.store
            .set_gateway_chat_session(GATEWAY_PLATFORM_QQ, chat_key, session_id)?;

        let now = Utc::now();
        Ok(Conversation {
            session_id,
            parent_session_id: None,
            workspace_root: self.workspace_root.display().to_string(),
            provider_id: active_model.provider_id.clone(),
            provider_display_name: active_model.provider_display_name.clone(),
            model_id: active_model.model_id.clone(),
            model_display_name: active_model.display_name.clone(),
            title,
            created_at: now,
            updated_at: now,
            context_summary: None,
            context_retained_from: 0,
            messages: Vec::new(),
            revert_message_id: None,
        })
    }

    async fn run_agent_with_tools(
        &mut self,
        channel_id: &str,
        msg_id: &str,
        conversation: &mut Conversation,
        active_model: &crate::config::ActiveModel,
    ) -> Result<()> {
        crate::log_info!(
            "Starting QQ agent: channel_id={}, model={}, session={}",
            channel_id,
            active_model.label(),
            conversation.session_id
        );

        let runtime = tokio::runtime::Handle::current();

        for _ in 1..=8 {
            // Check for cancellation at the start of each round
            if self.check_cancellation(channel_id) {
                crate::log_info!("Task cancelled by user: channel_id={}", channel_id);

                // Send cancellation confirmation
                self.send_markdown(channel_id, "🛑 Task stopped.", Some(msg_id))
                    .await?;
                return Ok(());
            }

            let turn = self
                .run_single_streaming_turn(conversation, active_model)
                .await?;

            if turn.tool_calls.is_empty() {
                let final_text = turn.content.trim();
                if !final_text.is_empty() {
                    self.msg_seq += 1;
                    self.client
                        .send_message_markdown(channel_id, final_text, Some(msg_id), self.msg_seq)
                        .await?;
                }

                let mut assistant_message =
                    Message::new(MessageRole::Assistant, turn.content.clone());
                assistant_message.reasoning = turn.reasoning.clone();
                conversation.push(assistant_message.clone());
                self.store
                    .append_message(conversation.session_id, &assistant_message)?;

                return Ok(());
            }

            self.execute_tool_calls(channel_id, msg_id, &runtime, conversation, turn.tool_calls)
                .await?;
        }

        bail!("assistant exceeded maximum tool rounds; aborting to prevent loop")
    }

    async fn run_single_streaming_turn(
        &mut self,
        conversation: &mut Conversation,
        active_model: &crate::config::ActiveModel,
    ) -> Result<AssistantTurn> {
        self.tools.set_active_model(active_model.clone());

        let context_manager = crate::context::ContextManager::from_state(
            conversation.context_summary.clone(),
            conversation.context_retained_from,
        );

        let request_messages = context_manager
            .build_request_messages(conversation, crate::prompts::SessionMode::Build);
        let tool_definitions = self.tools.all_definitions();

        let mut request_model = active_model.clone();
        request_model.system_prompt =
            shared::compose_system_prompt(&active_model.system_prompt, &self.instruction_prompt);

        let turn = self
            .llm_completion_turn(&request_model, request_messages, tool_definitions)
            .await?;

        let mut assistant_message = Message::new(MessageRole::Assistant, turn.content.clone());
        assistant_message.tool_calls = turn.tool_calls.clone();
        assistant_message.reasoning = turn.reasoning.clone();

        conversation.push(assistant_message.clone());
        self.store
            .append_message(conversation.session_id, &assistant_message)?;

        Ok(turn)
    }

    async fn llm_completion_turn(
        &self,
        model: &crate::config::ActiveModel,
        messages: Vec<Message>,
        tools: Vec<crate::tooling::ToolDefinition>,
    ) -> Result<AssistantTurn> {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let session_id = Uuid::new_v4();
        let request_id = 1;

        let client = self.llm.clone();
        let model = model.clone();

        tokio::spawn(async move {
            let thinking_level = model.thinking_level.clone();
            client
                .stream_chat(
                    session_id,
                    request_id,
                    model,
                    messages,
                    tools,
                    tx,
                    thinking_level,
                )
                .await;
        });

        let mut turn = AssistantTurn::default();
        while let Some(event) = rx.recv().await {
            match event {
                crate::session::BackendEvent::Delta { content, .. } => {
                    turn.content.push_str(&content);
                }
                crate::session::BackendEvent::ReasoningDelta { content, .. } => {
                    turn.reasoning.push_str(&content);
                }
                crate::session::BackendEvent::ToolCallUpdated { tool_call, .. } => {
                    if let Some(existing) =
                        turn.tool_calls.iter_mut().find(|tc| tc.id == tool_call.id)
                    {
                        *existing = tool_call;
                    } else {
                        turn.tool_calls.push(tool_call);
                    }
                }
                crate::session::BackendEvent::Failed { error, .. } => {
                    bail!("LLM Error: {}", error);
                }
                crate::session::BackendEvent::Finished {
                    turn: assistant_turn,
                    ..
                } => {
                    turn = assistant_turn;
                    break;
                }
                _ => {}
            }
        }

        Ok(turn)
    }

    async fn execute_tool_calls(
        &mut self,
        channel_id: &str,
        msg_id: &str,
        runtime: &tokio::runtime::Handle,
        conversation: &mut Conversation,
        tool_calls: Vec<ToolCall>,
    ) -> Result<()> {
        for tool_call in tool_calls {
            crate::log_info!("Executing tool: {}", tool_call.name);
            let result =
                self.tools
                    .execute_call(runtime, &self.store, conversation.session_id, &tool_call);

            let execution_result = match result {
                Ok(res) => res,
                Err(error) => ToolExecutionResult::new(format!("Error: {error}")),
            };

            let display_result =
                execution_result.preview_for_storage(Some(tool_call.name.as_str()));
            let output_for_tool_event = display_result.output.clone();

            let tool_message =
                Message::tool_result(&tool_call.id, &tool_call.name, execution_result);
            conversation.push(tool_message.clone());
            self.store
                .append_message(conversation.session_id, &tool_message)?;

            // Send tool result to user
            let tool_result_text = format!(
                "🔧 *{}*\n```\n{}\n```",
                tool_call.name,
                truncate_for_markdown(&output_for_tool_event)
            );
            self.send_markdown(channel_id, &tool_result_text, Some(msg_id))
                .await?;
        }
        Ok(())
    }

    async fn handle_command(
        &mut self,
        channel_id: &str,
        msg_id: &str,
        chat_key: &str,
        conversation: &mut Conversation,
        active_model: &mut ActiveModel,
        command: CommandInvocation,
    ) -> Result<bool> {
        match command.name.as_str() {
            "new" => {
                *conversation = self.rotate_chat_session(chat_key, active_model)?;
                self.send_markdown(channel_id, "Started a fresh session.", Some(msg_id))
                    .await?;
                Ok(true)
            }
            "session" => {
                if let Some(new_model) = self
                    .handle_session_command(
                        channel_id,
                        msg_id,
                        chat_key,
                        conversation,
                        active_model,
                        command.args,
                        None,
                    )
                    .await?
                {
                    *active_model = new_model;
                }
                Ok(true)
            }
            "model" => {
                self.handle_model_command(channel_id, msg_id).await?;
                Ok(true)
            }
            "help" => {
                self.send_markdown(channel_id, &gateway_help_text(), Some(msg_id))
                    .await?;
                Ok(true)
            }
            "status" => {
                self.handle_status_command(channel_id, msg_id, conversation, active_model)
                    .await?;
                Ok(true)
            }
            "stop" => {
                self.handle_stop_command(channel_id, msg_id, channel_id)
                    .await?;
                Ok(true)
            }
            "compact" => {
                self.handle_compact_command(
                    channel_id,
                    msg_id,
                    chat_key,
                    conversation,
                    active_model,
                )
                .await?;
                Ok(true)
            }
            "init" => {
                self.handle_init_command(channel_id, msg_id).await?;
                Ok(true)
            }
            _ => {
                self.send_markdown(
                    channel_id,
                    &format!(
                        "Unknown command: {}\n\n{}",
                        command.name,
                        gateway_help_text()
                    ),
                    Some(msg_id),
                )
                .await?;
                Ok(true)
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    async fn handle_session_command(
        &mut self,
        channel_id: &str,
        msg_id: &str,
        _chat_key: &str,
        conversation: &Conversation,
        active_model: &ActiveModel,
        args: Vec<String>,
        new_active_model: Option<ActiveModel>,
    ) -> Result<Option<ActiveModel>> {
        let updated_model = new_active_model;

        match args.first().map(|s| s.as_str()) {
            None | Some("") => {
                let text = format_session_summary(conversation, active_model);
                self.send_markdown(channel_id, &text, Some(msg_id)).await?;
            }
            _ => {
                self.send_markdown(channel_id, &gateway_help_text(), Some(msg_id))
                    .await?;
            }
        }

        Ok(updated_model)
    }

    /// Handle /model command - start interactive provider/model selection.
    async fn handle_model_command(&mut self, channel_id: &str, msg_id: &str) -> Result<()> {
        // Get available providers (user config + bundled, only those with valid auth)
        let providers = self.get_available_providers();

        if providers.is_empty() {
            self.send_markdown(
                channel_id,
                "No available providers found. Please check your configuration.",
                Some(msg_id),
            )
            .await?;
            return Ok(());
        }

        // Format provider list
        let mut text = String::from("Select a provider (enter number):\n\n");
        for (i, provider) in providers.iter().enumerate() {
            text.push_str(&format!("{}. {}\n", i + 1, provider.1));
        }
        text.push_str("\n(Enter any other number to cancel)");

        self.send_markdown(channel_id, &text, Some(msg_id)).await?;

        // Set state to waiting for provider selection
        self.model_selection_states.insert(
            channel_id.to_string(),
            ModelSelectionState::WaitingForProvider,
        );

        Ok(())
    }

    /// Handle interactive model selection input.
    async fn handle_model_selection(
        &mut self,
        channel_id: &str,
        msg_id: &str,
        state: &ModelSelectionState,
        content: &str,
    ) -> Result<()> {
        // Check if it's a command - cancel selection if so
        if content.starts_with('/') {
            self.model_selection_states.remove(channel_id);
            self.send_markdown(
                channel_id,
                "Selection cancelled. Send /model to try again.",
                Some(msg_id),
            )
            .await?;
            return Ok(());
        }

        match state {
            ModelSelectionState::WaitingForProvider => {
                // Parse provider selection
                let selection: usize = match content.parse() {
                    Ok(n) => n,
                    Err(_) => {
                        self.model_selection_states.remove(channel_id);
                        self.send_markdown(
                            channel_id,
                            "Invalid selection. Selection cancelled. Send /model to try again.",
                            Some(msg_id),
                        )
                        .await?;
                        return Ok(());
                    }
                };

                let providers = self.get_available_providers();
                if selection < 1 || selection > providers.len() {
                    self.model_selection_states.remove(channel_id);
                    self.client
                        .send_message(
                            channel_id,
                            "Selection cancelled. Send /model to try again.",
                            Some(msg_id),
                        )
                        .await?;
                    return Ok(());
                }

                let (provider_id, _provider_name) = &providers[selection - 1];

                // Get models for selected provider
                let models = self.get_models_for_provider(provider_id);
                if models.is_empty() {
                    self.model_selection_states.remove(channel_id);
                    self.send_markdown(
                        channel_id,
                        "No models available for this provider. Selection cancelled.",
                        Some(msg_id),
                    )
                    .await?;
                    return Ok(());
                }

                // Format model list
                let mut text = format!("Select a model for {} (enter number):\n\n", provider_id);
                for (i, model) in models.iter().enumerate() {
                    text.push_str(&format!("{}. {}\n", i + 1, model.1));
                }
                text.push_str("\n(Enter any other number to cancel)");

                self.send_markdown(channel_id, &text, Some(msg_id)).await?;
                // Set state to waiting for model selection
                self.model_selection_states.insert(
                    channel_id.to_string(),
                    ModelSelectionState::WaitingForModel {
                        provider_id: provider_id.clone(),
                    },
                );
            }
            ModelSelectionState::WaitingForModel { provider_id } => {
                // Parse model selection
                let selection: usize = match content.parse() {
                    Ok(n) => n,
                    Err(_) => {
                        self.model_selection_states.remove(channel_id);
                        self.send_markdown(
                            channel_id,
                            "Selection cancelled. Send /model to try again.",
                            Some(msg_id),
                        )
                        .await?;
                        return Ok(());
                    }
                };

                let models = self.get_models_for_provider(provider_id);
                if selection < 1 || selection > models.len() {
                    self.model_selection_states.remove(channel_id);
                    self.send_markdown(
                        channel_id,
                        "Invalid selection. Selection cancelled. Send /model to try again.",
                        Some(msg_id),
                    )
                    .await?;
                    return Ok(());
                }

                let (model_id, _model_name) = &models[selection - 1];

                // Save the model selection
                let chat_key = format!("qq:{}", channel_id);
                self.store.set_gateway_chat_model(
                    GATEWAY_PLATFORM_QQ,
                    &chat_key,
                    provider_id,
                    model_id,
                )?;

                // Clear state
                self.model_selection_states.remove(channel_id);

                // Send success message
                let success_text = format!(
                    "Model switched to {}/{}\n\nSend /model to change again.",
                    provider_id, model_id
                );
                self.send_markdown(channel_id, &success_text, Some(msg_id))
                    .await?;
            }
        }

        Ok(())
    }

    /// Get available providers (user config + bundled) that have valid auth.
    fn get_available_providers(&self) -> Vec<(String, String)> {
        let mut providers = Vec::new();

        // Check user-configured providers
        for (id, config) in &self.config.providers {
            if let Some(auth) = self.auth.providers.get(id)
                && auth.api_key.as_ref().is_some_and(|k| !k.trim().is_empty())
            {
                providers.push((id.clone(), config.display_name.clone()));
            }
        }

        // Check bundled providers
        for (id, config) in &self.config.bundled_providers {
            // Skip if already added from user config
            if self.config.providers.contains_key(id) {
                continue;
            }
            if let Some(auth) = self.auth.providers.get(id)
                && auth.api_key.as_ref().is_some_and(|k| !k.trim().is_empty())
            {
                providers.push((id.clone(), config.display_name.clone()));
            }
        }

        providers
    }

    /// Get models for a specific provider.
    fn get_models_for_provider(&self, provider_id: &str) -> Vec<(String, String)> {
        let mut models = Vec::new();

        // Check user-configured providers first
        if let Some(config) = self.config.providers.get(provider_id) {
            for (id, model_config) in &config.models {
                models.push((id.clone(), model_config.display_name.clone()));
            }
        }

        // Check bundled providers if not found
        if models.is_empty()
            && let Some(config) = self.config.bundled_providers.get(provider_id)
        {
            for (id, model_config) in &config.models {
                models.push((id.clone(), model_config.display_name.clone()));
            }
        }

        models
    }

    fn rotate_chat_session(
        &self,
        chat_key: &str,
        active_model: &ActiveModel,
    ) -> Result<Conversation> {
        let conversation = self.create_gateway_session(active_model)?;
        self.store.set_gateway_chat_session(
            GATEWAY_PLATFORM_QQ,
            chat_key,
            conversation.session_id,
        )?;
        Ok(conversation)
    }

    fn create_gateway_session(&self, active_model: &ActiveModel) -> Result<Conversation> {
        let session_id = Uuid::new_v4();
        let title = "Untitled session".to_string();
        let conversation = Conversation::new(
            session_id,
            self.workspace_root.display().to_string(),
            active_model.provider_id.clone(),
            active_model.provider_display_name.clone(),
            active_model.model_id.clone(),
            active_model.display_name.clone(),
            title,
        );
        self.store.create_session(
            session_id,
            &self.workspace_root,
            &active_model.provider_id,
            &active_model.provider_display_name,
            &active_model.model_id,
            &active_model.display_name,
            &conversation.title,
        )?;
        Ok(conversation)
    }

    /// Handle /status command - show session statistics.
    async fn handle_status_command(
        &mut self,
        channel_id: &str,
        msg_id: &str,
        conversation: &Conversation,
        active_model: &ActiveModel,
    ) -> Result<()> {
        // Count messages by role
        let user_message_count = conversation
            .messages
            .iter()
            .filter(|m| m.role == MessageRole::User)
            .count();
        let assistant_message_count = conversation
            .messages
            .iter()
            .filter(|m| m.role == MessageRole::Assistant)
            .count();

        // Get tool call count from database
        let tool_call_count = self
            .store
            .count_tool_events(conversation.session_id)
            .unwrap_or(0);

        // Get token stats from database
        let token_stats = self
            .store
            .get_session_token_stats(conversation.session_id)
            .unwrap_or(crate::storage::SessionTokenStats {
                input_tokens: 0,
                output_tokens: 0,
            });

        let text = format_status_summary(
            &conversation.session_id.to_string(),
            &conversation.title,
            conversation.messages.len(),
            user_message_count,
            assistant_message_count,
            tool_call_count,
            &active_model.provider_id,
            &active_model.model_id,
            active_model.context_window,
            token_stats.input_tokens,
            token_stats.output_tokens,
            self.start_time,
            None, // Average response time - could be tracked if needed
        );

        self.send_markdown(channel_id, &text, Some(msg_id)).await
    }

    /// Handle /stop command - set cancellation flag for current task.
    async fn handle_stop_command(
        &mut self,
        channel_id: &str,
        msg_id: &str,
        _chat_key: &str,
    ) -> Result<()> {
        // Get or create cancellation flag for this channel
        let flag = self
            .cancellation_flags
            .entry(channel_id.to_string())
            .or_insert_with(|| Arc::new(AtomicBool::new(false)));

        if flag.load(Ordering::SeqCst) {
            // Already stopping
            self.send_markdown(channel_id, "Already stopping...", Some(msg_id))
                .await?;
        } else {
            // Set the cancellation flag
            flag.store(true, Ordering::SeqCst);
            // We'll send confirmation after the task actually stops
            // The actual stopping is handled in run_agent_with_tools
        }
        Ok(())
    }

    /// Check and clear cancellation flag, return true if cancelled.
    fn check_cancellation(&self, channel_id: &str) -> bool {
        if let Some(flag) = self.cancellation_flags.get(channel_id)
            && flag.load(Ordering::SeqCst)
        {
            // Clear the flag
            flag.store(false, Ordering::SeqCst);
            return true;
        }
        false
    }

    /// Handle /compact command - compact session context.
    async fn handle_compact_command(
        &mut self,
        channel_id: &str,
        msg_id: &str,
        _chat_key: &str,
        conversation: &Conversation,
        active_model: &ActiveModel,
    ) -> Result<()> {
        use crate::context::ContextManager;

        let session_id = conversation.session_id;

        // Check if already compacting
        if self.compacting_sessions.contains(&session_id) {
            self.send_markdown(
                channel_id,
                "Already compacting session. Please wait...",
                Some(msg_id),
            )
            .await?;
            return Ok(());
        }

        self.compacting_sessions.insert(session_id);

        self.send_markdown(
            channel_id,
            "Compacting session context... This may take a moment.",
            Some(msg_id),
        )
        .await?;

        // Clone required data for async operation
        let llm = self.llm.clone();
        let store = self.store.clone();
        let session_id_for_compact = session_id;
        let active_model_for_compact = active_model.clone();
        let conversation_for_compact = conversation.clone();

        // Spawn compaction task
        tokio::spawn(async move {
            let mut context_manager = ContextManager::new();

            let result = context_manager
                .compact(
                    &llm,
                    &active_model_for_compact,
                    &conversation_for_compact,
                    true,
                    None,
                )
                .await;

            match result {
                Ok(true) => {
                    let summary = context_manager.summary.clone();
                    let retained_from = context_manager.retained_from;

                    // Save compacted context state
                    if let Some(summary) = &summary {
                        let _ = store.update_session_context_state(
                            session_id_for_compact,
                            Some(summary),
                            retained_from,
                        );
                    }

                    // Send success message
                    let text = format!(
                        "✅ Session context compacted.\n\
                         Messages retained: {}\n\
                         Summary: {}",
                        retained_from,
                        summary.as_deref().unwrap_or("(none)")
                    );
                    let _ = store.append_message(
                        session_id_for_compact,
                        &crate::session::Message::new(crate::session::MessageRole::System, text),
                    );
                }
                Ok(false) => {
                    let text = "â„šī¸ No compaction needed (context already compact)".to_string();
                    let _ = store.append_message(
                        session_id_for_compact,
                        &crate::session::Message::new(crate::session::MessageRole::System, text),
                    );
                }
                Err(e) => {
                    let text = format!("❌ Compaction failed: {}", e);
                    let _ = store.append_message(
                        session_id_for_compact,
                        &crate::session::Message::new(crate::session::MessageRole::System, text),
                    );
                }
            }
        });

        Ok(())
    }

    /// Handle /init command - load init prompt for project analysis.
    async fn handle_init_command(&mut self, channel_id: &str, msg_id: &str) -> Result<()> {
        let init_prompt = crate::prompts::init_command();
        let text = format!(
            "📁 Project Analysis Prompt\n\n\
             Copy and send this prompt to analyze your project:\n\n\
             ```\n{}\n```",
            init_prompt
        );
        self.send_markdown(channel_id, &text, Some(msg_id)).await
    }
}

#[async_trait]
impl Channel for QQChannel {
    fn name(&self) -> &'static str {
        GATEWAY_PLATFORM_QQ
    }

    fn store(&self) -> Option<&SessionStore> {
        Some(&self.store)
    }

    fn run(&mut self) -> Pin<Box<dyn Future<Output = Result<()>> + '_>> {
        Box::pin(async move {
            crate::log_info!("QQ channel ready");
            self.run_loop().await
        })
    }

    fn restore_sessions(&mut self, store: SessionStore) -> Result<usize> {
        let sessions = store.list_gateway_chat_sessions(GATEWAY_PLATFORM_QQ)?;
        let mut count = 0;
        let mut orphans_closed = 0;

        for (chat_key, session_id) in sessions {
            if let Some(_conversation) = store.load_conversation(session_id)? {
                let messages = store.load_messages(session_id)?;

                // Check for orphaned user turn (crash mid-query)
                if let Some(last) = messages.last()
                    && last.role == MessageRole::User
                {
                    // Close orphan with marker to prevent LLM from continuing the old request
                    let marker = Message::new(
                        MessageRole::Assistant,
                        "[Session interrupted — not continuing this request]".to_string(),
                    );
                    store.append_message(session_id, &marker)?;
                    orphans_closed += 1;
                }

                count += 1;
                crate::log_info!(
                    "Restored QQ session: chat_key={}, session_id={}, messages={}",
                    chat_key,
                    session_id,
                    messages.len()
                );
            }
        }

        if count > 0 {
            crate::log_info!("Restored {} QQ session(s) from disk", count);
        }
        if orphans_closed > 0 {
            crate::log_info!(
                "Closed {} orphaned session turn(s) from previous crash",
                orphans_closed
            );
        }

        Ok(count)
    }
}

fn format_session_summary(conversation: &Conversation, active_model: &ActiveModel) -> String {
    format!(
        "Session status\n- session_id: {}\n- title: {}\n- message_count: {}\n- model: {}/{}",
        conversation.session_id,
        conversation.title,
        conversation.messages.len(),
        active_model.provider_id,
        active_model.model_id
    )
}

fn truncate_for_markdown(value: &str) -> String {
    const MAX_CHARS: usize = 500;
    let mut out = String::new();
    for ch in value.chars().take(MAX_CHARS) {
        // Escape backticks to avoid breaking markdown code blocks
        if ch == '`' {
            out.push_str("\\`");
        } else {
            out.push(ch);
        }
    }
    if value.chars().count() > MAX_CHARS {
        out.push_str("\n... (truncated)");
    }
    out
}