repartee 0.9.1

A modern terminal IRC client built with Ratatui and Tokio
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
use super::App;

impl App {
    fn e2e_debug_enabled() -> bool {
        std::env::var("REPARTEE_E2E_DEBUG_BUFFER").is_ok_and(|v| {
            let v = v.trim();
            !v.is_empty() && v != "0" && !v.eq_ignore_ascii_case("false")
        })
    }

    fn emit_e2e_debug(&mut self, conn_id: &str, channel: Option<&str>, text: impl Into<String>) {
        if !Self::e2e_debug_enabled() {
            return;
        }
        let text = text.into();
        let buffer_id = channel
            .map(|channel| crate::state::buffer::make_buffer_id(conn_id, channel))
            .filter(|id| self.state.buffers.contains_key(id))
            .or_else(|| {
                self.state
                    .active_buffer()
                    .filter(|buf| buf.connection_id == conn_id)
                    .map(|buf| buf.id.clone())
            })
            .or_else(|| {
                self.state
                    .connections
                    .get(conn_id)
                    .map(|conn| crate::state::buffer::make_buffer_id(conn_id, &conn.label))
            });
        let Some(buffer_id) = buffer_id else { return };
        let id = self.state.next_message_id();
        let event_param = text.clone();
        self.state.add_message(
            &buffer_id,
            crate::state::buffer::Message {
                id,
                timestamp: chrono::Utc::now(),
                message_type: crate::state::buffer::MessageType::Event,
                nick: None,
                nick_mode: None,
                text,
                highlight: false,
                event_key: Some("e2e_info".to_string()),
                event_params: Some(vec![event_param]),
                log_msg_id: None,
                log_ref_id: None,
                tags: None,
            },
        );
    }

    /// Broadcast a `WebEvent` to all connected web clients.
    pub(crate) fn broadcast_web(&self, event: crate::web::protocol::WebEvent) {
        let _ = self.web_broadcaster.send(event);
    }

    /// Stop the web server if running. Aborts the accept loop task and
    /// clears per-session state (sessions, rate limiter, snapshot).
    /// The `web_broadcaster` and `web_cmd_tx/rx` channel survive — they
    /// are owned by `App` and reused across restarts.
    pub(crate) fn stop_web_server(&mut self) {
        if let Some(handle) = self.web_server_handle.take() {
            handle.abort();
            tracing::info!("web server stopped");
            crate::commands::helpers::add_local_event(self, "Web server stopped");
        }
        self.web_sessions = None;
        self.web_rate_limiter = None;
        self.web_state_snapshot = None;
        self.web_active_buffers.clear();
    }

    /// Start the web server (HTTPS + WebSocket). Creates fresh session
    /// store, rate limiter, and state snapshot. Reuses the existing
    /// `web_broadcaster` and `web_cmd_tx` channel.
    ///
    /// Does nothing if `web.enabled` is false or `web.password` is empty.
    pub(crate) async fn start_web_server(&mut self) {
        if !self.config.web.enabled {
            return;
        }
        if self.config.web.password.is_empty() {
            tracing::warn!("web.enabled=true but web.password is empty — set WEB_PASSWORD in .env");
            crate::commands::helpers::add_local_event(
                self,
                "web.enabled=true but web.password is empty — set WEB_PASSWORD in .env",
            );
            return;
        }

        let sessions = std::sync::Arc::new(tokio::sync::Mutex::new(
            crate::web::auth::SessionStore::with_hours(self.config.web.session_hours),
        ));
        let limiter =
            std::sync::Arc::new(tokio::sync::Mutex::new(crate::web::auth::RateLimiter::new()));
        self.web_sessions = Some(std::sync::Arc::clone(&sessions));
        self.web_rate_limiter = Some(std::sync::Arc::clone(&limiter));

        let snapshot = std::sync::Arc::new(std::sync::RwLock::new(
            crate::web::server::WebStateSnapshot {
                buffers: Vec::new(),
                connections: Vec::new(),
                mention_count: 0,
                active_buffer_id: None,
                timestamp_format: self.config.web.timestamp_format.clone(),
            },
        ));
        self.web_state_snapshot = Some(std::sync::Arc::clone(&snapshot));

        let handle = std::sync::Arc::new(crate::web::server::AppHandle {
            broadcaster: std::sync::Arc::clone(&self.web_broadcaster),
            web_cmd_tx: self.web_cmd_tx.clone(),
            password: self.config.web.password.clone(),
            session_store: sessions,
            rate_limiter: limiter,
            web_state_snapshot: Some(snapshot),
        });

        match crate::web::server::start(&self.config.web, handle).await {
            Ok(h) => {
                self.web_server_handle = Some(h);
                tracing::info!(
                    "web frontend at https://{}:{}",
                    self.config.web.bind_address,
                    self.config.web.port
                );
                crate::commands::helpers::add_local_event(
                    self,
                    &format!(
                        "Web server listening on https://{}:{}",
                        self.config.web.bind_address, self.config.web.port
                    ),
                );
            }
            Err(e) => {
                tracing::error!("failed to start web server: {e}");
                crate::commands::helpers::add_local_event(
                    self,
                    &format!("Failed to start web server: {e}"),
                );
            }
        }
    }

    /// Drain pending web events queued during IRC event processing.
    pub(crate) fn drain_pending_web_events(&mut self) {
        let events = std::mem::take(&mut self.state.pending_web_events);
        if !events.is_empty() {
            tracing::debug!(count = events.len(), "draining {} web events", events.len());
        }
        for event in events {
            match &event {
                crate::web::protocol::WebEvent::BufferCreated { buffer } => {
                    tracing::debug!(buffer_id = %buffer.id, "broadcasting BufferCreated");
                }
                crate::web::protocol::WebEvent::BufferClosed { buffer_id } => {
                    tracing::debug!(%buffer_id, "broadcasting BufferClosed");
                }
                crate::web::protocol::WebEvent::ActiveBufferChanged { .. } => continue,
                _ => {}
            }
            if let crate::web::protocol::WebEvent::MentionAlert {
                ref buffer_id,
                ref message,
            } = event
            {
                self.record_mention(buffer_id, message);
            }
            self.broadcast_web(event);
        }
    }

    /// Drain any queued RPE2E CTCP NOTICE sends produced by the E2E
    /// event handlers and ship them via the appropriate connection's IRC
    /// sender. Mirrors `drain_pending_web_events` and runs right after it
    /// inside the IRC event loop so handshake traffic reaches the wire
    /// in the same dispatch turn.
    pub(crate) fn drain_pending_e2e_sends(&mut self) {
        let pending: Vec<crate::state::PendingE2eSend> =
            std::mem::take(&mut self.state.pending_e2e_sends);
        for send in pending {
            let parsed = {
                let trimmed = send
                    .notice_text
                    .strip_prefix('\x01')
                    .unwrap_or(&send.notice_text);
                let inner = trimmed.strip_suffix('\x01').unwrap_or(trimmed);
                crate::e2e::handshake::parse(inner).ok().flatten()
            };
            let debug_line = parsed.as_ref().map(|msg| match msg {
                crate::e2e::handshake::HandshakeMsg::Req(req) => (
                    req.channel.as_str(),
                    format!(
                        "[E2E debug] TX KEYREQ to {} for {}",
                        send.target, req.channel
                    ),
                ),
                crate::e2e::handshake::HandshakeMsg::Rsp(rsp) => (
                    rsp.channel.as_str(),
                    format!(
                        "[E2E debug] TX KEYRSP to {} for {}",
                        send.target, rsp.channel
                    ),
                ),
                crate::e2e::handshake::HandshakeMsg::Rekey(rekey) => (
                    rekey.channel.as_str(),
                    format!(
                        "[E2E debug] TX REKEY to {} for {}",
                        send.target, rekey.channel
                    ),
                ),
            });
            let Some(handle) = self.irc_handles.get(&send.connection_id) else {
                tracing::warn!(
                    connection_id = %send.connection_id,
                    "e2e send dropped: no IRC handle for connection"
                );
                if let Some((channel, line)) = debug_line.as_ref() {
                    self.emit_e2e_debug(
                        &send.connection_id,
                        Some(channel),
                        format!("{line} failed: no IRC handle for connection"),
                    );
                }
                continue;
            };
            if let Err(e) = handle.sender.send_notice(&send.target, &send.notice_text) {
                tracing::warn!(
                    target = %send.target,
                    error = %e,
                    "e2e send_notice failed"
                );
                if let Some((channel, line)) = debug_line.as_ref() {
                    self.emit_e2e_debug(
                        &send.connection_id,
                        Some(channel),
                        format!("{line} failed: {e}"),
                    );
                }
            } else if let Some((channel, line)) = debug_line {
                self.emit_e2e_debug(&send.connection_id, Some(channel), line);
            }
        }
    }

    /// Insert a mention into the `SQLite` mentions table.
    pub(crate) fn record_mention(&self, buffer_id: &str, msg: &crate::web::protocol::WireMessage) {
        let Some(ref storage) = self.storage else {
            return;
        };
        let Ok(db) = storage.db.lock() else {
            return;
        };
        let (network, buffer) = crate::web::snapshot::split_buffer_id(buffer_id);
        let channel = self
            .state
            .buffers
            .get(buffer_id)
            .map_or(buffer, |b| b.name.as_str());
        let nick = msg.nick.as_deref().unwrap_or("");
        let _ = crate::storage::query::insert_mention(
            &db,
            msg.timestamp,
            network,
            buffer,
            channel,
            nick,
            &msg.text,
        );
    }

    /// Dispatch a command received from a web client.
    #[expect(
        clippy::too_many_lines,
        reason = "web command dispatch is intentionally flat and security checks are local"
    )]
    pub(crate) fn handle_web_command(
        &mut self,
        cmd: crate::web::protocol::WebCommand,
        session_id: &str,
    ) {
        use crate::web::protocol::WebCommand;
        use crate::web::snapshot;

        match cmd {
            WebCommand::WebConnect { initial_buffer_id } => {
                if let Some(buffer_id) = initial_buffer_id {
                    self.web_active_buffers
                        .insert(session_id.to_string(), buffer_id);
                }
            }
            WebCommand::SendMessage { buffer_id, text } => {
                self.web_send_message(&buffer_id, &text);
            }
            WebCommand::SwitchBuffer { buffer_id } => {
                self.web_active_buffers
                    .insert(session_id.to_string(), buffer_id.clone());
                let web_id = format!("web-{session_id}");
                if self.shell_mgr.has_web_session(&web_id) {
                    self.force_broadcast_web_shell_screen(&web_id);
                } else if let Some(shell_id) = self
                    .shell_mgr
                    .session_id_for_buffer(&buffer_id)
                    .map(ToString::to_string)
                {
                    self.force_broadcast_shell_screen(&shell_id);
                }
            }
            WebCommand::MarkRead { buffer_id, .. } => {
                self.web_mark_read(&buffer_id);
            }
            WebCommand::FetchMessages {
                buffer_id,
                limit,
                before,
            } => {
                self.web_fetch_messages(&buffer_id, limit, before, session_id);
            }
            WebCommand::FetchNickList { buffer_id } => {
                if let Some(crate::web::protocol::WebEvent::NickList {
                    buffer_id: bid,
                    nicks,
                    ..
                }) = snapshot::build_nick_list(&self.state, &buffer_id)
                {
                    self.broadcast_web(crate::web::protocol::WebEvent::NickList {
                        buffer_id: bid,
                        nicks,
                        session_id: Some(session_id.to_string()),
                    });
                }
            }
            WebCommand::FetchMentions => {
                self.web_fetch_mentions(session_id);
            }
            WebCommand::RunCommand { buffer_id, text } => {
                self.web_run_command(&buffer_id, &text);
            }
            WebCommand::ShellInput { buffer_id, data } => {
                if self.web_active_buffers.get(session_id) != Some(&buffer_id) {
                    tracing::debug!(%session_id, %buffer_id, "ignoring shell input for inactive web buffer");
                    return;
                }
                if !self
                    .state
                    .buffers
                    .get(&buffer_id)
                    .is_some_and(|b| b.buffer_type == crate::state::buffer::BufferType::Shell)
                {
                    tracing::debug!(%session_id, %buffer_id, "ignoring shell input for non-shell buffer");
                    return;
                }
                let web_id = format!("web-{session_id}");
                if let Ok(bytes) =
                    base64::Engine::decode(&base64::engine::general_purpose::STANDARD, &data)
                {
                    self.shell_mgr.write_web(&web_id, &bytes);
                }
            }
            WebCommand::WebDisconnect => {
                self.web_active_buffers.remove(session_id);
                self.shell_mgr.close_web_by_session(session_id);
            }
            WebCommand::ShellResize {
                buffer_id,
                cols,
                rows,
            } => {
                if self.web_active_buffers.get(session_id) != Some(&buffer_id) {
                    tracing::debug!(%session_id, %buffer_id, "ignoring shell resize for inactive web buffer");
                    return;
                }
                if !self
                    .state
                    .buffers
                    .get(&buffer_id)
                    .is_some_and(|b| b.buffer_type == crate::state::buffer::BufferType::Shell)
                {
                    tracing::debug!(%session_id, %buffer_id, "ignoring shell resize for non-shell buffer");
                    return;
                }
                let web_id = format!("web-{session_id}");
                if self.shell_mgr.has_web_session(&web_id) {
                    self.shell_mgr.resize_web(&web_id, cols, rows);
                } else if let Err(e) = self.shell_mgr.open_web(session_id, cols, rows) {
                    tracing::warn!("failed to open web shell: {e}");
                    return;
                }
                self.force_broadcast_web_shell_screen(&web_id);
            }
        }
    }

    /// Execute a command from a web client in the context of a buffer.
    fn web_run_command(&mut self, buffer_id: &str, text: &str) {
        let prior = self.state.active_buffer_id.clone();
        self.set_active_buffer_silent(buffer_id);
        self.handle_submit(text);
        if let Some(id) = prior {
            self.set_active_buffer_silent(&id);
        } else {
            self.state.active_buffer_id = None;
        }
    }

    fn set_active_buffer_silent(&mut self, buffer_id: &str) {
        if !self.state.buffers.contains_key(buffer_id) {
            return;
        }
        self.state.active_buffer_id = Some(buffer_id.to_string());
        if let Some(buf) = self.state.buffers.get_mut(buffer_id) {
            buf.activity = crate::state::buffer::ActivityLevel::None;
            buf.unread_count = 0;
        }
    }

    /// Send a message from a web client to IRC.
    fn web_send_message(&mut self, buffer_id: &str, text: &str) {
        self.web_run_command(buffer_id, text);
    }

    /// Mark a buffer as read from a web client.
    fn web_mark_read(&mut self, buffer_id: &str) {
        if let Some(buf) = self.state.buffers.get_mut(buffer_id) {
            buf.unread_count = 0;
            buf.activity = crate::state::buffer::ActivityLevel::None;
        }
        self.broadcast_web(crate::web::protocol::WebEvent::ActivityChanged {
            buffer_id: buffer_id.to_string(),
            activity: 0,
            unread_count: 0,
        });
    }

    /// Fetch messages for a web client.
    fn web_fetch_messages(
        &self,
        buffer_id: &str,
        limit: u32,
        before: Option<i64>,
        session_id: &str,
    ) {
        if buffer_id == Self::MENTIONS_BUFFER_ID {
            if let Some(buf) = self.state.buffers.get(buffer_id) {
                let capped = limit.min(500) as usize;
                let msgs: Vec<_> = buf
                    .messages
                    .iter()
                    .rev()
                    .take(capped)
                    .rev()
                    .map(crate::web::snapshot::message_to_wire)
                    .collect();
                tracing::debug!(
                    %buffer_id, count = msgs.len(),
                    "web FetchMessages: sending {} in-memory mention messages", msgs.len()
                );
                self.broadcast_web(crate::web::protocol::WebEvent::Messages {
                    buffer_id: buffer_id.to_string(),
                    messages: msgs,
                    has_more: false,
                    session_id: Some(session_id.to_string()),
                });
            }
            return;
        }

        // Initial load (no scroll-back cursor): serve from in-memory buffer.
        // This includes messages that haven't been flushed to DB yet (log writer
        // has a 1s flush interval + batch size of 50).
        if before.is_none()
            && let Some(buf) = self.state.buffers.get(buffer_id)
        {
            let capped = limit.min(500) as usize;
            let msgs: Vec<_> = buf
                .messages
                .iter()
                .rev()
                .take(capped)
                .rev()
                .map(crate::web::snapshot::message_to_wire)
                .collect();
            if !msgs.is_empty() {
                let has_more = buf.messages.len() > capped;
                tracing::debug!(
                    %buffer_id, count = msgs.len(),
                    "web FetchMessages: sending {} in-memory messages", msgs.len()
                );
                self.broadcast_web(crate::web::protocol::WebEvent::Messages {
                    buffer_id: buffer_id.to_string(),
                    messages: msgs,
                    has_more,
                    session_id: Some(session_id.to_string()),
                });
                return;
            }
        }

        // If the in-memory buffer was empty (e.g. brand new buffer or post-reconnect
        // before messages arrive), fall through to DB. Also used for scroll-back.
        let Some(ref storage) = self.storage else {
            tracing::warn!("web FetchMessages: storage not available");
            return;
        };
        let Ok(db) = storage.db.lock() else {
            tracing::warn!("web FetchMessages: failed to lock db");
            return;
        };
        let capped_limit = limit.min(500) as usize;
        let (conn_id, buffer) = crate::web::snapshot::split_buffer_id(buffer_id);
        let network = self
            .state
            .connections
            .get(conn_id)
            .map_or_else(|| conn_id.to_string(), |c| c.label.clone());
        let messages = crate::storage::query::get_messages(
            &db,
            &network,
            buffer,
            before,
            capped_limit + 1,
            storage.encrypt,
            None,
        );
        match messages {
            Ok(mut msgs) => {
                let has_more = msgs.len() > capped_limit;
                msgs.truncate(capped_limit);
                tracing::debug!(
                    %buffer_id, count = msgs.len(), %has_more,
                    "web FetchMessages: sending {} messages", msgs.len()
                );
                let wire: Vec<_> = msgs
                    .iter()
                    .map(crate::web::snapshot::stored_to_wire)
                    .collect();
                self.broadcast_web(crate::web::protocol::WebEvent::Messages {
                    buffer_id: buffer_id.to_string(),
                    messages: wire,
                    has_more,
                    session_id: Some(session_id.to_string()),
                });
            }
            Err(e) => {
                tracing::warn!(%buffer_id, error = %e, "web FetchMessages: query failed");
            }
        }
    }

    /// Fetch unread mentions for a web client.
    fn web_fetch_mentions(&self, session_id: &str) {
        let Some(ref storage) = self.storage else {
            return;
        };
        let Ok(db) = storage.db.lock() else {
            return;
        };
        if let Ok(mentions) = crate::storage::query::get_unread_mentions(&db) {
            let wire: Vec<_> = mentions
                .iter()
                .map(|m| crate::web::protocol::WireMention {
                    id: m.id,
                    timestamp: m.timestamp,
                    buffer_id: format!("{}/{}", m.network, m.buffer),
                    channel: m.channel.clone(),
                    nick: m.nick.clone(),
                    text: m.text.clone(),
                })
                .collect();
            self.broadcast_web(crate::web::protocol::WebEvent::MentionsList {
                mentions: wire,
                session_id: Some(session_id.to_string()),
            });
        }
    }
}