Luxe 0.1.3: your sessions on your phone, joinable sessions, and nested AGENTS.md

- luxe remote puts the sessions on your computer in reach of your own phone or tablet over
  Tailscale: write, steer, answer prompts, send photos, browse files, diffs and GitHub, with a
  paired device and your own Tailscale login.
- luxe join lets another program on the same machine join a running session over the RPC protocol.
- An AGENTS.md in a subfolder reaches the model the first time it works there.
- Long sessions stay fast: no stall before each model call, lighter memory, cheaper drawing.
- A session is open in one Luxe at a time, web_search shares results across its phrasings, and a
  grep glob starting with ! excludes.

The CHANGELOG has the full list.
This commit is contained in:
Evan Whittaker
2026-10-20 02:40:13 -05:00
parent 99e30d6d0f
commit d2129a886f
423 changed files with 31666 additions and 1669 deletions

View File

@@ -213,6 +213,11 @@ pub struct App {
pub headless: bool,
/// Whether submit sends `Action::EditResend` instead of `SubmitUserMessage`
edit_resend_mode: bool,
/// Whether this front-end started a turn whose user message the engine hasn't committed yet.
///
/// That message is already on screen, so its commit adopts the copy rather than adding one;
/// a commit with this unset came from a client joined to the session.
own_commit_pending: bool,
/// When an interrupt was sent that the engine has not yet confirmed by ending the turn.
pub(crate) interrupt_sent_at: Option<std::time::Instant>,
/// Whether this session has already been told that nothing is selected.

View File

@@ -4,7 +4,7 @@
//! command behavior stays separate from key precedence.
use super::conversation::first_code_block;
use super::{App, AppState, ConvoBlock};
use super::{App, ConvoBlock};
#[cfg(test)]
use luxe_core::config::Config;
use luxe_core::engine::Action;
@@ -336,8 +336,7 @@ pub(super) fn dispatch_action(app: &mut App, action: UiAction) -> bool {
let question = app.convo[index].block().clone();
app.push_convo(question);
}
app.status.state = AppState::Streaming;
app.status.on_turn_start();
app.begin_own_turn();
true
}
UiAction::Regenerate => {
@@ -349,8 +348,7 @@ pub(super) fn dispatch_action(app: &mut App, action: UiAction) -> bool {
return true;
}
app.drop_transcript_from(index + 1);
app.status.state = AppState::Streaming;
app.status.on_turn_start();
app.begin_own_turn();
true
}
UiAction::EditResend => {

View File

@@ -1,6 +1,7 @@
//! App construction — building an app from its config and the machine it runs on.
use super::*;
use crate::statusline_state::StatuslineState;
impl App {
/// Create a new app with the given engine channel, keymap, and UI config.
@@ -47,8 +48,6 @@ impl App {
let mouse_enabled = config.mouse.unwrap_or(true);
let mut dock = DockState::new(config.dock.mode());
dock.position = config.dock.position();
let statusline_state =
crate::statusline_state::StatuslineState::new(config.statusline.visibility());
// Seed the review's diff presentation from config; `w` and `Ctrl+B` move it at runtime.
let mut guided_review_workspace = GuidedReviewWorkspace::default();
guided_review_workspace.word_wrap = config.diff.word_wrap();
@@ -70,6 +69,7 @@ impl App {
review: ReviewMirror::default(),
streaming: false,
keymap,
statusline_state: StatuslineState::new(config.statusline.visibility()),
config,
mouse_enabled,
hit: std::cell::RefCell::default(),
@@ -82,7 +82,6 @@ impl App {
files: crate::files::FilesTree::default(),
external_seen: std::collections::HashMap::new(),
external_folds: std::collections::HashMap::new(),
statusline_state,
workspace_layout: WorkspaceLayout::Standard,
theme_styles,
themes,
@@ -125,6 +124,7 @@ impl App {
terminal_focused: None,
headless: false, // Will be set by main_loop based on CLI args.
edit_resend_mode: false,
own_commit_pending: false,
interrupt_sent_at: None,
said_to_choose_a_model: false,
never_sent: HashSet::new(),

View File

@@ -5,11 +5,11 @@
//! off to the module that owns its domain.
use super::{App, ConvoBlock};
use luxe_core::config::NotificationEvent;
use luxe_core::event::Event;
mod compaction;
mod github;
mod prompts;
mod review;
mod transcript;
mod turn;
@@ -65,38 +65,34 @@ pub(super) fn reduce(app: &mut App, event: Event) {
Event::LastTurnAvailable { session_id, turn_id } => {
app.review.last_turn = Some((session_id, turn_id));
}
Event::TurnStarted => turn::turn_started(app),
Event::TurnEnded { .. } => turn::turn_ended(app),
Event::PlanWritten { path } => app.plan_written = Some(path),
Event::ReviewStarted { model } => app.push_convo(ConvoBlock::System(format!(
"A reviewer on {model} is reading the uncommitted changes in a fresh context. Its \
findings will show here."
))),
Event::ReviewStarted { model } => {
app.push_convo(ConvoBlock::System(turn::review_started(&model)));
}
Event::ReviewFinished { verdict, findings } => {
app.push_convo(ConvoBlock::System(turn::review_summary(verdict, &findings)));
}
// The running turn took it in: retire the tray row. The transcript copy arrives (or has
// already arrived) as the committed user entry the engine appended for it.
Event::SteeringDelivered { .. } => app.retire_steering(),
// A notice is informational and the turn keeps running, so it lands in the transcript
// without touching streaming/turn state.
// On the dashboard there is no conversation to put it in — and whichever row the reader
// picks loads a session, which replaces the transcript. So it waits.
// A notice leaves the turn running, so it lands in the transcript without touching turn
// state. The dashboard has no conversation to put it in, and whichever row the reader
// picks loads a session that replaces the transcript, so there it waits.
Event::Notice(msg) => match app.dashboard.is_some() {
true => app.startup_notices.push(msg),
false => app.push_convo(ConvoBlock::System(msg)),
},
Event::GuestsChanged(guests) => app.status.guests = guests,
Event::Error(msg) => turn::failed(app, msg),
Event::ToolStarted { name, .. } => turn::tool_started(app, name),
Event::ToolProgress { .. } => {}
// Over before its batch commits, so the clock beside it stops now rather than when the
// last call of the message does
Event::ToolCompleted { .. } => {
app.status.active_tool = None;
app.status.tool_started = None;
}
Event::ToolCompleted { .. } => app.status.tool_finished(),
Event::ToolEnded { call_id, .. } => {
app.status.active_tool = None;
app.status.tool_started = None;
app.status.tool_finished();
if app.pull_request_pushes.remove(&call_id) {
app.pull_request_link_pending = true;
}
@@ -105,7 +101,7 @@ pub(super) fn reduce(app: &mut App, event: Event) {
Event::ContextUsage { used_tokens, context_window } if context_window > 0 => {
app.status.context_window = context_window;
app.status.context_pct =
(used_tokens as f32 / context_window as f32 * 100.0).min(100.0);
crate::statusline::context_percent(used_tokens, context_window);
}
Event::TurnUsage {
prompt_tokens, completion_tokens, cost_usd, cache_read_tokens, ..
@@ -117,35 +113,20 @@ pub(super) fn reduce(app: &mut App, event: Event) {
Event::ContextComposition(report) => app.push_convo(ConvoBlock::Context(report)),
// Compaction rewrites what the model can see and spends a provider call doing it. Saying
// so is the difference between "the agent forgot" and "the conversation was summarized".
Event::CompactionStarted { .. } => compaction::started(app),
Event::CompactionStarted { tokens_before } => compaction::started(app, tokens_before),
Event::CompactionDone { tokens_before, tokens_after } => {
compaction::done(app, tokens_before, tokens_after);
}
Event::CompactionStopped => compaction::ended(app),
Event::CompactionStopped => compaction::stopped(app),
Event::WorkspaceUpdated(snapshot) => workspace_updated(app, *snapshot),
Event::ToolActivityUpdated(activity) => app.apply_tool_activity(*activity),
Event::PermissionRequested { id, tool, summary, always_patterns, .. } => {
// The prompt is a question to the user; nothing above it should still be arriving.
app.reveal_catch_up();
// The turn stops until someone answers, which is the moment most worth hearing about
let body = turn::permission_body(&tool, &summary);
turn::alert(app, NotificationEvent::Permission, &body);
app.overlays.permission = Some(
crate::permission_prompt::PermissionPromptState::new(
id,
tool,
summary,
always_patterns,
)
.opened(app.frame_now()),
);
prompts::permission_requested(app, id, tool, summary, always_patterns);
}
Event::QuestionAsked { id, prompt, options, multi, .. } => {
app.reveal_catch_up();
turn::alert(app, NotificationEvent::Question, &format!("Question: {prompt}"));
app.overlays.question =
Some(crate::question_prompt::QuestionPromptState::new(id, prompt, options, multi));
prompts::question_asked(app, id, prompt, options, multi);
}
Event::PromptClosed { id } => prompts::prompt_closed(app, &id),
Event::GuidedReviewLoading { request_id, .. }
if app.active_guided_review_request.as_ref() != Some(&request_id) =>
{

View File

@@ -3,18 +3,26 @@
//! A summary is one provider call that can take a minute, on request or mid-turn. Without a state
//! of its own the dock showed nothing for `/compact` and the turn's label for an automatic one, and
//! the context reading kept the full figure until the next provider call reported a new one.
//!
//! The transcript says so as it starts, not only once it's done: the row above the composer shows
//! no label, and the statusline that does is hidden while the dock is open, so a minute of summary
//! otherwise looks like a turn that stalled. The line is settled in place when the summary ends.
use super::super::{App, AppState, ConvoBlock};
use luxe_core::usage::format_tokens;
/// The engine began writing a summary.
pub(super) fn started(app: &mut App) {
/// The engine began writing a summary of `tokens_before` of context.
pub(super) fn started(app: &mut App, tokens_before: u64) {
app.status.compacting_mid_turn = matches!(app.status.state, AppState::Streaming);
app.status.state = AppState::Compacting;
let note =
format!("Compacting the conversation — {} of context…", format_tokens(tokens_before));
app.push_convo(ConvoBlock::System(note));
app.status.compaction_note = app.convo.last().map(|item| item.id.clone());
}
/// The summary stands: the dock reads what it left, and the transcript says what happened.
pub(super) fn done(app: &mut App, tokens_before: u64, tokens_after: u64) {
use luxe_core::usage::format_tokens;
ended(app);
if app.status.context_window > 0 {
let used = tokens_after as f32 / app.status.context_window as f32 * 100.0;
@@ -22,19 +30,34 @@ pub(super) fn done(app: &mut App, tokens_before: u64, tokens_after: u64) {
}
// The summary may not have kept a server's tool names, so the next reference sends them
app.mcp_listed.clear();
app.push_convo(ConvoBlock::System(format!(
"Compacted the conversation — {} → {} of context.",
format_tokens(tokens_before),
format_tokens(tokens_after)
)));
let before = format_tokens(tokens_before);
let after = format_tokens(tokens_after);
settle_note(app, format!("Compacted the conversation — {before} → {after} of context."));
}
/// The summary was cancelled or failed; a failure's reason follows as a notice of its own.
pub(super) fn stopped(app: &mut App) {
ended(app);
settle_note(app, "Compaction stopped.".to_string());
}
/// The compaction under way is over, with or without a summary; the turn it interrupted, if any,
/// carries on.
pub(super) fn ended(app: &mut App) {
fn ended(app: &mut App) {
if !matches!(app.status.state, AppState::Compacting) {
return;
}
app.status.state =
if app.status.compacting_mid_turn { AppState::Streaming } else { AppState::Idle };
}
/// Rewrites the line `started` left with how it ended, or adds one when it's gone (a session
/// switched mid-summary, or a host that never said it started).
fn settle_note(app: &mut App, text: String) {
let note = app.status.compaction_note.take();
let item = note.and_then(|id| app.convo.iter_mut().rev().find(|item| item.id == id));
match item {
Some(item) => item.set_block(ConvoBlock::System(text)),
None => app.push_convo(ConvoBlock::System(text)),
}
}

View File

@@ -0,0 +1,54 @@
//! Prompts — the permission and question modals a turn waits on, opened and taken down.
//!
//! A prompt can be answered somewhere else: a phone joined to the session, or any other front-end
//! on the same engine. The engine says when one stops waiting, and the modal goes with it.
use super::super::App;
use luxe_core::config::NotificationEvent;
use luxe_core::permission::PermissionRequestId;
use luxe_core::question::{QuestionOption, QuestionRequestId};
/// Opens the permission prompt the turn is waiting on, and tells the reader.
pub(super) fn permission_requested(
app: &mut App,
id: PermissionRequestId,
tool: String,
summary: String,
always_patterns: Vec<String>,
) {
// The prompt is a question to the user; nothing above it should still be arriving.
app.reveal_catch_up();
// The turn stops until someone answers, which is the moment most worth hearing about
let body = super::turn::permission_body(&tool, &summary);
super::turn::alert(app, NotificationEvent::Permission, &body);
let prompt =
crate::permission_prompt::PermissionPromptState::new(id, tool, summary, always_patterns);
app.overlays.permission = Some(prompt.opened(app.frame_now()));
}
/// Opens the question the turn is waiting on, and tells the reader.
pub(super) fn question_asked(
app: &mut App,
id: QuestionRequestId,
prompt: String,
options: Vec<QuestionOption>,
multi: bool,
) {
app.reveal_catch_up();
super::turn::alert(app, NotificationEvent::Question, &format!("Question: {prompt}"));
app.overlays.question =
Some(crate::question_prompt::QuestionPromptState::new(id, prompt, options, multi));
}
/// Takes down the prompt `id` names, once nothing is waiting on it.
///
/// Only that one: the reader may already be looking at the next prompt, and a question the TUI
/// asks itself (the plan handoff) has an id the engine never closes.
pub(super) fn prompt_closed(app: &mut App, id: &str) {
if app.overlays.permission.as_ref().is_some_and(|prompt| prompt.id.as_str() == id) {
app.overlays.permission = None;
}
if app.overlays.question.as_ref().is_some_and(|prompt| prompt.id.as_str() == id) {
app.overlays.question = None;
}
}

View File

@@ -27,7 +27,14 @@ pub(super) fn message_committed(app: &mut App, session_id: String, entry_id: Str
// The user's own words are never held back — a steer that lands mid-turn has to be
// visible the moment it lands, not when the prose above it finishes arriving.
app.reveal_catch_up();
for (block_index, text) in luxe_core::briefs::readers_words(&msg.content) {
let words = luxe_core::briefs::readers_words(&msg.content);
if std::mem::take(&mut app.own_commit_pending) {
let block_index = words.first().map_or(0, |(index, _)| *index);
if adopt_own_message(app, &session_id, &entry_id, block_index) {
return;
}
}
for (block_index, text) in words {
app.convo.push(ConversationItem::new(
persisted_id(&session_id, &entry_id, block_index),
user_block(text),
@@ -49,7 +56,19 @@ pub(super) fn message_committed(app: &mut App, session_id: String, entry_id: Str
}
}
/// This front-end's own message, on screen since it was sent, takes the id the engine gave it.
///
/// The copy on screen keeps its chips and images, which the committed text doesn't carry.
fn adopt_own_message(app: &mut App, session_id: &str, entry_id: &str, block_index: usize) -> bool {
let Some(index) = app.last_user_message_index() else {
return false;
};
app.convo[index].id = persisted_id(session_id, entry_id, block_index);
true
}
pub(super) fn session_loaded(app: &mut App, session_id: String, messages: Vec<SessionMessage>) {
app.own_commit_pending = false;
app.review.last_turn = None;
app.mcp_listed.clear();
app.worktree_emptied = false;

View File

@@ -62,6 +62,15 @@ pub(super) fn token_delta(app: &mut App, delta: String) {
app.status.state = AppState::Streaming;
}
/// A turn began, maybe one a joined client asked for. One sent from here has been running since
/// Enter, so its clock is left alone.
pub(super) fn turn_started(app: &mut App) {
app.status.state = AppState::Streaming;
if app.status.turn_started.is_none() {
app.status.on_turn_start();
}
}
pub(super) fn turn_ended(app: &mut App) {
end_turn(app, "The turn ended before this call ran");
// Steering the turn ended before taking in stays held. That window is now narrow — the
@@ -111,6 +120,8 @@ pub(super) fn failed(app: &mut App, msg: String) {
fn end_turn(app: &mut App, reason: &str) {
// A load that failed sends no snapshot, and one that never comes must not mute the next real one
app.arrival.owes_snapshot = false;
// A prompt a hook refused never commits, and must not claim the next client's message
app.own_commit_pending = false;
app.interrupt_sent_at = None;
app.streaming = false;
app.streamed_thinking = false;
@@ -281,6 +292,14 @@ pub(super) fn mark_unfinished_tools(app: &mut App, state: ToolActivityState, sum
}
}
/// The transcript line saying a requested review began.
pub(super) fn review_started(model: &str) -> String {
format!(
"A reviewer on {model} is reading the uncommitted changes in a fresh context. Its \
findings will show here."
)
}
/// What a requested review found, as one line of the transcript and the list under it.
pub(super) fn review_summary(
verdict: luxe_core::event::RequestedReviewVerdict,

View File

@@ -233,7 +233,10 @@ fn send_user_turn(
app.never_sent.extend(message);
app.push_convo(ConvoBlock::System("[engine unavailable — channel closed]".to_string()));
app.status.state = AppState::Idle;
} else if starts_new_turn {
return;
}
app.own_commit_pending = true;
if starts_new_turn {
app.review.last_turn = None;
}
}
@@ -241,7 +244,13 @@ fn send_user_turn(
/// Routes a submission made while a turn is running: steer it into the turn, or hold it for one
/// of its own. Either way it is pinned above the composer rather than dropped into the
/// transcript, so the UI never claims a message started work it hasn't started.
fn deliver_mid_turn(app: &mut App, submission: PendingSubmission) {
///
/// A message with images always waits: steering carries text alone, so steering one would deliver
/// its words and drop its images.
fn deliver_mid_turn(app: &mut App, mut submission: PendingSubmission) {
if !submission.images.is_empty() {
submission.delivery = MidTurnDelivery::Queue;
}
if submission.delivery == MidTurnDelivery::Steer {
let content = submission.content.clone();
if !app.send_action(Action::SteerTurn { content }, "steer the turn") {

View File

@@ -65,6 +65,51 @@ async fn a_message_the_engine_never_took_is_marked_never_sent() {
assert!(!marked(|block| matches!(block, ConvoBlock::Image { .. })), "its image is not");
}
/// An app with a turn running, and the actions it sends.
fn mid_turn() -> (App, mpsc::Receiver<Action>) {
let (tx, rx) = mpsc::channel(8);
let config = luxe_core::config::Config::default();
let mut app = App::new(tx, luxe_core::keymap::KeyMap::defaults(), config);
app.status.model = "gpt-5.6".into();
app.status.state = AppState::Streaming;
(app, rx)
}
fn trace_png() -> AttachedImage {
let (data, mime) = ("aW1hZ2U=".into(), "image/png".into());
AttachedImage { data, mime, filename: "trace.png".into(), width: 4, height: 4 }
}
/// A message with an image, sent mid-turn, waits for a turn of its own: steering carries text
/// alone, so steering it would deliver the words and drop the image.
///
/// The break this catches: Enter mid-turn steering a message with a pasted screenshot, which the
/// model never sees, and which leaves the tray when the words are delivered.
#[tokio::test]
async fn a_message_with_an_image_waits_for_its_own_turn() {
let (mut app, mut sent) = mid_turn();
app.editor.prepend_messages([("why does it stall here?".to_string(), vec![trace_png()])]);
submit_prompt(&mut app);
assert!(sent.try_recv().is_err(), "nothing steered the turn");
assert_eq!(app.queued_count(), 1);
assert_eq!(app.pending_submissions[0].images.len(), 1);
}
/// The break this catches: the image check catching every mid-turn message, so plain text no
/// longer steers the running turn.
#[tokio::test]
async fn a_message_without_one_still_steers() {
let (mut app, mut sent) = mid_turn();
app.editor.prepend_messages([("also check the backoff".to_string(), vec![])]);
submit_prompt(&mut app);
assert!(matches!(sent.try_recv(), Ok(Action::SteerTurn { .. })));
assert_eq!(app.queued_count(), 0);
}
/// A draft whose mentions nest still places its chips instead of crashing on submit.
#[test]
fn nested_mention_text_places_chips() {

View File

@@ -16,6 +16,8 @@ pub struct StatusModel {
pub mode: String,
pub git_branch: Option<String>,
pub git_dirty: bool,
/// Who's joined this session from elsewhere, by name, for the dock's SESSION block
pub guests: Vec<String>,
/// Project name, for the bar's left anchor.
pub project: Option<String>,
/// Compact working-directory path (e.g. `~/projects/luxe`) for the optional cwd module.
@@ -26,6 +28,8 @@ pub struct StatusModel {
/// Whether the compaction under way started inside a turn, which carries on once it ends; one
/// asked for with `/compact` returns to idle
pub(crate) compacting_mid_turn: bool,
/// The transcript line saying a summary is being written, rewritten with how it ended
pub(crate) compaction_note: Option<crate::app::ConversationItemId>,
/// Animation frame counter, advanced on every tick while streaming/compacting.
///
/// Monotonic within a turn: every consumer takes it modulo its own frame count, and the
@@ -100,11 +104,13 @@ impl Default for StatusModel {
mode: luxe_core::mode::BUILD.into(),
git_branch: None,
git_dirty: false,
guests: Vec::new(),
project: None,
cwd: None,
active_tool: None,
state: AppState::Idle,
compacting_mid_turn: false,
compaction_note: None,
spinner_frame: 0,
animating: false,
turn_started: None,
@@ -126,6 +132,12 @@ impl Default for StatusModel {
}
impl StatusModel {
/// The tool call in flight is over: no name beside the spinner, no clock on its card.
pub(crate) fn tool_finished(&mut self) {
self.active_tool = None;
self.tool_started = None;
}
/// Advance the animation frame.
///
/// Streaming and compacting are the states with something running, plus whatever a surface has
@@ -296,19 +308,6 @@ impl StatusModel {
.map_or(std::time::Duration::ZERO, |since| now.saturating_duration_since(since))
}
/// Format elapsed time as a string (e.g. "31s", "1m 23s").
///
/// Whole seconds: this counts up while a turn runs, and a tenth of a second is not a figure
/// anyone reads — it is one they notice moving.
pub fn format_elapsed(dur: std::time::Duration) -> String {
let secs = dur.as_secs();
if secs < 60 {
format!("{secs}s")
} else {
format!("{}m {:02}s", secs / 60, secs % 60)
}
}
/// Format token counts as a string (e.g. "↑1.2k ↓340").
pub fn format_tokens(prompt: u64, completion: u64) -> String {
let fmt = |n: u64| -> String {
@@ -357,7 +356,7 @@ impl StatusModel {
spans.push(Span::raw(state));
if let Some(dur) = self.elapsed(now) {
spans.push(Span::raw(" "));
spans.push(Span::raw(Self::format_elapsed(dur)));
spans.push(Span::raw(crate::statusline::format_elapsed_compact(dur)));
}
if self.prompt_tokens > 0 || self.completion_tokens > 0 {
spans.push(Span::raw(" "));

View File

@@ -18,6 +18,14 @@ impl App {
.count()
}
/// A turn this front-end asked for is under way, re-sending a message already on screen, so
/// its commit adopts that copy rather than adding a second.
pub(crate) fn begin_own_turn(&mut self) {
self.own_commit_pending = true;
self.status.state = AppState::Streaming;
self.status.on_turn_start();
}
/// Records a submission that could not be delivered at all, so it still shows up in the
/// transcript instead of vanishing along with the failure.
pub fn record_unsent_submission(&mut self, submission: PendingSubmission) {
@@ -132,6 +140,7 @@ impl App {
// It is a real turn now, so it reads as one: the message joins the transcript ahead of
// the output it is about to produce.
self.land_submission(message, false);
self.own_commit_pending = true;
self.review.last_turn = None;
true
}

View File

@@ -4,10 +4,12 @@ use luxe_core::engine::ReviewEdit;
mod composer;
mod dashboard;
mod github;
mod joined;
mod mentions;
mod modes;
mod notify;
mod pickers;
mod prompts;
mod replay;
mod review;
mod review_send;

View File

@@ -0,0 +1,121 @@
//! Joined clients: messages sent here and from a client joined to the same session.
use super::*;
use luxe_core::message::Message;
use luxe_core::session::EntryId;
/// Who's joined, as the shared session reports it, is what the status holds, replaced whole each
/// time, and it adds nothing to the transcript.
///
/// The break this catches: the dock's list never updated, kept growing as phones reconnect, or a
/// join written into the transcript after all.
#[test]
fn whos_joined_is_held_for_the_dock_and_not_written_down() {
let (mut app, _rx) = app_in_session();
let before = app.convo.len();
app.update(Msg::Engine(Event::GuestsChanged(vec!["iPhone".into()])));
app.update(Msg::Engine(Event::GuestsChanged(vec!["iPad".into()])));
assert_eq!(app.status.guests, ["iPad"]);
assert_eq!(app.convo.len(), before);
}
fn app_in_session() -> (App, mpsc::Receiver<Action>) {
let (tx, rx) = mpsc::channel(8);
let config = luxe_core::config::Config::default();
let mut app = App::new(tx, luxe_core::keymap::KeyMap::defaults(), config);
app.status.model = "gpt-5.6".into();
app.update(Msg::Engine(Event::SessionLoaded { session_id: "s".into(), messages: Vec::new() }));
(app, rx)
}
fn send(app: &mut App, text: &str) {
app.editor.insert_text(text);
app.submit_prompt();
}
fn committed(app: &mut App, entry: &str, text: &str) {
let message = Message::user(text);
let entry_id = EntryId(entry.into());
app.update(Msg::Engine(Event::MessageCommitted { session_id: "s".into(), entry_id, message }));
}
fn user_messages(app: &App) -> Vec<(&ConversationItemId, &str)> {
app.convo.iter().filter_map(user_message).collect()
}
fn user_message(item: &ConversationItem) -> Option<(&ConversationItemId, &str)> {
match item.block() {
ConvoBlock::User { text, .. } => Some((&item.id, text.as_str())),
_ => None,
}
}
/// A message sent here is on screen once, and takes the id of the entry the engine saved.
///
/// The break this catches: landing every committed user message, so each one you type shows
/// twice; or leaving the copy's id provisional, so copy and expand can't find it in the session.
#[test]
fn a_message_sent_here_is_adopted_not_repeated() {
let (mut app, _engine) = app_in_session();
send(&mut app, "explain the stall");
committed(&mut app, "entry-1", "explain the stall");
let saved = ConversationItemId::Persisted {
session_id: "s".into(),
entry_id: "entry-1".into(),
block_index: 0,
};
assert_eq!(user_messages(&app), [(&saved, "explain the stall")]);
}
/// A message a joined client sent is shown, after one sent here has already been adopted.
///
/// The break this catches: adopting whatever user message commits next, so the phone's message
/// replaces the id of the last one typed here and never appears.
#[test]
fn a_joined_clients_message_is_shown() {
let (mut app, _engine) = app_in_session();
send(&mut app, "mine");
committed(&mut app, "entry-1", "mine");
committed(&mut app, "entry-2", "from the phone");
let texts: Vec<&str> = user_messages(&app).into_iter().map(|(_, text)| text).collect();
assert_eq!(texts, ["mine", "from the phone"]);
}
/// A turn a joined client started shows as running from its start, not its first token.
///
/// The break this catches: ignoring `turn_started`, so the bar reads idle (and Enter starts a turn
/// instead of steering) while the phone's turn waits on the model.
#[test]
fn a_turn_another_client_started_shows_as_running() {
let (mut app, _engine) = app_in_session();
app.update(Msg::Engine(Event::TurnStarted));
assert!(app.turn_in_flight());
assert!(app.status.turn_started.is_some(), "the turn clock runs");
}
/// The break this catches: `turn_started` restarting the clock of a turn sent here, which began
/// counting when Enter was pressed.
#[test]
fn the_start_of_a_turn_sent_here_keeps_its_clock() {
let (mut app, _engine) = app_in_session();
send(&mut app, "explain the stall");
let pressed = app.status.turn_started;
std::thread::sleep(std::time::Duration::from_millis(2));
app.update(Msg::Engine(Event::TurnStarted));
assert_eq!(app.status.turn_started, pressed);
}
/// A prompt a hook refused never commits, so the turn's end lets go of it.
///
/// The break this catches: still waiting on the refused prompt's commit, so the next message a
/// joined client sends is taken for it and never shows.
#[test]
fn a_refused_prompt_does_not_claim_the_next_message() {
let (mut app, _engine) = app_in_session();
send(&mut app, "refused");
let reason = luxe_core::StopReason::EndTurn;
app.update(Msg::Engine(Event::TurnEnded { reason }));
committed(&mut app, "entry-2", "from the phone");
let texts: Vec<&str> = user_messages(&app).into_iter().map(|(_, text)| text).collect();
assert_eq!(texts, ["refused", "from the phone"]);
}

View File

@@ -0,0 +1,40 @@
//! Prompts — a modal answered on another front-end comes down here too.
use super::notify::{permission_asked, question_asked};
use super::*;
fn closed(id: &str) -> Msg {
Msg::Engine(Event::PromptClosed { id: id.into() })
}
fn quiet_app() -> App {
let (tx, _rx) = mpsc::channel(8);
App::new(tx, KeyMap::defaults(), Config::default())
}
/// A permission prompt answered on another front-end comes down, and only that one.
///
/// The break this catches: ignoring `PromptClosed`, which leaves the terminal holding a prompt a
/// phone already answered; or closing on any id, which takes down the next prompt because of a
/// late close of the last one.
#[tokio::test]
async fn a_permission_answered_elsewhere_comes_down_here() {
let mut app = quiet_app();
app.update(permission_asked("bash", "Run: ls"));
app.update(closed("perm:another"));
assert!(app.overlays.permission.is_some(), "another prompt's close leaves this one");
app.update(closed("perm:1"));
assert!(app.overlays.permission.is_none());
}
/// The same for a question, which has its own modal.
#[tokio::test]
async fn a_question_answered_elsewhere_comes_down_here() {
let mut app = quiet_app();
app.update(question_asked("Which database?"));
let id = app.overlays.question.as_ref().expect("asked").id.as_str().to_string();
app.update(closed("ask:another"));
assert!(app.overlays.question.is_some(), "another question's close leaves this one");
app.update(closed(&id));
assert!(app.overlays.question.is_none());
}

View File

@@ -326,16 +326,23 @@ fn test_status_model_cost_none_when_price_unknown() {
assert_eq!(status.cost_usd, None);
}
/// The turn timer reads at every scale a turn reaches, the way a tool card does.
///
/// The break this catches: minutes as a clock (`1:23`) with no hours, so a two-hour turn read
/// `125:03` above the composer while the tool card beside it said `2h 05m`.
#[test]
fn test_status_model_format_elapsed() {
// Zero duration.
let formatted = StatusModel::format_elapsed(std::time::Duration::ZERO);
assert!(formatted.contains("0s"), "zero elapsed should show 0s");
// Whole seconds. This counts up on a running turn, so a tenths digit is a number moving ten
// times a second beside a spinner already saying the same thing.
assert_eq!(StatusModel::format_elapsed(std::time::Duration::from_millis(3_140)), "3s");
assert_eq!(StatusModel::format_elapsed(std::time::Duration::from_secs(83)), "1m 23s");
fn the_turn_timer_reads_at_every_scale() {
use crate::statusline::format_elapsed_compact as timer;
use std::time::Duration;
assert_eq!(timer(Duration::ZERO), "0s");
// Whole seconds: a tenths digit moves ten times a second beside a bar already moving
assert_eq!(timer(Duration::from_millis(3_140)), "3s");
assert_eq!(timer(Duration::from_secs(59)), "59s");
assert_eq!(timer(Duration::from_secs(60)), "1m 00s");
assert_eq!(timer(Duration::from_secs(83)), "1m 23s");
assert_eq!(timer(Duration::from_secs(3_599)), "59m 59s");
assert_eq!(timer(Duration::from_secs(3_600)), "1h 00m");
assert_eq!(timer(Duration::from_secs(7_503)), "2h 05m");
}
#[test]
@@ -396,6 +403,42 @@ async fn turn_reports_keep_a_compaction_on_show_until_the_turn_ends() {
assert!(matches!(app.status.state, AppState::Idle), "{:?}", app.status.state);
}
/// The transcript's notices, in order.
fn system_lines(app: &App) -> Vec<String> {
let notices = app.convo.iter().filter_map(|item| match item.block() {
ConvoBlock::System(text) => Some(text.clone()),
_ => None,
});
notices.collect()
}
/// A compaction is in the transcript from the moment it starts, and its line becomes the result.
///
/// The break this catches: a minute of summary with nothing in the conversation to say so (the
/// row above the composer has no label), or a second line added beside the first when it's done.
#[tokio::test]
async fn a_compaction_is_written_down_as_it_starts_and_settled_when_done() {
let mut app = idle_app();
app.update(Msg::Engine(Event::CompactionStarted { tokens_before: 579_400 }));
assert_eq!(system_lines(&app), ["Compacting the conversation — 579.4k of context…"]);
app.update(Msg::Engine(Event::CompactionDone { tokens_before: 579_400, tokens_after: 28_700 }));
let done = "Compacted the conversation — 579.4k → 28.7k of context.";
assert_eq!(system_lines(&app), [done]);
}
/// A compaction that ends without a summary says so on the line that announced it.
///
/// The break this catches: "Compacting the conversation…" left standing after a cancel or a
/// failure, reading as a summary still under way.
#[tokio::test]
async fn a_stopped_compaction_settles_its_line() {
let mut app = idle_app();
app.update(Msg::Engine(Event::CompactionStarted { tokens_before: 190_000 }));
app.update(Msg::Engine(Event::Notice("between".into())));
app.update(Msg::Engine(Event::CompactionStopped));
assert_eq!(system_lines(&app), ["Compaction stopped.", "between"]);
}
pub(super) fn type_into(app: &mut App, text: &str) {
for character in text.chars() {
app.update(Msg::Key(KeyEvent::new(KeyCode::Char(character), KeyModifiers::NONE)));

View File

@@ -35,6 +35,7 @@ pub use card::{render_card, CardState, PullRequestCard};
pub(crate) use draft::note_lines as draft_note_lines;
pub use draft::{DraftCard, DraftKey};
pub use header::{ago, author_spans, diff_counts, state_word};
pub use html::readable;
pub use merge::MergeDialog;
pub use parts::action_hint;
pub(crate) use parts::lift_dim;

View File

@@ -7,7 +7,7 @@
//! entities. Code is left alone: a fenced block or an inline span that shows HTML means to show it.
/// `body` with its HTML reduced to markdown, outside code.
pub(super) fn readable(body: &str) -> String {
pub fn readable(body: &str) -> String {
if !body.contains('<') && !body.contains('&') {
return body.to_string();
}

View File

@@ -62,6 +62,8 @@ pub struct ImageStore {
clock: u64,
next_id: u32,
total_source_bytes: usize,
/// Bumped whenever something a layout reads changes: see [`Self::layout_revision`]
layout_revision: u64,
}
impl Default for ImageStore {
@@ -84,9 +86,20 @@ impl ImageStore {
// drawing images in the same window — and a collision silently replaces *their* image.
next_id: seed_id(),
total_source_bytes: 0,
layout_revision: 0,
}
}
/// Counts the changes to what laying an image out reads: the sources, the tier and the cell
/// size.
///
/// The transcript keys an image's laid-out rows on it, so they are reused until one of those
/// changes rather than rebuilt every frame. What is prepared for painting isn't counted:
/// painting prepares on sight.
pub fn layout_revision(&self) -> u64 {
self.layout_revision
}
/// The fidelity this store is drawing at.
pub fn tier(&self) -> ImageTier {
self.tier
@@ -98,6 +111,7 @@ impl ImageStore {
return;
}
self.tier = tier;
self.layout_revision += 1;
self.release_prepared();
}
@@ -107,6 +121,7 @@ impl ImageStore {
return;
}
self.cell = cell;
self.layout_revision += 1;
self.release_prepared();
}
@@ -132,6 +147,7 @@ impl ImageStore {
return false;
}
self.clock += 1;
self.layout_revision += 1;
self.total_source_bytes += bytes.len();
self.sources.insert(
key,
@@ -258,6 +274,7 @@ impl ImageStore {
self.release_all();
self.sources.clear();
self.total_source_bytes = 0;
self.layout_revision += 1;
}
/// Ensures `key` is prepared at `fit`, re-preparing when the size changed.
@@ -318,6 +335,7 @@ impl ImageStore {
fn drop_source(&mut self, key: &ImageKey) {
if let Some(source) = self.sources.remove(key) {
self.total_source_bytes = self.total_source_bytes.saturating_sub(source.bytes.len());
self.layout_revision += 1;
}
}

View File

@@ -239,3 +239,58 @@ fn image_ids_stay_inside_the_protocols_range() {
assert_eq!(store.allocate_id(), kitty::MAX_ID);
assert_eq!(store.allocate_id(), 1, "and wraps rather than overflowing");
}
/// The break this catches: an image arriving without moving the layout revision, so a card laid
/// out before it landed keeps its old rows.
#[test]
fn a_new_image_moves_the_layout_revision_and_a_known_one_does_not() {
let mut store = store(ImageTier::Blocks);
let empty = store.layout_revision();
let key = ImageKey::new("k");
assert!(store.insert(key.clone(), png(32, 16), origin("shot.png")));
let landed = store.layout_revision();
assert_ne!(landed, empty, "a new source moves it");
assert!(store.insert(key, png(32, 16), origin("shot.png")));
assert_eq!(store.layout_revision(), landed, "a known one changes nothing a layout reads");
}
/// The break this catches: a new cell size or tier leaving image rows sized for the old one, or
/// a repeated report of the same geometry throwing every image card's layout away.
#[test]
fn only_a_real_change_of_geometry_or_tier_moves_the_layout_revision() {
let mut store = store(ImageTier::Blocks);
let start = store.layout_revision();
store.set_cell_size(CellSize { width: 10, height: 20 });
store.set_tier(ImageTier::Blocks);
assert_eq!(store.layout_revision(), start, "the same geometry and tier change nothing");
store.set_cell_size(CellSize { width: 8, height: 16 });
let resized = store.layout_revision();
assert_ne!(resized, start, "a new cell size moves it");
store.set_tier(ImageTier::Text);
assert_ne!(store.layout_revision(), resized, "a new tier moves it");
}
/// The break this catches: a source that is gone (cleared for another session, or dropped for not
/// decoding) leaving its card laid out as though it could still be drawn.
#[test]
fn losing_a_source_moves_the_layout_revision() {
let (mut store, _) = seeded(ImageTier::Blocks, 32, 16);
let seeded_at = store.layout_revision();
store.clear();
assert_ne!(store.layout_revision(), seeded_at, "clearing moves it");
// A header that parses ahead of pixels that don't: the source is dropped on first paint
let mut broken = png(32, 16);
let pixels = broken.len() - 20;
broken[pixels] ^= 0xff;
let key = ImageKey::new("broken");
assert!(store.insert(key.clone(), broken, origin("broken.png")));
let inserted = store.layout_revision();
let fit = store.fit(&key, 6, 24).expect("the header gives a size");
let mut buf = Buffer::empty(Rect::new(0, 0, 10, 2));
assert!(!store.paint_row(&mut buf, (0, 0), &key, fit, 0, Color::Reset));
assert!(!store.contains(&key), "the source is gone");
assert_ne!(store.layout_revision(), inserted, "and the layout revision says so");
}

View File

@@ -234,7 +234,7 @@ fn role_theme() -> &'static syntect::highlighting::Theme {
}
/// One highlighted line, as roles: what the memo keeps, since it holds for every theme.
type RoleLine = Vec<(Role, String)>;
pub type RoleLine = Vec<(Role, String)>;
/// Highlights `code` as `lang`, in `styles`' colors.
///
@@ -243,7 +243,9 @@ pub fn highlight_code(code: &str, lang: Option<&str>, styles: &ThemeStyles) -> V
paint(&highlight_roles(code, lang), styles)
}
fn highlight_roles(code: &str, lang: Option<&str>) -> Arc<Vec<RoleLine>> {
/// Highlights `code` as `lang` into roles, for a surface that colors roles itself: the phone app's
/// HTML names each role's theme token as a class. Memoized, like [`highlight_code`].
pub fn highlight_roles(code: &str, lang: Option<&str>) -> Arc<Vec<RoleLine>> {
let key = fingerprint(code, lang);
if let Some(hit) = cache().get(key, code, lang) {
return hit;

View File

@@ -33,10 +33,11 @@ pub(crate) mod keys_card;
pub mod launcher;
pub mod main_loop;
pub mod markdown;
pub mod marks;
pub mod mention_flyout;
pub mod mentions;
pub mod model_picker;
pub(crate) mod modes;
pub mod modes;
pub mod mouse;
pub mod notify;
pub(crate) mod option_layer;

View File

@@ -243,8 +243,13 @@ fn matrix() -> String {
///
/// The break this catches: grouping or reordering the overlays changing which one an input
/// reaches. Set `LUXE_OVERLAY_MATRIX` to a path to write the current table there.
///
/// A click can choose a theme, which is written to the global config, so the test has a config
/// home of its own; without one it rewrites the developer's real theme.
#[tokio::test]
async fn every_pair_of_overlays_answers_as_recorded() {
let home = tempfile::tempdir().expect("temp dir");
let _config_home = crate::test_env::TempConfigHome::at(home.path());
let actual = matrix();
if let Ok(path) = std::env::var("LUXE_OVERLAY_MATRIX") {
std::fs::write(path, &actual).expect("write the matrix");

View File

@@ -11,6 +11,7 @@
//! `MarkdownVoice`.
mod fence;
pub mod html;
mod layout;
mod line;
mod table;

View File

@@ -0,0 +1,352 @@
//! Markdown as HTML — model text for the phone app, drawn the way the transcript draws it.
//!
//! The line renderer lays text out in cells at a width it knows; a browser reflows on every turn of
//! the phone, so this walks the same events, in the same dialect, into elements instead, and keeps
//! the TUI's choices: the alert's word and mark, a fence's language and copy affordance on its
//! rule, a link's address after its words. How those look (bullets, `> `, the rules) is the app's
//! stylesheet. Code is highlighted into the same roles the terminal paints, each a class naming
//! its theme token (`t-accent-secondary`), never an inline style: the app's CSP forbids those, and
//! the token's color comes from the user's theme as it is now.
//!
//! What the model wrote is data: every character of it is escaped, raw HTML shows as its source
//! the way the TUI shows it, and a link only gets an `href` when it leaves for the web or mail.
use pulldown_cmark::{Alignment, BlockQuoteKind, CodeBlockKind, Event, Parser, Tag, TagEnd};
use super::fence::fence_language;
use super::layout::parser_options;
use super::voice::{alert_icon, alert_label};
use crate::glyphs::{GlyphTier, Icon};
use crate::highlight::{highlight_roles, Role};
/// Which reader a block is rendered for, as in the transcript.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Voice {
/// Assistant prose, fences highlighted
#[default]
Answer,
/// Model reasoning: line breaks kept, fences left plain so the block stays muted
Reasoning,
}
/// The app's font ships with the Nerd Font marks, so every glyph is drawn at that tier.
const TIER: GlyphTier = GlyphTier::Nerd;
/// `src` as HTML for `voice`, with no wrapping element: the app supplies that and its class.
///
/// Partial input is fine. A reply is rendered as it streams, and pulldown-cmark closes whatever is
/// still open at the end, so an unterminated fence is a fence.
pub fn render(src: &str, voice: Voice) -> String {
let mut writer = HtmlWriter { voice, ..HtmlWriter::default() };
for event in Parser::new_ext(src, parser_options()) {
writer.event(event);
}
writer.out
}
/// One source line highlighted as HTML, the way a diff row's code is: on its own, as the TUI's
/// diff views highlight it. Everything in `text` comes back escaped.
pub fn code_line(text: &str, lang: Option<&str>) -> String {
let mut out = String::new();
// the highlighter keeps every character of a line, so only empty text has no first line
for (role, part) in highlight_roles(text, lang).first().into_iter().flatten() {
role_span_into(&mut out, *role, part);
}
out
}
/// `text` in the span for its highlight role, or bare when the role is body text.
fn role_span_into(out: &mut String, role: Role, text: &str) {
let Some(class) = role_class(role) else { return escape_into(out, text) };
out.push_str(&format!("<span class=\"{class}\">"));
escape_into(out, text);
out.push_str("</span>");
}
/// One walk's state: the HTML so far, and the open things whose end changes what is written.
#[derive(Default)]
struct HtmlWriter {
out: String,
voice: Voice,
link: Option<Link>,
fence: Option<Fence>,
table: Option<Table>,
}
/// A link being written: where it goes, what it says so far, and whether it got an `href`.
struct Link {
url: String,
words: String,
live: bool,
}
/// A code block being collected, since it is highlighted whole.
struct Fence {
lang: Option<String>,
code: String,
}
/// A table being written: how each column aligns, and which cell is next.
struct Table {
alignments: Vec<Alignment>,
cell: usize,
head: bool,
}
impl HtmlWriter {
fn event(&mut self, event: Event<'_>) {
match event {
Event::Start(tag) => self.start(tag),
Event::End(tag) => self.end(tag),
// block HTML shows as the source the model wrote, as it does in the terminal
Event::Text(text) | Event::Html(text) => self.text(&text),
Event::Code(code) => self.code(&code),
Event::SoftBreak if self.voice == Voice::Reasoning => self.out.push_str("<br>"),
Event::SoftBreak => self.out.push(' '),
Event::HardBreak => self.out.push_str("<br>"),
Event::Rule => self.out.push_str("<hr>"),
// inline HTML, footnotes and the rest: the terminal leaves them out too
_ => {}
}
}
fn start(&mut self, tag: Tag<'_>) {
match tag {
Tag::Paragraph => self.out.push_str("<p>"),
Tag::Heading { level, .. } => self.out.push_str(&format!("<{level}>")),
Tag::BlockQuote(kind) => self.open_quote(kind),
Tag::CodeBlock(kind) => {
self.fence = Some(Fence { lang: fence_lang(kind), code: "".into() })
}
Tag::List(Some(1)) => self.out.push_str("<ol>"),
Tag::List(Some(start)) => self.out.push_str(&format!("<ol start=\"{start}\">")),
Tag::List(None) => self.out.push_str("<ul>"),
Tag::Item => self.out.push_str("<li>"),
Tag::Table(alignments) => self.open_table(alignments),
Tag::TableHead | Tag::TableRow => self.open_row(),
Tag::TableCell => self.open_cell(),
Tag::Emphasis => self.out.push_str("<em>"),
Tag::Strong => self.out.push_str("<strong>"),
Tag::Strikethrough => self.out.push_str("<del>"),
Tag::Link { dest_url, .. } => self.open_link(&dest_url),
// an image's words are its alt text, which follows as text
_ => {}
}
}
fn end(&mut self, tag: TagEnd) {
let close = match tag {
TagEnd::Paragraph => "</p>",
TagEnd::Heading(level) => return self.out.push_str(&format!("</{level}>")),
TagEnd::BlockQuote(_) => "</blockquote>",
TagEnd::CodeBlock => return self.close_fence(),
TagEnd::List(true) => "</ol>",
TagEnd::List(false) => "</ul>",
TagEnd::Item => "</li>",
TagEnd::Table => return self.close_table(),
TagEnd::TableHead => return self.close_head(),
TagEnd::TableRow => "</tr>",
TagEnd::TableCell => return self.close_cell(),
TagEnd::Emphasis => "</em>",
TagEnd::Strong => "</strong>",
TagEnd::Strikethrough => "</del>",
TagEnd::Link => return self.close_link(),
_ => "",
};
self.out.push_str(close);
}
fn text(&mut self, text: &str) {
if let Some(fence) = &mut self.fence {
return fence.code.push_str(text);
}
if let Some(link) = &mut self.link {
link.words.push_str(text);
}
escape_into(&mut self.out, text);
}
fn code(&mut self, code: &str) {
if let Some(link) = &mut self.link {
link.words.push_str(code);
}
self.out.push_str("<code>");
escape_into(&mut self.out, code);
self.out.push_str("</code>");
}
/// Opens a quote; an alert writes its word out first, since its severity is in the tag rather
/// than in its prose, and the color is only polish.
fn open_quote(&mut self, kind: Option<BlockQuoteKind>) {
let Some(kind) = kind else { return self.out.push_str("<blockquote>") };
let label = alert_label(kind);
self.out.push_str(&format!("<blockquote class=\"alert {}\">", label.to_lowercase()));
self.out.push_str("<p class=\"alert-label\">");
escape_into(&mut self.out, &icon_label(alert_icon(kind), label));
self.out.push_str("</p>");
}
fn open_link(&mut self, url: &str) {
let live = leaves_for_the_web(url);
if live {
self.out.push_str("<a href=\"");
escape_into(&mut self.out, url);
self.out.push_str("\" target=\"_blank\" rel=\"noopener noreferrer\">");
} else {
self.out.push_str("<span class=\"link\">");
}
self.link = Some(Link { url: url.to_string(), words: String::new(), live });
}
/// Closes a link and writes its address after it, once, unless the words already are the
/// address or a table cell holds it, as the terminal does.
fn close_link(&mut self) {
let Some(link) = self.link.take() else { return };
self.out.push_str(if link.live { "</a>" } else { "</span>" });
let repeats = link.url.trim_start_matches("mailto:") == link.words.trim();
if link.url.is_empty() || repeats || self.table.is_some() {
return;
}
self.out.push_str("<span class=\"url\"> (");
escape_into(&mut self.out, &link.url);
self.out.push_str(")</span>");
}
}
impl HtmlWriter {
/// Writes a code block between its rules: the language and copy on the top one. An empty
/// block draws nothing, as in the terminal.
fn close_fence(&mut self) {
let Some(fence) = self.fence.take() else { return };
if fence.code.is_empty() {
return;
}
self.out.push_str("<figure class=\"fence\"><figcaption>");
if let Some(language) = fence_language(fence.lang.as_deref()) {
self.out.push_str("<span class=\"lang\">");
let icon = crate::widgets::language_icon(&language);
escape_into(&mut self.out, &icon_label(icon, &language));
self.out.push_str("</span>");
}
self.out.push_str("<span class=\"fill\"></span><button type=\"button\" class=\"copy\">");
escape_into(&mut self.out, &icon_label(Icon::Copy, "copy"));
self.out.push_str("</button></figcaption><pre><code>");
self.fence_body(&fence);
self.out.push_str("</code></pre></figure>");
}
/// The code, highlighted for an answer and plain for reasoning, which a palette would pull out
/// of its muted voice.
fn fence_body(&mut self, fence: &Fence) {
if self.voice == Voice::Reasoning {
return escape_into(&mut self.out, fence.code.trim_end_matches('\n'));
}
let lines = highlight_roles(&fence.code, fence.lang.as_deref());
for (index, line) in lines.iter().enumerate() {
if index > 0 {
self.out.push('\n');
}
for (role, text) in line {
role_span_into(&mut self.out, *role, text);
}
}
}
fn open_table(&mut self, alignments: Vec<Alignment>) {
self.table = Some(Table { alignments, cell: 0, head: true });
self.out.push_str("<div class=\"table\"><table><thead>");
}
fn open_row(&mut self) {
if let Some(table) = &mut self.table {
table.cell = 0;
}
self.out.push_str("<tr>");
}
fn open_cell(&mut self) {
let Some(table) = &mut self.table else { return };
let tag = if table.head { "th" } else { "td" };
let align = match table.alignments.get(table.cell) {
Some(Alignment::Right) => " class=\"right\"",
Some(Alignment::Center) => " class=\"center\"",
_ => "",
};
self.out.push_str(&format!("<{tag}{align}>"));
}
fn close_cell(&mut self) {
let Some(table) = &mut self.table else { return };
self.out.push_str(if table.head { "</th>" } else { "</td>" });
table.cell += 1;
}
/// pulldown-cmark puts the header cells straight under the head, with no row of their own.
fn close_head(&mut self) {
if let Some(table) = &mut self.table {
table.head = false;
}
self.out.push_str("</tr></thead><tbody>");
}
fn close_table(&mut self) {
self.table = None;
self.out.push_str("</tbody></table></div>");
}
}
/// The language a code block declared: an indented one declares none.
fn fence_lang(kind: CodeBlockKind<'_>) -> Option<String> {
match kind {
CodeBlockKind::Fenced(lang) => Some(lang.to_string()),
CodeBlockKind::Indented => None,
}
}
/// `{glyph} {label}`, the shape the terminal's labels take at the Nerd tier.
fn icon_label(icon: Icon, label: &str) -> String {
format!("{} {label}", icon.at(TIER))
}
/// The classes a role is drawn with: its theme token, then its weight or slant. Plain text takes
/// none, which keeps a highlighted block about half the size.
fn role_class(role: Role) -> Option<String> {
use ratatui::style::Modifier;
if role == Role::Text {
return None;
}
let (token, modifier) = role.token();
let mut class = format!("t-{}", luxe_core::theme::css::css_name(token));
if modifier.contains(Modifier::BOLD) {
class.push_str(" b");
}
if modifier.contains(Modifier::ITALIC) {
class.push_str(" i");
}
Some(class)
}
/// Whether a link may be followed from the app: to the web or to mail, never `javascript:`, a
/// `data:` page, or a path on the bridge itself.
fn leaves_for_the_web(url: &str) -> bool {
let lower = url.trim_start().to_ascii_lowercase();
["https://", "http://", "mailto:"].iter().any(|scheme| lower.starts_with(scheme))
}
/// Appends `text` with every character that means something in HTML escaped, quotes included,
/// since some of it lands in attributes.
fn escape_into(out: &mut String, text: &str) {
for character in text.chars() {
match character {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
_ => out.push(character),
}
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,135 @@
use super::{code_line, render, Voice};
fn answer(src: &str) -> String {
render(src, Voice::Answer)
}
/// What a model writes is shown, never run: block HTML is escaped and inline HTML left out.
///
/// The break this catches: text written into the page unescaped, which would let a reply run
/// script in the app.
#[test]
fn model_html_is_shown_not_run() {
let html = answer("<script>alert(1)</script>\n\nhi <img src=x onerror=alert(1)> & bye");
assert!(!html.contains("<script"), "{html}");
assert!(!html.contains("<img"), "{html}");
assert!(html.contains("&lt;script&gt;alert(1)&lt;/script&gt;"), "{html}");
assert!(html.contains("&amp; bye"), "{html}");
}
/// The break this catches: any scheme getting an `href`, so a tap on `javascript:` runs it.
#[test]
fn only_web_and_mail_links_are_followed() {
let unsafe_link = answer("[tap](javascript:alert(1))");
assert!(!unsafe_link.contains("href"), "{unsafe_link}");
assert!(unsafe_link.contains("<span class=\"link\">tap</span>"), "{unsafe_link}");
let page = answer("[docs](https://example.com/a)");
assert!(page.contains("<a href=\"https://example.com/a\""), "{page}");
assert!(answer("[me](mailto:a@b.c)").contains("href=\"mailto:a@b.c\""));
assert!(!answer("[up](/api/sessions)").contains("href"));
}
/// The break this catches: an address written into `href` unescaped, so a quote in it closes the
/// attribute and opens one of the model's choosing.
#[test]
fn a_link_cannot_add_attributes() {
let html = answer("[a](<https://x.y/\" onclick=\"steal()>)");
assert!(!html.contains("\" onclick"), "{html}");
assert!(html.contains("&quot; onclick=&quot;steal()"), "{html}");
}
/// The address follows the words, as in the terminal, but not when the words are the address.
///
/// The break this catches: the repeat check dropped, doubling every bare link.
#[test]
fn a_link_names_its_address_unless_its_words_are_it() {
let named = answer("[docs](https://example.com)");
assert!(named.contains("<span class=\"url\"> (https://example.com)</span>"), "{named}");
let bare = answer("<https://example.com>");
assert!(!bare.contains("class=\"url\""), "{bare}");
}
/// The break this catches: a fence losing its language label, copy control or highlighting
/// classes, which are what make it read like the terminal's.
#[test]
fn a_fence_is_framed_with_its_language_and_copy() {
let html = answer("```Rust\nfn main() {}\n```");
assert!(html.contains("<span class=\"lang\">"), "{html}");
assert!(html.contains(" rust</span>"), "{html}");
assert!(html.contains("<button type=\"button\" class=\"copy\">"), "{html}");
assert!(html.contains("<span class=\"t-accent-secondary\">fn</span>"), "{html}");
assert!(html.contains("<span class=\"t-accent\">main</span>"), "{html}");
}
/// The break this catches: a diff row's code left unhighlighted, highlighted for the wrong
/// language, or written into the page unescaped.
#[test]
fn a_line_of_code_is_highlighted_and_escaped() {
let html = code_line("fn main() { a < b }", Some("rs"));
assert!(html.starts_with("<span class=\"t-accent-secondary\">fn</span>"), "{html}");
assert!(html.contains("&lt;"), "{html}");
assert!(!html.contains(" < "), "{html}");
assert_eq!(code_line("a < b", None), "a &lt; b");
}
/// A fence that says it is plain text names no language, and an empty one draws nothing.
///
/// The break this catches: the label taken from the raw info string instead of
/// `fence_language`, or an empty block drawn as an empty frame.
#[test]
fn a_plain_or_empty_fence_names_nothing() {
let plain = answer("```text\nx\n```");
assert!(plain.contains("<figure class=\"fence\">"), "{plain}");
assert!(!plain.contains("class=\"lang\""), "{plain}");
assert_eq!(answer("```\n```"), "");
}
/// Streaming input ends wherever the model has got to; a fence still open is still a fence.
///
/// The break this catches: code collected and only written at a closing fence that has not
/// arrived yet, so a streaming block shows nothing.
#[test]
fn an_unfinished_fence_is_still_drawn() {
let html = answer("Here:\n\n```rust\nlet x");
assert!(html.contains("<pre><code>"), "{html}");
assert!(html.contains("x</code>"), "{html}");
}
/// Reasoning keeps its line breaks and leaves its code plain; an answer reflows.
///
/// The break this catches: the voice ignored, so reasoning runs its notes together or wears a
/// syntax palette.
#[test]
fn reasoning_keeps_breaks_and_plain_code() {
assert_eq!(render("a\nb", Voice::Reasoning), "<p>a<br>b</p>");
assert_eq!(answer("a\nb"), "<p>a b</p>");
let fence = render("```rust\nfn main() {}\n```", Voice::Reasoning);
assert!(!fence.contains("t-"), "{fence}");
assert!(fence.contains("fn main() {}</code>"), "{fence}");
}
/// The break this catches: an alert drawn as a plain quote, losing the only thing that made it
/// one.
#[test]
fn an_alert_writes_its_word() {
let html = answer("> [!WARNING]\n> careful");
assert!(html.starts_with("<blockquote class=\"alert warning\"><p class=\"alert-label\">"));
assert!(html.contains(" Warning</p>"), "{html}");
assert!(html.contains("<p>careful</p>"), "{html}");
}
/// The break this catches: the column count not reset per row, so the second body row takes
/// alignments that belong to cells past the end.
#[test]
fn table_cells_keep_their_column_alignment() {
let html = answer("| a | b |\n|---|--:|\n| 1 | 2 |\n| 3 | 4 |");
assert!(html.contains("<thead><tr><th>a</th><th class=\"right\">b</th></tr></thead>"));
assert!(html.contains("<tr><td>3</td><td class=\"right\">4</td></tr>"), "{html}");
}
/// The break this catches: a list's start number dropped, renumbering a list the model resumed.
#[test]
fn an_ordered_list_keeps_its_start() {
assert!(answer("3. x\n4. y").starts_with("<ol start=\"3\"><li>x</li>"));
assert!(answer("1. x").starts_with("<ol><li>"));
}

View File

@@ -37,20 +37,25 @@ fn push_block_gap(lines: &mut Vec<MarkdownLine>) {
}
}
/// Renders markdown in `voice`, preserving the structural block kinds conversation layout needs.
pub(crate) fn layout_markdown_in(
src: &str,
theme: &ThemeStyles,
voice: MarkdownVoice,
) -> Vec<MarkdownLine> {
/// The dialect model markdown is read in, here and in the phone app's HTML.
pub(super) fn parser_options() -> Options {
let mut opts = Options::empty();
opts.insert(Options::ENABLE_STRIKETHROUGH);
opts.insert(Options::ENABLE_TABLES);
// Alerts (`> [!WARNING]`) are the GitHub dialect models were trained on and write unprompted.
// Without this the tag is body text, and the quote opens with a literal `[!WARNING]`.
opts.insert(Options::ENABLE_GFM);
opts
}
/// Renders markdown in `voice`, preserving the structural block kinds conversation layout needs.
pub(crate) fn layout_markdown_in(
src: &str,
theme: &ThemeStyles,
voice: MarkdownVoice,
) -> Vec<MarkdownLine> {
let mut renderer = MarkdownRenderer::new(theme, voice);
for event in Parser::new_ext(src, opts) {
for event in Parser::new_ext(src, parser_options()) {
renderer.event(event);
}
// Flush any remaining spans

View File

@@ -0,0 +1,29 @@
//! Marks — the signs the dock puts beside a todo and a changed file.
//!
//! Public so the phone app's renderer draws the same ones; the dock's colors stay with the dock,
//! and the app's stylesheet colors them by status.
use crate::glyphs::{GlyphTier, Mark};
use luxe_core::workspace::FileChangeStatus;
use luxe_core::TodoSummaryStatus;
/// The mark beside a todo in the PLAN checklist, at `tier`.
pub fn todo(status: TodoSummaryStatus, tier: GlyphTier) -> &'static str {
match status {
TodoSummaryStatus::Completed => Mark::Yes.at(tier),
TodoSummaryStatus::InProgress => Mark::Underway.at(tier),
TodoSummaryStatus::Blocked => Mark::Halted.at(tier),
TodoSummaryStatus::Pending => "○",
}
}
/// The letter Git's status reads as beside a changed file.
pub const fn change(status: FileChangeStatus) -> &'static str {
match status {
FileChangeStatus::Added => "A",
FileChangeStatus::Modified => "M",
FileChangeStatus::Deleted => "D",
FileChangeStatus::Renamed => "R",
FileChangeStatus::Untracked => "?",
}
}

View File

@@ -11,8 +11,8 @@ use crate::theme::styles::ThemeStyles;
use ratatui::style::Style;
use std::borrow::Cow;
/// The icon beside a mode's name.
pub(crate) fn icon(mode: &str) -> Icon {
/// The icon beside a mode's name, here and on the phone app's mode button.
pub fn icon(mode: &str) -> Icon {
match mode {
luxe_core::mode::PLAN => Icon::ModePlan,
_ => Icon::ModeBuild,

View File

@@ -18,6 +18,7 @@
mod activity;
mod layout;
pub mod plain;
mod segments;
use crate::app::App;
@@ -321,6 +322,11 @@ fn palette(theme: &ThemeStyles) -> Palette {
}
}
/// How full a window of `window` tokens is with `used` in it, as a percentage capped at 100.
pub(crate) fn context_percent(used: u32, window: u32) -> f32 {
(used as f32 / window as f32 * 100.0).min(100.0)
}
pub(crate) fn compact_number(value: u64) -> String {
if value < 1_000 {
value.to_string()

View File

@@ -42,16 +42,18 @@ pub(crate) fn activity_parts(app: &App) -> Option<(&'static str, String)> {
}
}
/// Formats turn elapsed time compactly: `45s` under a minute, `1:23` beyond.
/// Formats a live timer: `45s`, `1m 23s`, then `1h 04m`.
///
/// Whole seconds, for the reason the tool card's duration is: this is redrawn on every frame of a
/// running turn, and a tenths digit there is a number moving ten times a second beside a spinner
/// that is already saying the same thing.
/// The one format for every clock that counts up, tool cards included, so a turn and the call
/// inside it never read in two notations. Whole seconds: this is redrawn every frame, and a tenths
/// digit is a number moving ten times a second beside a bar that already shows motion. Seconds go
/// past an hour, where nobody acts on them.
pub(crate) fn format_elapsed_compact(elapsed: std::time::Duration) -> String {
if elapsed.as_secs() < 60 {
format!("{}s", elapsed.as_secs())
} else {
format!("{}:{:02}", elapsed.as_secs() / 60, elapsed.as_secs() % 60)
let secs = elapsed.as_secs();
match secs {
0..=59 => format!("{secs}s"),
60..=3_599 => format!("{}m {:02}s", secs / 60, secs % 60),
_ => format!("{}h {:02}m", secs / 3_600, (secs % 3_600) / 60),
}
}

View File

@@ -0,0 +1,116 @@
//! Plain — the status line's right-hand facts as words, for a surface that isn't a terminal.
//!
//! The phone app shows what the bar shows, so it takes the bar's own wording from here rather than
//! keeping a copy that could drift: the context reading and its ramp, the cost slot's choice
//! between a plan's allowance and the session's spend, the thinking level's short name. No slabs
//! and no truncation, which are the terminal's problems; glyphs are the Nerd Font marks, which the
//! app's font always has.
use super::segments::{context_text, cost_text};
use super::{context_percent, thinking_label};
use crate::glyphs::{GlyphTier, Icon};
use crate::theme::styles::ContextFill;
use luxe_core::provider::{PlanUsage, ThinkingLevel};
use luxe_core::usage::SessionUsage;
use luxe_core::ModelRef;
/// What a session last reported, each part absent until its event arrives.
#[derive(Debug, Default, Clone, Copy)]
pub struct Facts<'a> {
/// The model answering, from `state_changed`
pub model: Option<&'a ModelRef>,
/// Its thinking level, from `state_changed`
pub thinking: Option<ThinkingLevel>,
/// Tokens in the window and the window's size, from `context_usage`
pub context: Option<(u32, u32)>,
/// A subscription's allowance, from `plan_usage`
pub plan: Option<&'a PlanUsage>,
/// The session's spend, from `session_usage`
pub session: Option<&'a SessionUsage>,
}
/// One fact as the bar words it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Segment {
/// Which fact this is
pub kind: Kind,
/// The mark in front of it, if the bar draws one
pub glyph: Option<&'static str>,
/// The words
pub label: String,
/// How loudly to color it
pub tone: Tone,
}
/// The facts, in the bar's order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
/// How full the context window is
Context,
/// A plan's allowance or the session's spend
Cost,
/// The thinking level
Thinking,
/// The model
Model,
}
/// How loudly a segment is colored.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tone {
/// Body text
Plain,
/// The theme's warning color
Warning,
/// The theme's error color
Error,
}
/// The facts the session has reported, worded and ordered as the bar's right-hand side.
pub fn segments(facts: &Facts<'_>) -> Vec<Segment> {
[context(facts), cost(facts), thinking(facts), model(facts)].into_iter().flatten().collect()
}
fn context(facts: &Facts<'_>) -> Option<Segment> {
let (used, window) = facts.context.filter(|(_, window)| *window > 0)?;
let percent = context_percent(used, window);
let tone = match ContextFill::at(percent) {
ContextFill::Roomy => Tone::Plain,
ContextFill::Filling => Tone::Warning,
ContextFill::Full => Tone::Error,
};
Some(Segment {
kind: Kind::Context,
glyph: Some(Icon::Context.at(GlyphTier::Nerd)),
label: context_text(percent, window),
tone,
})
}
fn cost(facts: &Facts<'_>) -> Option<Segment> {
let label = cost_text(facts.plan, facts.session.unwrap_or(&SessionUsage::default()))?;
Some(Segment { kind: Kind::Cost, glyph: None, label, tone: Tone::Plain })
}
fn thinking(facts: &Facts<'_>) -> Option<Segment> {
let level = facts.thinking?;
facts.model.filter(|model| !model.model.is_empty())?;
Some(Segment {
kind: Kind::Thinking,
glyph: Some(Icon::Thinking.at(GlyphTier::Nerd)),
label: thinking_label(&level).to_string(),
tone: Tone::Plain,
})
}
// Always there, as on the bar: with no model, saying so explains a refused turn
fn model(facts: &Facts<'_>) -> Option<Segment> {
let (label, tone) = match facts.model.filter(|model| !model.model.is_empty()) {
Some(model) => (model.display().to_string(), Tone::Plain),
None => ("no model".to_string(), Tone::Warning),
};
Some(Segment { kind: Kind::Model, glyph: Some(Icon::Model.at(GlyphTier::Nerd)), label, tone })
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,89 @@
use super::*;
use luxe_core::usage::UsageTotals;
/// `state_changed`, `plan_usage` and `session_usage` as a Copilot session sent them over the
/// bridge, so the shapes the phone forwards are the ones these words are made from.
const MODEL: &str = r#"{"provider":"github-copilot","model":"claude-haiku-4.5","display_name":"Claude Haiku 4.5 (latest)"}"#;
const PLAN: &str = r#"{"plan":"individual","primary":{"used_percent":22.3,"window_minutes":43200,"resets_in_secs":1106993}}"#;
const SESSION: &str = r#"{"total":{"calls":14,"prompt_tokens":122790,"completion_tokens":2212,"cache_read_tokens":103435,"cache_write_tokens":19237,"reasoning_tokens":888,"cost_usd":0.0,"unpriced_calls":0,"plan_usd":0.04556775,"plan_calls":14},"by_source":[]}"#;
fn parse<T: serde::de::DeserializeOwned>(json: &str) -> T {
serde_json::from_str(json).expect("a literal copied from a real frame parses")
}
fn words(facts: &Facts<'_>) -> Vec<(Kind, String)> {
segments(facts).into_iter().map(|segment| (segment.kind, segment.label)).collect()
}
fn spent(cost_usd: f64) -> SessionUsage {
SessionUsage::single(
luxe_core::usage::UsageSource::Agent,
UsageTotals { calls: 1, cost_usd, ..UsageTotals::default() },
)
}
/// The break this catches: the phone's wording or order drifting from the bar's, which says
/// `4.8%/200k`, the plan's share, `high` and the model, in that order.
#[test]
fn every_fact_reads_as_the_bar_words_it() {
let (model, plan, session) = (parse(MODEL), parse(PLAN), parse(SESSION));
let facts = Facts {
model: Some(&model),
thinking: Some(ThinkingLevel::High),
context: Some((9613, 200_000)),
plan: Some(&plan),
session: Some(&session),
};
let expected = [
(Kind::Context, "4.8%/200k"),
(Kind::Cost, "22% monthly"),
(Kind::Thinking, "high"),
(Kind::Model, "Claude Haiku 4.5 (latest)"),
];
let expected: Vec<_> = expected.into_iter().map(|(kind, label)| (kind, label.into())).collect();
assert_eq!(words(&facts), expected);
}
/// The break this catches: the phone coloring a window at a different mark than the bar's ramp.
#[test]
fn the_context_reading_colors_on_the_bars_ramp() {
let tone = |used| {
let facts = Facts { context: Some((used, 1000)), ..Facts::default() };
segments(&facts)[0].tone
};
assert_eq!([tone(749), tone(750), tone(900)], [Tone::Plain, Tone::Warning, Tone::Error]);
}
/// The break this catches: a dollar figure shown in the slot a plan's allowance owns, spend
/// dropped when there's no plan, plan-billed calls with no allowance reading shown as nothing
/// rather than what they were worth, or `$0.00` claimed before anything was priced.
#[test]
fn the_cost_slot_prefers_the_plan_then_the_spend_then_nothing() {
let (plan, session, covered) = (parse::<PlanUsage>(PLAN), spent(0.44), parse(SESSION));
let cost = |plan, session| {
let facts = Facts { plan, session, ..Facts::default() };
segments(&facts).into_iter().find(|segment| segment.kind == Kind::Cost).map(|s| s.label)
};
assert_eq!(cost(Some(&plan), Some(&session)).as_deref(), Some("22% monthly"));
assert_eq!(cost(None, Some(&session)).as_deref(), Some("$0.44"));
assert_eq!(cost(None, Some(&covered)).as_deref(), Some("≈$0.05"));
assert_eq!(cost(None, None), None);
}
/// The break this catches: a session with no model left without a word, when saying so is what
/// explains a refused turn; or a thinking level shown for a model that isn't there.
#[test]
fn no_model_says_so_and_drops_the_thinking_level() {
let facts = Facts { thinking: Some(ThinkingLevel::High), ..Facts::default() };
let all = segments(&facts);
assert_eq!(all.len(), 1, "{all:?}");
assert_eq!((all[0].label.as_str(), all[0].tone), ("no model", Tone::Warning));
}
/// The break this catches: an empty window (a provider that doesn't say its size) read as a
/// division by zero, which prints `NaN%` or `inf%`.
#[test]
fn a_window_of_unknown_size_shows_no_reading() {
let facts = Facts { context: Some((10, 0)), ..Facts::default() };
assert!(segments(&facts).iter().all(|segment| segment.kind != Kind::Context));
}

View File

@@ -9,6 +9,8 @@ use crate::app::App;
use crate::glyphs::Icon;
use crate::widgets::truncate_end as truncate_to_width;
use luxe_core::config::StatuslineModule;
use luxe_core::provider::PlanUsage;
use luxe_core::usage::SessionUsage;
/// Builds the left cluster from the configured (or default) module list.
///
@@ -282,12 +284,7 @@ pub(super) fn right_segments(app: &App, palette: Palette) -> Vec<Segment> {
fn right_segment(module: StatuslineModule, app: &App, palette: Palette) -> Option<Segment> {
match module {
StatuslineModule::Cost => {
// On a subscription the binding constraint is the plan's allowance, not a dollar figure
// nobody is being charged — so that takes the slot when the provider reports it.
let label = match app.status.plan_compact() {
Some(plan) => plan,
None => app.status.session_cost_label()?,
};
let label = cost_text(app.status.plan_usage.as_ref(), &app.status.session)?;
Some(segment(SegmentKind::Cost, None, label, Ink::Neutral))
}
StatuslineModule::Tokens
@@ -325,11 +322,7 @@ fn right_segment(module: StatuslineModule, app: &App, palette: Palette) -> Optio
Some(segment(
SegmentKind::Context,
Some((Icon::Context.glyph(), ink)),
format!(
"{:.1}%/{}",
app.status.context_pct,
compact_number(u64::from(app.status.context_window))
),
context_text(app.status.context_pct, app.status.context_window),
ink,
))
}
@@ -363,3 +356,16 @@ fn right_segment(module: StatuslineModule, app: &App, palette: Palette) -> Optio
_ => None,
}
}
/// The cost slot's words. On a subscription the binding constraint is the plan's allowance, not a
/// dollar figure nobody is being charged, so that takes the slot when the provider reports it.
pub(super) fn cost_text(plan: Option<&PlanUsage>, session: &SessionUsage) -> Option<String> {
plan.and_then(PlanUsage::compact)
.or_else(|| session.total.cost_label())
.or_else(|| session.total.plan_label())
}
/// The context reading: `4.8%/200k`.
pub(super) fn context_text(percent: f32, window: u32) -> String {
format!("{percent:.1}%/{}", compact_number(u64::from(window)))
}

View File

@@ -219,18 +219,15 @@ impl ThemeStyles {
/// How full the context window reads at `percent`: body text, then warning, then error.
///
/// One ramp, two surfaces. The rail prints the number in a telemetry row and the statusline
/// prints it in a slab, and they had drifted — one went default-to-warning at 75 while the other
/// went green-to-warning at 70, so the same session read as "fine" in one place and "filling" in
/// the other. Low is body text rather than a color, because a window with room left is not news;
/// the hue is spent on the point where the next long turn compacts.
/// One ramp for every surface that prints the number (the rail, the statusline, the phone
/// app), so a session never reads as "fine" in one place and "filling" in another. Low is body
/// text rather than a color, because a window with room left is not news; the hue is spent on
/// the point where the next long turn compacts.
pub fn context_fill(&self, percent: f32) -> Style {
if percent >= CONTEXT_ERROR_PCT {
self.error
} else if percent >= CONTEXT_WARNING_PCT {
self.warning
} else {
self.text
match ContextFill::at(percent) {
ContextFill::Full => self.error,
ContextFill::Filling => self.warning,
ContextFill::Roomy => self.text,
}
}
@@ -466,6 +463,30 @@ const CARD_TINT: f32 = 0.09;
/// obviously located at a glance but the marks read first.
const DIFF_EMPHASIS_TINT: f32 = 0.20;
/// How full a context window reads, on the ramp [`ThemeStyles::context_fill`] colors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ContextFill {
/// Room left, which is not news
Roomy,
/// Past the warning mark
Filling,
/// Near the point where the next long turn compacts
Full,
}
impl ContextFill {
/// Where `percent` sits on the ramp.
pub(crate) fn at(percent: f32) -> Self {
if percent >= CONTEXT_ERROR_PCT {
Self::Full
} else if percent >= CONTEXT_WARNING_PCT {
Self::Filling
} else {
Self::Roomy
}
}
}
/// Context occupancy at which the reading turns warning-colored.
const CONTEXT_WARNING_PCT: f32 = 75.0;

View File

@@ -93,8 +93,8 @@ fn card_icon<'a>(
// The tool running and the model writing the call are both work in progress, and
// the card says so the same way for each — a spinner over a card that is visibly
// filling in, and a queued mark only over one that genuinely is not moving. A
// model writes a message's calls in order and the engine runs them in order, so
// exactly one card spins at a time.
// model writes a message's calls in order and the engine runs them in order, and a
// call written while another runs arrives queued, so exactly one card spins at a time.
// Except the call that is waiting on the reader. A spinner says the agent is busy, and
// over a question it is waiting on you to answer it only adds pressure; the call's
// own glyph, in the same running color, says it is open without hurrying anyone
@@ -238,15 +238,10 @@ pub(in crate::view) const BODY_INDENT: &str = " ";
/// the corner of the eye — which is what a spinner is for, and this is not the spinner. Nobody
/// acts on the tenth of a second a call took; they act on whether it was one second or forty.
pub(super) fn format_tool_duration(elapsed_ms: u64) -> String {
const SECOND: u64 = 1_000;
const MINUTE: u64 = 60 * SECOND;
const HOUR: u64 = 60 * MINUTE;
match elapsed_ms {
0 => "<1ms".to_string(),
ms if ms < SECOND => format!("{ms}ms"),
ms if ms < MINUTE => format!("{}s", ms / SECOND),
ms if ms < HOUR => format!("{}m {:02}s", ms / MINUTE, (ms % MINUTE) / SECOND),
ms => format!("{}h {:02}m", ms / HOUR, (ms % HOUR) / MINUTE),
ms if ms < 1_000 => format!("{ms}ms"),
ms => crate::statusline::format_elapsed_compact(std::time::Duration::from_millis(ms)),
}
}

View File

@@ -9,25 +9,13 @@ use ratatui::{
text::{Line, Span},
};
/// The color-independent lifecycle marker.
const fn change_status_marker(status: luxe_core::workspace::FileChangeStatus) -> &'static str {
use luxe_core::workspace::FileChangeStatus as Status;
match status {
Status::Added => "A",
Status::Modified => "M",
Status::Deleted => "D",
Status::Renamed => "R",
Status::Untracked => "?",
}
}
/// The dock's marker and color for `status`, for another surface that shows a file's Git status
/// and must show it the same way.
pub(crate) fn status_mark(
status: luxe_core::workspace::FileChangeStatus,
theme: &crate::theme::styles::ThemeStyles,
) -> (&'static str, ratatui::style::Style) {
(change_status_marker(status), status_style(status, theme))
(crate::marks::change(status), status_style(status, theme))
}
fn status_style(

View File

@@ -169,13 +169,12 @@ pub(super) fn todo_lines(
app: &App,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let (glyph, style) = match item.status {
TodoSummaryStatus::Completed => (crate::glyphs::Mark::Yes.glyph(), styles.success),
TodoSummaryStatus::InProgress => {
(crate::glyphs::Mark::Underway.glyph(), styles.text.add_modifier(Modifier::BOLD))
}
TodoSummaryStatus::Blocked => (crate::glyphs::Mark::Halted.glyph(), styles.warning),
TodoSummaryStatus::Pending => ("○", styles.muted),
let glyph = crate::marks::todo(item.status, crate::glyphs::tier());
let style = match item.status {
TodoSummaryStatus::Completed => styles.success,
TodoSummaryStatus::InProgress => styles.text.add_modifier(Modifier::BOLD),
TodoSummaryStatus::Blocked => styles.warning,
TodoSummaryStatus::Pending => styles.muted,
};
let subject_style = match item.status {
TodoSummaryStatus::Completed => style.add_modifier(Modifier::CROSSED_OUT),

View File

@@ -261,8 +261,8 @@ fn model_telemetry(app: &App, served_by: &str, row: usize, column: usize) -> Vec
lines
}
/// The SESSION block, once a turn has something to measure: the window, tokens, cost, and what
/// the review and compaction spent of it.
/// The SESSION block, once a turn has something to measure or someone has joined: the window,
/// tokens, cost, what the review and compaction spent of it, and who's joined.
fn session_telemetry(app: &App, row: usize, column: usize) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let status = &app.status;
@@ -270,7 +270,8 @@ fn session_telemetry(app: &App, row: usize, column: usize) -> Vec<Line<'static>>
let totals = &status.session.total;
let cost = status.session_cost_label();
let has_tokens = totals.prompt_tokens > 0 || totals.completion_tokens > 0;
if !(status.context_window > 0 || has_tokens || cost.is_some()) {
let joined = guests_row(app, row, column);
if !(status.context_window > 0 || has_tokens || cost.is_some() || joined.is_some()) {
return lines;
}
lines.push(Line::default());
@@ -304,9 +305,21 @@ fn session_telemetry(app: &App, row: usize, column: usize) -> Vec<Line<'static>>
lines.push(telemetry_row("cost", cost, styles.text, column, app));
}
lines.extend(source_cost_rows(app, column));
lines.extend(joined);
lines
}
/// Who's joined from elsewhere, while anyone has: here rather than in the transcript, where a
/// phone's every reconnect would add a line.
fn guests_row(app: &App, row: usize, column: usize) -> Option<Line<'static>> {
let guests = &app.status.guests;
if guests.is_empty() {
return None;
}
let names = truncate_cells(&guests.join(", "), telemetry_value_width(row, column));
Some(telemetry_row("joined", names, app.theme_styles.text, column, app))
}
/// What the review and compaction cost, each a dimmed share of the session's total.
fn source_cost_rows(app: &App, column: usize) -> Vec<Line<'static>> {
let styles = &app.theme_styles;

View File

@@ -5,6 +5,7 @@ use luxe_core::{config::Config, keymap::KeyMap};
use ratatui::style::Color;
use unicode_width::UnicodeWidthStr;
mod guests;
mod lists;
mod plan;
mod rail;

View File

@@ -0,0 +1,27 @@
//! Guests — who's joined the session from elsewhere, as the rail's SESSION block shows them.
use super::rail::{app, text};
use super::*;
/// The rail's lines as text.
fn rendered(app: &App) -> Vec<String> {
telemetry_lines(app).iter().map(text).collect()
}
/// Who's joined shows in SESSION while anyone has, even before a turn has anything to measure,
/// and leaves no row once they've gone.
///
/// The break this catches: a phone joined to an idle session shown nowhere (SESSION waits for a
/// turn), or the row left behind after everyone left.
#[test]
fn the_rail_shows_who_has_joined_while_they_are_here() {
let mut app = app();
assert!(!rendered(&app).iter().any(|line| line.contains("joined")));
app.status.guests = vec!["iPhone".into(), "iPad".into()];
let lines = rendered(&app);
let row = lines.iter().find(|line| line.contains("joined")).expect("a joined row");
assert!(row.ends_with("iPhone, iPad"), "{row:?}");
assert!(lines.iter().any(|line| line.contains("SESSION")), "{lines:?}");
app.status.guests.clear();
assert!(!rendered(&app).iter().any(|line| line.contains("joined")));
}

View File

@@ -407,23 +407,8 @@ fn chapter_accounted_label(
review: &luxe_core::guided_review::GuidedReview,
chapter: &luxe_core::guided_review::ReviewChapter,
) -> String {
use luxe_core::guided_review::{ItemVerdict, ReviewItemRef};
let mut reason: Option<luxe_core::guided_review::Accounted> = None;
for item in &chapter.items {
let verdict = match item {
ReviewItemRef::Hunk(hunk_id) => app.review.budget.hunk_verdict(hunk_id),
ReviewItemRef::File(_) => app.review.budget.verdict(item),
};
let ItemVerdict::Accounted(accounted) = verdict else {
return "nothing here needs you".into();
};
match &reason {
Some(seen) if *seen != accounted => return "nothing here needs you".into(),
_ => reason = Some(accounted),
}
}
let _ = review;
reason.map_or_else(
luxe_core::guided_review::shared_reason(&app.review.budget, chapter).map_or_else(
|| "nothing here needs you".into(),
|accounted| format!("{} \u{2014} nothing here needs you", accounted.label()),
)

View File

@@ -93,6 +93,9 @@ pub(crate) struct UnitSignature {
pub(crate) selected: bool,
pub(crate) never_sent: bool,
pub(crate) expanded: bool,
/// The image store's [`layout_revision`](crate::graphics::ImageStore::layout_revision) for a
/// unit that draws an image, `None` for one that doesn't
pub(crate) images: Option<u64>,
}
/// One unit's rows, and what they were drawn against.

View File

@@ -3,7 +3,7 @@
use super::reveal::{rendered_chars, revealed_lines};
use super::rows::{append_banded_rows, folded_run_rows, Banded};
use super::{LayoutContext, TranscriptLayout, UnitSignature};
use crate::app::{App, ToolRunFold};
use crate::app::{App, ConversationItem, ConvoBlock, ToolRunFold};
use crate::view::{blocks, wrapping, ConversationCanvasWidths};
use ratatui::text::Line;
use std::rc::Rc;
@@ -154,6 +154,7 @@ fn layout_folded_run(
selected: app.selected_block.is_some_and(|index| range.contains(&index)),
never_sent: false,
expanded: false,
images: None,
};
// A run that is still working spins, so its line is different every tick and
// there is nothing about it a later frame could reuse.
@@ -189,10 +190,10 @@ fn layout_item(
selected: app.selected_block == Some(block_index),
never_sent: app.was_never_sent(item_id),
expanded: app.message_is_expanded(item_id),
images: image_revision(app, item),
};
// Anything that redraws on a clock of its own — a spinner, an image the store is still
// sizing — has nothing worth keeping between frames.
let volatile = draws_by_itself(app, item);
// A spinner redraws on a clock of its own, so there is nothing worth keeping between frames
let volatile = draws_by_itself(item);
let cached_chars = (!volatile).then(|| layout.reusable(&signature)).flatten();
// The reveal decides how much of an item to draw from its *rendered* character count, and
@@ -328,30 +329,37 @@ fn newest_revision(app: &App, range: std::ops::Range<usize>) -> crate::app::Bloc
.unwrap_or(crate::app::BlockRevision::ZERO)
}
/// Whether a block's own drawing moves without the transcript changing.
///
/// A working card spins, and an image is laid out against a store that may still be loading or
/// resizing it. Those units are rebuilt every frame, because there is nothing about them a later
/// frame could honestly reuse.
/// Whether a block's own drawing moves without the transcript changing: a working card spins.
/// Such a unit is rebuilt every frame, because there is nothing about it a later frame could reuse.
///
/// **Working**, not running: a call the model is still writing spins too, and the memo is keyed on
/// the card's revision — so a provider that delivers a tool call's arguments in one lump at the end
/// left the spinner frozen for the whole time it took to arrive, which reads worse than no spinner
/// at all.
fn draws_by_itself(app: &App, item: &crate::app::ConversationItem) -> bool {
fn draws_by_itself(item: &ConversationItem) -> bool {
match item.block() {
crate::app::ConvoBlock::Image { .. } => true,
crate::app::ConvoBlock::Tool(tool) => {
tool.activity.state.is_working()
|| app.tool_images.contains_key(&(
tool.activity.session_id.clone(),
tool.activity.call_id.clone(),
))
}
ConvoBlock::Tool(tool) => tool.activity.state.is_working(),
_ => false,
}
}
/// The image store's layout revision for an item that draws an image, `None` for one that
/// doesn't.
///
/// An image's rows depend on the store (its size, the tier, the cell geometry) as well as on the
/// item, so they are keyed on both. Rebuilding them every frame would cost a session with a
/// hundred screenshots a hundred card layouts a frame, wherever they sit.
fn image_revision(app: &App, item: &ConversationItem) -> Option<u64> {
let draws_image = match item.block() {
ConvoBlock::Image { .. } => true,
ConvoBlock::Tool(tool) => app
.tool_images
.contains_key(&(tool.activity.session_id.clone(), tool.activity.call_id.clone())),
_ => false,
};
draws_image.then(|| app.images.layout_revision())
}
/// True when a rendered line carries no visible content.
fn line_is_blank(line: &Line<'static>) -> bool {
line.spans.iter().all(|span| span.content.trim().is_empty())

View File

@@ -1,5 +1,6 @@
use super::*;
use crate::app::{ConversationItem, ConvoBlock};
use crate::app::{App, ConversationItem, ConvoBlock, ToolItem};
use crate::graphics::{CellSize, ImageKey, ImageOrigin};
fn signature(first: usize, revision: BlockRevision) -> UnitSignature {
UnitSignature {
@@ -12,6 +13,7 @@ fn signature(first: usize, revision: BlockRevision) -> UnitSignature {
selected: false,
never_sent: false,
expanded: false,
images: None,
}
}
@@ -121,7 +123,7 @@ fn a_changed_item_invalidates_only_itself() {
assert_eq!(text, ["a", "b", "b2"]);
}
/// A unit that redraws by itself — a spinner, an image, a row the reveal is still typing —
/// A unit that redraws by itself — a spinner, a row the reveal is still typing —
/// must never be served from the cache, however unchanged its signature looks.
#[test]
fn a_self_animating_unit_is_never_reused() {
@@ -175,6 +177,79 @@ fn a_shortened_transcript_drops_the_rows_it_lost() {
assert_eq!(layout.rows().len(), 1, "the popped item's row is gone");
}
/// An app with nothing in its transcript, and `key` in its image store.
fn app_holding(key: &ImageKey) -> App {
let (tx, _rx) = tokio::sync::mpsc::channel(4);
let config = luxe_core::config::Config::default();
let mut app = App::new(tx, luxe_core::keymap::KeyMap::defaults(), config);
let mut png = std::io::Cursor::new(Vec::new());
image::DynamicImage::new_rgba8(32, 16).write_to(&mut png, image::ImageFormat::Png).unwrap();
let origin = ImageOrigin { label: "screenshot".into(), path: None };
assert!(app.images.insert(key.clone(), png.into_inner(), origin));
app
}
/// An app whose transcript is one finished screenshot call, its image in the store.
fn app_with_screenshot() -> App {
let key = ImageKey::tool_result("s", "call-shot", 1);
let mut app = app_holding(&key);
let mut shot = luxe_core::ToolActivity::running("s", "call-shot", "screenshot", "url", 1);
shot.state = luxe_core::ToolActivityState::Succeeded;
let card =
ToolItem { activity: shot, expanded: false, details_toggled: false, waited_on_user_ms: 0 };
app.push_convo(ConvoBlock::Tool(Box::new(card)));
app.tool_images.insert(("s".into(), "call-shot".into()), vec![key]);
app
}
/// An app whose transcript is one attached image.
fn app_with_attached_image() -> App {
let key = ImageKey::new("attached");
let mut app = app_holding(&key);
app.push_convo(ConvoBlock::Image { key, width: 32, height: 16 });
app
}
/// One frame's layout of `app`'s transcript, as the rows' shared lines.
fn lay_out_frame(layout: &mut TranscriptLayout, app: &mut App) -> Vec<Rc<Line<'static>>> {
super::layout::lay_out_transcript(
layout,
app,
super::super::conversation_canvas_widths(120),
40,
);
layout.rows().iter().map(|row| Rc::clone(&row.line)).collect()
}
/// The break this catches: a card carrying an image rebuilt every frame, which in a session with a
/// hundred screenshots lays out a hundred cards a frame wherever they sit; or kept after the store
/// changes under it, drawing rows sized for the old geometry.
#[test]
fn an_image_card_is_reused_until_the_image_store_changes() {
assert_reused_until_the_store_changes(app_with_screenshot());
}
/// The break this catches: an attached image left out of the store's revision, so its rows
/// outlive a change of cell size or a cleared store.
#[test]
fn an_attached_image_is_reused_until_the_image_store_changes() {
assert_reused_until_the_store_changes(app_with_attached_image());
}
/// `app`'s only item is laid out once across unchanged frames, and again once the store moves.
fn assert_reused_until_the_store_changes(mut app: App) {
let mut layout = TranscriptLayout::default();
let first = lay_out_frame(&mut layout, &mut app);
let second = lay_out_frame(&mut layout, &mut app);
assert!(!first.is_empty(), "the card draws");
let reused = first.iter().zip(&second).all(|(a, b)| Rc::ptr_eq(a, b));
assert!(reused && first.len() == second.len(), "an unchanged frame reuses the card");
app.images.set_cell_size(CellSize { width: 7, height: 15 });
let third = lay_out_frame(&mut layout, &mut app);
assert!(!Rc::ptr_eq(&second[0], &third[0]), "a store change lays it out again");
}
/// Every field of the signature has to be part of the comparison, or the cache serves a stale
/// row the moment that one thing changes on its own. Flipping each in turn is the cheap way to
/// keep a future field from being added to the struct and forgotten in the equality.
@@ -182,7 +257,7 @@ fn a_shortened_transcript_drops_the_rows_it_lost() {
fn every_field_of_the_signature_is_part_of_the_comparison() {
let base = signature(3, BlockRevision::for_test(1));
type Mutation = (&'static str, fn(&mut UnitSignature));
let mutations: [Mutation; 9] = [
let mutations: [Mutation; 10] = [
("first", |s| s.first += 1),
("len", |s| s.len += 1),
("revision", |s| s.revision = BlockRevision::for_test(2)),
@@ -192,6 +267,7 @@ fn every_field_of_the_signature_is_part_of_the_comparison() {
("selected", |s| s.selected = !s.selected),
("never_sent", |s| s.never_sent = !s.never_sent),
("expanded", |s| s.expanded = !s.expanded),
("images", |s| s.images = Some(1)),
];
for (field, mutate) in mutations {
let mut changed = base;

View File

@@ -21,7 +21,9 @@ pub use card::{card, card_inner_width};
pub(crate) use fit::{elide_path_components, truncate_middle};
pub use fit::{truncate_end, truncate_start};
pub use gauge::fill_gauge;
pub use language_glyph::{language_hue, language_icon, GENERIC_LANGUAGE};
pub use language_glyph::{
language_hue, language_hue_role, language_icon, LanguageHue, GENERIC_LANGUAGE,
};
pub use panel::{
code_spans, footed_body, key_hint, key_hint_row, panel_block, panel_title, panel_title_width,
render_footed, render_footer, split_footer, titled_panel, FOOTER_ROWS, PANEL_BORDER_TYPE,
@@ -33,8 +35,8 @@ pub use slab::{
};
pub use tool_glyph::{tool_glyph, tool_icon, GENERIC_TOOL};
pub use wordmark::{
banner_frame_due, render_wordmark, smoothstep, BannerClock, Wordmark, WordmarkInk, BAND,
DRIFT_DEPTH, DRIFT_FRAME_TICKS, DRIFT_PERIOD_TICKS, LEAN, PEAK_DARK, PEAK_LIGHT,
banner_frame_due, render_wordmark, smoothstep, tile_png, BannerClock, Wordmark, WordmarkInk,
BAND, DRIFT_DEPTH, DRIFT_FRAME_TICKS, DRIFT_PERIOD_TICKS, LEAN, PEAK_DARK, PEAK_LIGHT,
SHINE_CYCLE_TICKS, SHINE_SWEEP_TICKS, STILL_TICK,
};
pub use wrap::{wrap_cells, wrap_line, wrap_lines, wrapped_row_starts};

View File

@@ -83,25 +83,58 @@ pub fn language_hue(
icon: Icon,
styles: &crate::theme::styles::ThemeStyles,
) -> ratatui::style::Style {
match language_hue_role(icon) {
LanguageHue::Warning => styles.warning,
LanguageHue::Info => styles.info,
LanguageHue::Success => styles.success,
LanguageHue::Error => styles.error,
LanguageHue::ThinkingUltra => styles.thinking_ultra,
LanguageHue::Text => styles.text,
LanguageHue::Muted => styles.muted,
}
}
/// The theme role a language's mark is colored by, for a surface that colors by role rather than
/// by a terminal's style: the phone app, whose stylesheet has a variable for each.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LanguageHue {
/// The theme's warning hue
Warning,
/// The theme's info hue
Info,
/// The theme's success hue
Success,
/// The theme's error hue
Error,
/// The deepest thinking level's hue
ThinkingUltra,
/// Body text
Text,
/// Muted text, for a mark with no known hue
Muted,
}
/// The role [`language_hue`] colors `icon` by.
pub fn language_hue_role(icon: Icon) -> LanguageHue {
match icon {
Icon::LangRust | Icon::LangSwift | Icon::LangZig => styles.warning,
Icon::LangPython | Icon::LangJavaScript | Icon::LangJson => styles.warning,
Icon::LangRust | Icon::LangSwift | Icon::LangZig => LanguageHue::Warning,
Icon::LangPython | Icon::LangJavaScript | Icon::LangJson => LanguageHue::Warning,
Icon::LangTypeScript
| Icon::LangGo
| Icon::LangC
| Icon::LangLua
| Icon::LangCss
| Icon::LangNix
| Icon::LangDocker => styles.info,
Icon::LangShell => styles.success,
| Icon::LangDocker => LanguageHue::Info,
Icon::LangShell => LanguageHue::Success,
Icon::LangRuby | Icon::LangJava | Icon::LangHtml | Icon::LangSvelte | Icon::LangToml => {
styles.error
LanguageHue::Error
}
Icon::LangCpp | Icon::LangPhp | Icon::LangKotlin | Icon::LangHaskell => {
styles.thinking_ultra
LanguageHue::ThinkingUltra
}
Icon::LangMarkdown => styles.text,
_ => styles.muted,
Icon::LangMarkdown => LanguageHue::Text,
_ => LanguageHue::Muted,
}
}

View File

@@ -24,6 +24,7 @@
mod art;
mod light;
mod tile;
use art::{column_groups, FULL_ART, LINE_ART, SMALL_ART};
pub use light::smoothstep;
@@ -34,6 +35,7 @@ use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;
use ratatui::Frame;
use std::sync::LazyLock;
pub use tile::tile_png;
/// Ticks for one full pass of the drift (~7s at the 33ms animation tick).
///

View File

@@ -0,0 +1,104 @@
//! Tile — the mark's square tile as a bitmap, for a phone's home screen.
//!
//! The same tile `examples/wordmark_svg.rs` writes as the website's favicon, from the same art: a
//! plate with the L on it, fit by height inside a sixteenth of padding and centered across. A home
//! screen takes only bitmaps, so this one is drawn to pixels at the size asked for.
use super::Wordmark;
use image::{ImageFormat, Rgb, RgbImage};
use std::io::Cursor;
/// A cell's width and height in drawing units, at the 1:2.2 a terminal draws, as the SVG twin has
/// them: the mark is recognized at those proportions.
const CELL_W: f64 = 10.0;
const CELL_H: f64 = 22.0;
/// The padding around the letter, as a share of the side: 32 of the favicon's 512.
const PAD_SHARE: f64 = 1.0 / 16.0;
/// The tile, `side` pixels square, with the L in `ink` on a `plate`, as PNG bytes.
pub fn tile_png(side: u32, plate: [u8; 3], ink: [u8; 3]) -> Result<Vec<u8>, image::ImageError> {
let mut canvas = RgbImage::from_pixel(side, side, Rgb(plate));
let cells = letter_cells();
let fit = Fit::new(side, &cells);
for cell in &cells {
paint(&mut canvas, fit.pixels(cell), Rgb(ink));
}
let mut png = Vec::new();
canvas.write_to(&mut Cursor::new(&mut png), ImageFormat::Png)?;
Ok(png)
}
/// One inked cell of the letter, in drawing units: where it starts and how tall its ink is.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Cell {
x: f64,
y: f64,
height: f64,
}
/// The L's cells: a full block inks its cell, a half block the top or bottom half of it.
fn letter_cells() -> Vec<Cell> {
let art = Wordmark::Full;
let in_letter = |column: usize| art.groups().get(column) == Some(&0);
let mut cells = Vec::new();
for (row, text) in art.rows().iter().enumerate() {
for (column, glyph) in text.chars().enumerate().filter(|(column, _)| in_letter(*column)) {
let (top, share) = match glyph {
'\u{2588}' => (0.0, 1.0),
'\u{2580}' => (0.0, 0.5),
'\u{2584}' => (0.5, 0.5),
_ => continue,
};
let (x, y) = (column as f64 * CELL_W, (row as f64 + top) * CELL_H);
cells.push(Cell { x, y, height: share * CELL_H });
}
}
cells
}
/// How the letter's drawing units land on the tile's pixels.
struct Fit {
scale: f64,
left: f64,
top: f64,
}
impl Fit {
/// Fit the art's height, the letter's taller axis, then center the ink across.
fn new(side: u32, cells: &[Cell]) -> Self {
let side = f64::from(side);
let pad = side * PAD_SHARE;
let height = Wordmark::Full.rows().len() as f64 * CELL_H;
let left = cells.iter().map(|cell| cell.x).fold(f64::INFINITY, f64::min);
let right = cells.iter().map(|cell| cell.x + CELL_W).fold(0.0, f64::max);
let scale = (side - pad * 2.0) / height;
Self { scale, left: (side - (right - left) * scale) / 2.0 - left * scale, top: pad }
}
/// The pixel columns and rows `cell` covers. Edges round the same way on both sides of a
/// boundary, so neighbors meet with no seam between them.
fn pixels(&self, cell: &Cell) -> (std::ops::Range<u32>, std::ops::Range<u32>) {
let at = |units: f64, origin: f64| (origin + units * self.scale).round() as u32;
let columns = at(cell.x, self.left)..at(cell.x + CELL_W, self.left);
let rows = at(cell.y, self.top)..at(cell.y + cell.height, self.top);
(columns, rows)
}
}
fn paint(
canvas: &mut RgbImage,
(columns, rows): (std::ops::Range<u32>, std::ops::Range<u32>),
ink: Rgb<u8>,
) {
for y in rows {
for x in columns.clone() {
if x < canvas.width() && y < canvas.height() {
canvas.put_pixel(x, y, ink);
}
}
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,112 @@
use super::*;
const PLATE: [u8; 3] = [0x12, 0x10, 0x0e];
const INK: [u8; 3] = [0xdd, 0xc0, 0x84];
fn drawn(side: u32) -> RgbImage {
let png = tile_png(side, PLATE, INK).expect("the tile encodes");
image::load_from_memory_with_format(&png, ImageFormat::Png).expect("a PNG").to_rgb8()
}
/// The columns that hold any ink, first and last.
fn inked_columns(canvas: &RgbImage) -> (u32, u32) {
let inked: Vec<u32> = (0..canvas.width())
.filter(|&x| (0..canvas.height()).any(|y| canvas.get_pixel(x, y).0 == INK))
.collect();
(inked[0], *inked.last().expect("some ink"))
}
/// The break this catches: the size asked for not being the size drawn, which a home screen
/// scales into a blur.
#[test]
fn the_tile_is_drawn_at_the_size_asked_for() {
for side in [180, 192, 512] {
let canvas = drawn(side);
assert_eq!((canvas.width(), canvas.height()), (side, side));
assert_eq!(canvas.get_pixel(0, 0).0, PLATE, "a corner is the plate at {side}");
}
}
/// The break this catches: the letter scaled past its padding, or set off center, so the icon
/// crops it or leans to one side.
#[test]
fn the_letter_sits_inside_its_padding_and_centered() {
let canvas = drawn(512);
let pad = 32;
let row_has_ink = |y: u32| (0..512).any(|x| canvas.get_pixel(x, y).0 == INK);
assert!(!(0..pad).any(row_has_ink), "ink in the top padding");
assert!(!(512 - pad..512).any(row_has_ink), "ink in the bottom padding");
let (first, last) = inked_columns(&canvas);
let (left, right) = (first, 511 - last);
assert!(left.abs_diff(right) <= 1, "margins {left} and {right}");
}
/// The break this catches: the letter scaled to other than the favicon's 32-of-512 padding, so
/// the home screen's L is a different size from the browser tab's.
#[test]
fn the_art_fills_the_favicons_box() {
let canvas = drawn(512);
let rows = Wordmark::Full.rows().len() as f64;
let scale = (512.0 - 2.0 * 32.0) / (rows * CELL_H);
let cells = letter_cells();
let top = cells.iter().map(|cell| cell.y).fold(f64::INFINITY, f64::min);
let first_inked_row = (0..512).find(|&y| (0..512).any(|x| canvas.get_pixel(x, y).0 == INK));
assert_eq!(first_inked_row, Some((32.0 + top * scale).round() as u32));
}
/// The break this catches: a glyph the art draws with missing from the tile, a half block drawn
/// whole, or the upper and lower halves crossed. Each of the letter's cells is read in the art
/// and sampled in both halves of where it lands.
#[test]
fn every_cell_of_the_letter_is_drawn_as_the_art_has_it() {
let canvas = drawn(512);
let fit = Fit::new(512, &letter_cells());
let art = Wordmark::Full;
for (row, text) in art.rows().iter().enumerate() {
for (column, glyph) in text.chars().enumerate() {
if art.groups().get(column) != Some(&0) {
continue;
}
let drawn = (
inked(&canvas, &fit, column, row as f64),
inked(&canvas, &fit, column, row as f64 + 0.5),
);
assert_eq!(drawn, halves(glyph), "{glyph:?} at row {row}, column {column}");
}
}
}
/// Which halves of its cell `glyph` inks, top then bottom.
fn halves(glyph: char) -> (bool, bool) {
match glyph {
'\u{2588}' => (true, true),
'\u{2580}' => (true, false),
'\u{2584}' => (false, true),
_ => (false, false),
}
}
/// Whether the middle of the half cell at `column` and `row` (in rows, a half step for the
/// bottom) is drawn in ink.
fn inked(canvas: &RgbImage, fit: &Fit, column: usize, row: f64) -> bool {
let cell = Cell { x: column as f64 * CELL_W, y: row * CELL_H, height: CELL_H / 2.0 };
let (columns, rows) = fit.pixels(&cell);
let middle = |range: std::ops::Range<u32>| (range.start + range.end) / 2;
canvas.get_pixel(middle(columns), middle(rows)).0 == INK
}
/// The break this catches: the L read from the wrong columns, or a kind of block skipped, so the
/// tile draws a different letter than the terminal and the favicon do.
#[test]
fn the_letter_is_every_inked_cell_of_the_first_group() {
let art = Wordmark::Full;
let inked = art
.rows()
.iter()
.flat_map(|row| row.chars().enumerate())
.filter(|(column, glyph)| art.groups().get(*column) == Some(&0) && *glyph != ' ')
.count();
let cells = letter_cells();
assert_eq!(cells.len(), inked);
assert!(cells.iter().any(|cell| cell.height < CELL_H), "the L has a half block");
}