Merge pull request 'feat(tui): per-message outbox delivery state (queued/sending/sent/failed) + N queued footer' (#48) from feat/tui-outbox-state into main
Reviewed-on: #48
This commit is contained in:
commit
cecad2b364
3 changed files with 734 additions and 76 deletions
378
src/tui.rs
378
src/tui.rs
|
|
@ -1,6 +1,7 @@
|
|||
use std::collections::HashMap;
|
||||
use std::io::{self, IsTerminal};
|
||||
use std::sync::{Arc, mpsc};
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
|
||||
use ratatui::layout::{Constraint, Layout, Rect};
|
||||
|
|
@ -11,9 +12,10 @@ use ratatui::{DefaultTerminal, Frame};
|
|||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
use crate::node::Node;
|
||||
use crate::outbox::DEFAULT_MAX_ATTEMPTS;
|
||||
use crate::qr::{self, QrPayload};
|
||||
use crate::sanitize;
|
||||
use crate::store::{Friend, FriendProfile};
|
||||
use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus};
|
||||
|
||||
const C_ACCENT: Color = Color::Rgb(232, 165, 75);
|
||||
const C_TEXT: Color = Color::Rgb(196, 214, 176);
|
||||
|
|
@ -117,6 +119,202 @@ pub fn empty_friend_chat_text() -> &'static str {
|
|||
"no messages\ntype below, Enter sends"
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Delivery state (outbox)
|
||||
//
|
||||
// The outbox is the only source of per-message state: `Queued` / `Sending` /
|
||||
// `Failed` rows are what `Node::outbox_pending` still holds, and a row is
|
||||
// deleted the moment the send crosses the circuit — so an outbound message with
|
||||
// no row is `Sent`. No parallel state model, no new wire prefix.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Longest short-form failure reason shown in a chat row.
|
||||
pub const FAIL_REASON_BUDGET: usize = 24;
|
||||
|
||||
/// Marker glyph for one delivery state. ASCII chrome falls back to `ok` for the
|
||||
/// wordless delivered state; `queued` / `sending` / `failed` already carry their
|
||||
/// word, so their glyph is dropped rather than invented.
|
||||
pub fn delivery_glyph(status: &OutboxStatus) -> &'static str {
|
||||
let ascii = ascii_chrome();
|
||||
match status {
|
||||
OutboxStatus::Sent => {
|
||||
if ascii {
|
||||
"ok"
|
||||
} else {
|
||||
"✓"
|
||||
}
|
||||
}
|
||||
OutboxStatus::Queued => {
|
||||
if ascii {
|
||||
""
|
||||
} else {
|
||||
"◷"
|
||||
}
|
||||
}
|
||||
OutboxStatus::Sending => {
|
||||
if ascii {
|
||||
""
|
||||
} else {
|
||||
"»"
|
||||
}
|
||||
}
|
||||
OutboxStatus::Failed(_) => {
|
||||
if ascii {
|
||||
""
|
||||
} else {
|
||||
"✗"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Next-attempt age for a queued row, from the absolute `next_attempt_at` the
|
||||
/// outbox stores.
|
||||
pub fn retry_in_text(next_in_secs: i64) -> String {
|
||||
if next_in_secs <= 0 {
|
||||
"retry now".to_string()
|
||||
} else if next_in_secs < 60 {
|
||||
format!("retry {next_in_secs}s")
|
||||
} else {
|
||||
format!("retry {}m", (next_in_secs + 59) / 60)
|
||||
}
|
||||
}
|
||||
|
||||
/// Transport failure text, short form: sanitized, tail of the `a: b: c` chain,
|
||||
/// capped at `budget` cells so one peer's error cannot blow out the row.
|
||||
pub fn short_send_reason(why: &str, budget: usize) -> String {
|
||||
let clean = sanitize::display_text(why.as_bytes());
|
||||
let tail = clean.rsplit(": ").next().unwrap_or("").trim();
|
||||
let text = if tail.is_empty() { clean.trim() } else { tail };
|
||||
truncate_chars(text, budget)
|
||||
}
|
||||
|
||||
/// One row's delivery marker, straight from the outbox state.
|
||||
pub fn delivery_tag(status: &OutboxStatus, attempts: u32, next_in_secs: i64) -> String {
|
||||
let glyph = delivery_glyph(status);
|
||||
let body = match status {
|
||||
OutboxStatus::Sent => String::new(),
|
||||
OutboxStatus::Queued => format!(
|
||||
"queued (try {attempts}/{DEFAULT_MAX_ATTEMPTS}, {})",
|
||||
retry_in_text(next_in_secs)
|
||||
),
|
||||
OutboxStatus::Sending => "sending".to_string(),
|
||||
OutboxStatus::Failed(why) => {
|
||||
format!("failed: {}", short_send_reason(why, FAIL_REASON_BUDGET))
|
||||
}
|
||||
};
|
||||
match (glyph.is_empty(), body.is_empty()) {
|
||||
(_, true) => glyph.to_string(),
|
||||
(true, false) => body,
|
||||
(false, false) => format!("{glyph} {body}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Footer summary derived from the outbox rows of the selected friend.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct OutboxSummary {
|
||||
/// `Queued` + `Sending`: rows the worker may still deliver.
|
||||
pub queued: usize,
|
||||
/// Terminal failures — these never retry.
|
||||
pub failed: usize,
|
||||
/// First terminal failure, for the fail-closed footer copy.
|
||||
pub first_error: Option<String>,
|
||||
}
|
||||
|
||||
impl OutboxSummary {
|
||||
/// Footer note, or `None` when nothing is outstanding. Any terminal failure
|
||||
/// keeps a `send failed` statement so the fail-closed copy stays visible.
|
||||
pub fn note(&self) -> Option<String> {
|
||||
let reason = || {
|
||||
short_send_reason(
|
||||
self.first_error.as_deref().unwrap_or("unknown"),
|
||||
FAIL_REASON_BUDGET,
|
||||
)
|
||||
};
|
||||
match (self.queued, self.failed) {
|
||||
(0, 0) => None,
|
||||
(queued, 0) => Some(format!("{queued} queued")),
|
||||
(0, 1) => Some(format!("send failed: {}", reason())),
|
||||
(0, failed) => Some(format!("send failed: {} ({failed} failed)", reason())),
|
||||
(queued, _) => Some(format!("{queued} queued, send failed: {}", reason())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Chat transcript with per-message delivery state, plus the footer summary.
|
||||
///
|
||||
/// Pending rows are matched to messages by body, newest send first: an
|
||||
/// outstanding retry is the most recent send of that text, and the outbox holds
|
||||
/// no message id the UI could join on.
|
||||
pub fn chat_with_delivery(
|
||||
msgs: &[Message],
|
||||
pending: &[OutboxEntry],
|
||||
now: i64,
|
||||
) -> (Vec<String>, OutboxSummary) {
|
||||
let mut summary = OutboxSummary::default();
|
||||
for entry in pending {
|
||||
match &entry.status {
|
||||
OutboxStatus::Failed(why) => {
|
||||
summary.failed += 1;
|
||||
summary.first_error.get_or_insert_with(|| why.clone());
|
||||
}
|
||||
_ => summary.queued += 1,
|
||||
}
|
||||
}
|
||||
if msgs.is_empty() {
|
||||
return (
|
||||
empty_friend_chat_text()
|
||||
.lines()
|
||||
.map(str::to_string)
|
||||
.collect(),
|
||||
summary,
|
||||
);
|
||||
}
|
||||
|
||||
let mut by_body: HashMap<&[u8], Vec<&OutboxEntry>> = HashMap::new();
|
||||
for entry in pending {
|
||||
by_body
|
||||
.entry(entry.body.as_slice())
|
||||
.or_default()
|
||||
.push(entry);
|
||||
}
|
||||
let mut tags: Vec<Option<String>> = vec![None; msgs.len()];
|
||||
for (i, msg) in msgs.iter().enumerate().rev() {
|
||||
if msg.dir != "out" {
|
||||
continue;
|
||||
}
|
||||
if let Some(rows) = by_body.get_mut(msg.plaintext.as_slice())
|
||||
&& let Some(entry) = rows.pop()
|
||||
{
|
||||
tags[i] = Some(delivery_tag(
|
||||
&entry.status,
|
||||
entry.attempts,
|
||||
entry.next_attempt_at - now,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let lines = msgs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, msg)| {
|
||||
let side = if msg.dir == "out" { "you" } else { "them" };
|
||||
let body = sanitize::display_text(&msg.plaintext);
|
||||
let tag = match tags[i].clone() {
|
||||
Some(tag) => tag,
|
||||
None if msg.dir == "out" => delivery_tag(&OutboxStatus::Sent, 0, 0),
|
||||
None => String::new(),
|
||||
};
|
||||
if tag.is_empty() {
|
||||
format!("{side}: {body}")
|
||||
} else {
|
||||
format!("{side}: {body} {tag}")
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
(lines, summary)
|
||||
}
|
||||
|
||||
/// Paste overlay copy. Error keeps the resubmit hint.
|
||||
pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String {
|
||||
let hint = match err {
|
||||
|
|
@ -1515,11 +1713,13 @@ impl App {
|
|||
let (tx, rx) = mpsc::channel();
|
||||
self.status_note = Some("sending".into());
|
||||
std::mem::drop(self.rt.spawn(async move {
|
||||
// send() now reports `Sent`/`Queued`; surfacing `queued` in the
|
||||
// footer is a follow-up card, so this arm keeps today's wording.
|
||||
// `send()` reports `Sent` when the circuit took it and `Queued` when
|
||||
// the peer's onion is unreachable. The footer then reads the real
|
||||
// row count from the outbox, so this note is only the first word.
|
||||
let note = match node.send(&pk, &body).await {
|
||||
Ok(_) => "sent".to_string(),
|
||||
Err(e) => format!("send failed: {e}"),
|
||||
Ok(OutboxStatus::Sent) => "sent".to_string(),
|
||||
Ok(_) => "queued".to_string(),
|
||||
Err(e) => format!("send failed: {}", short_send_reason(&e, FAIL_REASON_BUDGET)),
|
||||
};
|
||||
let _ = tx.send(note);
|
||||
}));
|
||||
|
|
@ -1629,38 +1829,22 @@ impl App {
|
|||
}
|
||||
f.render_stateful_widget(roster, panes[0], &mut roster_state);
|
||||
|
||||
let chat_lines = self.chat_lines();
|
||||
let inner_h = panes[1].height.saturating_sub(2);
|
||||
let nlines = chat_lines.len();
|
||||
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
|
||||
let scroll = self.chat_scroll.min(max_scroll);
|
||||
let overflow = nlines > inner_h as usize && inner_h > 0;
|
||||
let chat_title = {
|
||||
let name = self.friends.get(self.selected).map(|friend| {
|
||||
friend
|
||||
.petname
|
||||
.as_deref()
|
||||
.unwrap_or(&friend.fingerprint)
|
||||
.to_string()
|
||||
});
|
||||
let mut t = match name {
|
||||
Some(n) => format!("chat {n}"),
|
||||
None => "chat".to_string(),
|
||||
};
|
||||
if overflow {
|
||||
let end = (scroll as usize + inner_h as usize).min(nlines);
|
||||
t.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
|
||||
}
|
||||
let mark = if self.focus == Pane::Chat { "> " } else { " " };
|
||||
format!("{mark}{t}")
|
||||
};
|
||||
let chat_text = chat_lines.join("\n");
|
||||
let chat = Paragraph::new(chat_text)
|
||||
.style(style_text())
|
||||
.wrap(Wrap { trim: false })
|
||||
.scroll((scroll, 0))
|
||||
.block(self.pane_block(&chat_title, Pane::Chat));
|
||||
f.render_widget(chat, panes[1]);
|
||||
let (chat_lines, summary) = self.chat_view();
|
||||
let chat_name = self.friends.get(self.selected).map(|friend| {
|
||||
friend
|
||||
.petname
|
||||
.as_deref()
|
||||
.unwrap_or(&friend.fingerprint)
|
||||
.to_string()
|
||||
});
|
||||
draw_chat(
|
||||
f,
|
||||
panes[1],
|
||||
&chat_lines,
|
||||
chat_name.as_deref(),
|
||||
self.focus == Pane::Chat,
|
||||
self.chat_scroll,
|
||||
);
|
||||
|
||||
let mark = if self.focus == Pane::Composer {
|
||||
"> "
|
||||
|
|
@ -1684,62 +1868,108 @@ impl App {
|
|||
cols[3],
|
||||
);
|
||||
|
||||
let footer = self.footer_line(area.width);
|
||||
let footer = self.footer_line(area.width, &summary);
|
||||
f.render_widget(Paragraph::new(footer).style(style_dim()), cols[4]);
|
||||
}
|
||||
|
||||
fn footer_line(&self, width: u16) -> String {
|
||||
fn footer_line(&self, width: u16, summary: &OutboxSummary) -> String {
|
||||
// The outbox is the source of truth while anything is outstanding; the
|
||||
// transient note still covers "sending", "sent file x", "invoice sent".
|
||||
let note = summary.note().or_else(|| self.status_note.clone());
|
||||
status_footer(
|
||||
width,
|
||||
&self.me_fp,
|
||||
&self.me_onion,
|
||||
self.status_note.as_deref(),
|
||||
note.as_deref(),
|
||||
footer_hints(&self.screen),
|
||||
)
|
||||
}
|
||||
|
||||
fn chat_lines(&self) -> Vec<String> {
|
||||
fn chat_view(&self) -> (Vec<String>, OutboxSummary) {
|
||||
let Some(friend) = self.friends.get(self.selected) else {
|
||||
return vec![
|
||||
"no friends yet".into(),
|
||||
"F3 paste an invite to add one".into(),
|
||||
];
|
||||
return (
|
||||
vec![
|
||||
"no friends yet".into(),
|
||||
"F3 paste an invite to add one".into(),
|
||||
],
|
||||
OutboxSummary::default(),
|
||||
);
|
||||
};
|
||||
match self.node.list_messages(&friend.pubkey) {
|
||||
Ok(msgs) if msgs.is_empty() => empty_friend_chat_text()
|
||||
.lines()
|
||||
.map(str::to_string)
|
||||
.collect(),
|
||||
Ok(msgs) => msgs
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let side = if m.dir == "out" { "you" } else { "them" };
|
||||
format!("{side}: {}", sanitize::display_text(&m.plaintext))
|
||||
})
|
||||
.collect(),
|
||||
Err(e) => vec![e],
|
||||
Ok(msgs) => {
|
||||
let pending = self.node.outbox_pending(&friend.pubkey).unwrap_or_default();
|
||||
chat_with_delivery(&msgs, &pending, unix_now_secs())
|
||||
}
|
||||
Err(e) => (vec![e], OutboxSummary::default()),
|
||||
}
|
||||
}
|
||||
|
||||
fn pane_block<'a>(&self, title: &'a str, pane: Pane) -> Block<'a> {
|
||||
let focused = self.focus == pane;
|
||||
let border = if focused {
|
||||
style_accent()
|
||||
} else {
|
||||
style_border()
|
||||
};
|
||||
let title_style = if focused {
|
||||
style_accent().add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
style_dim()
|
||||
};
|
||||
apply_chrome_borders(Block::default())
|
||||
.border_style(border)
|
||||
.title(title)
|
||||
.title_style(title_style)
|
||||
pane_block_for(title, self.focus == pane)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pane chrome without an `App`: focus is accent border + bold title, never
|
||||
/// color alone (the `> ` marks come from the callers).
|
||||
fn pane_block_for(title: &str, focused: bool) -> Block<'_> {
|
||||
let border = if focused {
|
||||
style_accent()
|
||||
} else {
|
||||
style_border()
|
||||
};
|
||||
let title_style = if focused {
|
||||
style_accent().add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
style_dim()
|
||||
};
|
||||
apply_chrome_borders(Block::default())
|
||||
.border_style(border)
|
||||
.title(title)
|
||||
.title_style(title_style)
|
||||
}
|
||||
|
||||
fn unix_now_secs() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Real chat-pane renderer: `App::draw_main` calls this, so width, wrap and
|
||||
/// delivery-marker behaviour are testable without constructing a `Node`.
|
||||
pub fn draw_chat(
|
||||
f: &mut Frame,
|
||||
area: Rect,
|
||||
lines: &[String],
|
||||
name: Option<&str>,
|
||||
focused: bool,
|
||||
scroll: u16,
|
||||
) {
|
||||
let inner_h = area.height.saturating_sub(2);
|
||||
let nlines = lines.len();
|
||||
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
|
||||
let scroll = scroll.min(max_scroll);
|
||||
let overflow = nlines > inner_h as usize && inner_h > 0;
|
||||
let mut title = match name {
|
||||
Some(n) => format!("chat {n}"),
|
||||
None => "chat".to_string(),
|
||||
};
|
||||
if overflow {
|
||||
let end = (scroll as usize + inner_h as usize).min(nlines);
|
||||
title.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
|
||||
}
|
||||
let mark = if focused { "> " } else { " " };
|
||||
let title = format!("{mark}{title}");
|
||||
f.render_widget(
|
||||
Paragraph::new(lines.join("\n"))
|
||||
.style(style_text())
|
||||
.wrap(Wrap { trim: false })
|
||||
.scroll((scroll, 0))
|
||||
.block(pane_block_for(&title, focused)),
|
||||
area,
|
||||
);
|
||||
}
|
||||
|
||||
/// Status bar: never drop a non-empty `status_note`. Always keep `TOR`, `me:`, `? help`.
|
||||
pub fn status_footer(
|
||||
width: u16,
|
||||
|
|
@ -1755,7 +1985,7 @@ pub fn status_footer(
|
|||
let mut note = status_note.unwrap_or("").trim().to_string();
|
||||
if !note.is_empty()
|
||||
&& color_mode() == ColorMode::None
|
||||
&& (note.starts_with("send failed") || note == "fingerprint mismatch")
|
||||
&& (note.contains("send failed") || note == "fingerprint mismatch")
|
||||
&& !note.starts_with("! ")
|
||||
{
|
||||
note = format!("! {note}");
|
||||
|
|
|
|||
Loading…
Reference in a new issue