Luxe 0.1.2: Windows fixes, working compaction, and compaction progress in the dock
This commit is contained in:
@@ -8,7 +8,7 @@ repository.workspace = true
|
||||
homepage.workspace = true
|
||||
|
||||
[dependencies]
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.1" }
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.2" }
|
||||
# `unstable-rendered-line-info` enables Paragraph::line_count, used for precise wrapping-aware
|
||||
# mouse hit-testing over word-wrapped surfaces (guide/dock/conversation clicks). It adds no crate;
|
||||
# the API is marked unstable upstream but is stable within our pinned minor (re-check on upgrade).
|
||||
|
||||
@@ -167,11 +167,8 @@ pub struct App {
|
||||
pub plan_written: Option<String>,
|
||||
/// The id of the question modal when it is the plan's handoff, which the TUI answers itself
|
||||
pub plan_handoff: Option<luxe_core::question::QuestionRequestId>,
|
||||
/// What to send once a fresh session has loaded: the plan, built from scratch
|
||||
pub pending_build: Option<String>,
|
||||
/// Whether the composer's draft goes out once a fresh session has loaded — a prompt typed on
|
||||
/// the start screen, waiting for the session it asked for
|
||||
pub send_draft_on_load: bool,
|
||||
/// What waits on the session this TUI last asked the engine for
|
||||
pub(crate) arrival: navigation::SessionArrival,
|
||||
pub file_provider: crate::ref_provider::FileRefProvider,
|
||||
/// The `@` picker's file list being read again, off the render thread
|
||||
pub file_listing: FileListing,
|
||||
|
||||
@@ -157,6 +157,7 @@ impl App {
|
||||
self.refresh_configuration();
|
||||
}
|
||||
WizardOutcome::Finished(outcome) => self.finish_login(*outcome),
|
||||
WizardOutcome::CopyCode(code) => self.record_copy(code),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -98,8 +98,7 @@ impl App {
|
||||
mention_listings: Default::default(),
|
||||
plan_written: None,
|
||||
plan_handoff: None,
|
||||
pending_build: None,
|
||||
send_draft_on_load: false,
|
||||
arrival: Default::default(),
|
||||
permission_auto_approve: false,
|
||||
file_provider,
|
||||
file_listing: FileListing::default(),
|
||||
|
||||
@@ -8,6 +8,7 @@ use super::{App, ConvoBlock};
|
||||
use luxe_core::config::NotificationEvent;
|
||||
use luxe_core::event::Event;
|
||||
|
||||
mod compaction;
|
||||
mod github;
|
||||
mod review;
|
||||
mod transcript;
|
||||
@@ -116,16 +117,11 @@ 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::CompactionDone { tokens_before, tokens_after } => {
|
||||
use luxe_core::usage::format_tokens;
|
||||
// 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)
|
||||
)));
|
||||
compaction::done(app, tokens_before, tokens_after);
|
||||
}
|
||||
Event::CompactionStopped => compaction::ended(app),
|
||||
Event::WorkspaceUpdated(snapshot) => workspace_updated(app, *snapshot),
|
||||
Event::ToolActivityUpdated(activity) => app.apply_tool_activity(*activity),
|
||||
Event::PermissionRequested { id, tool, summary, always_patterns, .. } => {
|
||||
|
||||
40
crates/luxe-tui/src/app/events/compaction.rs
Normal file
40
crates/luxe-tui/src/app/events/compaction.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
//! Compaction — the dock while a summary is written, and its reading once one stands.
|
||||
//!
|
||||
//! 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.
|
||||
|
||||
use super::super::{App, AppState, ConvoBlock};
|
||||
|
||||
/// The engine began writing a summary.
|
||||
pub(super) fn started(app: &mut App) {
|
||||
app.status.compacting_mid_turn = matches!(app.status.state, AppState::Streaming);
|
||||
app.status.state = AppState::Compacting;
|
||||
}
|
||||
|
||||
/// 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;
|
||||
app.status.context_pct = used.min(100.0);
|
||||
}
|
||||
// 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)
|
||||
)));
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
if !matches!(app.status.state, AppState::Compacting) {
|
||||
return;
|
||||
}
|
||||
app.status.state =
|
||||
if app.status.compacting_mid_turn { AppState::Streaming } else { AppState::Idle };
|
||||
}
|
||||
@@ -109,6 +109,8 @@ pub(super) fn failed(app: &mut App, msg: String) {
|
||||
/// A prompt can't outlive its turn (the engine already resolved or dropped it), and a card still
|
||||
/// spinning is settled as cancelled with `reason`.
|
||||
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;
|
||||
app.interrupt_sent_at = None;
|
||||
app.streaming = false;
|
||||
app.streamed_thinking = false;
|
||||
@@ -132,7 +134,12 @@ pub(super) fn tool_started(app: &mut App, name: String) {
|
||||
}
|
||||
|
||||
pub(super) fn state_changed(app: &mut App, state: EngineState) {
|
||||
app.status.state = if state.streaming { AppState::Streaming } else { AppState::Idle };
|
||||
// The load's own snapshot was taken before the turn its `SessionLoaded` sent, so its idle is
|
||||
// about a moment that has passed; believed, it hides the running turn until the first token
|
||||
let stale = std::mem::take(&mut app.arrival.owes_snapshot) && app.turn_in_flight();
|
||||
if !stale {
|
||||
follow_reported_activity(app, state.streaming);
|
||||
}
|
||||
if !state.model.model.is_empty() {
|
||||
app.status.model = state.model.display().to_string();
|
||||
app.status.provider = state.model.provider.clone();
|
||||
@@ -142,7 +149,16 @@ pub(super) fn state_changed(app: &mut App, state: EngineState) {
|
||||
// Not marked in the transcript: the composer's title, the bar and the dock say which
|
||||
// mode is on, and a line per switch would fill the scrollback with every toggle
|
||||
app.status.mode = state.mode.clone();
|
||||
if !state.streaming {
|
||||
}
|
||||
|
||||
/// Takes the engine's word on whether a turn is running. A turn that is still running leaves a
|
||||
/// compaction inside it on show: the summary is the turn's work until its own end event lands.
|
||||
fn follow_reported_activity(app: &mut App, streaming: bool) {
|
||||
if streaming && matches!(app.status.state, AppState::Compacting) {
|
||||
return;
|
||||
}
|
||||
app.status.state = if streaming { AppState::Streaming } else { AppState::Idle };
|
||||
if !streaming {
|
||||
app.status.active_tool = None;
|
||||
app.status.tool_started = None;
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ fn ask_in_a_new_session(app: &mut App) {
|
||||
return;
|
||||
}
|
||||
start_new_session(app);
|
||||
app.send_draft_on_load = true;
|
||||
app.arrival.send_draft = true;
|
||||
}
|
||||
|
||||
/// Runs a command typed or found on the start screen.
|
||||
@@ -167,10 +167,24 @@ impl App {
|
||||
NextSession::Load(session_id) => (Action::LoadSession(session_id), "load a session"),
|
||||
NextSession::ResumeLatest => (Action::ResumeLatest, "resume the latest session"),
|
||||
};
|
||||
self.send_action(action, doing)
|
||||
let sent = self.send_action(action, doing);
|
||||
self.arrival.owes_snapshot = sent;
|
||||
sent
|
||||
}
|
||||
}
|
||||
|
||||
/// What waits on a session the TUI asked the engine for, settled as it arrives.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct SessionArrival {
|
||||
/// The plan's build prompt, built from scratch in the new session
|
||||
pub(crate) build: Option<String>,
|
||||
/// Whether the composer's draft goes out once it loads: a prompt typed on the start screen
|
||||
pub(crate) send_draft: bool,
|
||||
/// Whether its closing state snapshot is still to come. It trails `SessionLoaded`, which may
|
||||
/// already have sent a turn, so its "idle" is stale
|
||||
pub(crate) owes_snapshot: bool,
|
||||
}
|
||||
|
||||
/// Where `/sessions` reads the project's sessions from, and how many reads it has asked for.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct SessionCatalog {
|
||||
|
||||
@@ -64,7 +64,8 @@ pub(super) fn answered(app: &mut App, answers: Option<Vec<String>>) {
|
||||
// Sent once the new session has loaded, or it would land in the one being left; parked
|
||||
// only once there is a new session coming to send it to
|
||||
if app.send_action(Action::NewSession, "start a new session") {
|
||||
app.pending_build = Some(build);
|
||||
app.arrival.build = Some(build);
|
||||
app.arrival.owes_snapshot = true;
|
||||
}
|
||||
}
|
||||
RUN_AS_LOOP => {
|
||||
@@ -87,11 +88,11 @@ pub(super) fn answered(app: &mut App, answers: Option<Vec<String>>) {
|
||||
pub(super) fn session_loaded(app: &mut App) {
|
||||
// a plan another session wrote is not this session's to offer
|
||||
app.plan_written = None;
|
||||
if let Some(build) = app.pending_build.take() {
|
||||
if let Some(build) = app.arrival.build.take() {
|
||||
submit(app, &build);
|
||||
}
|
||||
// A prompt typed on the start screen, which asked for this session to answer it
|
||||
if std::mem::take(&mut app.send_draft_on_load) {
|
||||
if std::mem::take(&mut app.arrival.send_draft) {
|
||||
super::input::submit_prompt(app);
|
||||
}
|
||||
}
|
||||
@@ -137,7 +138,7 @@ mod tests {
|
||||
fn building_fresh_parks_nothing_when_no_session_is_coming() {
|
||||
let mut app = seeded_app("nord", FixtureScenario::ChatIdle).unwrap();
|
||||
answered(&mut app, Some(vec![BUILD_FRESH.to_string()]));
|
||||
assert_eq!(app.pending_build, None);
|
||||
assert_eq!(app.arrival.build, None);
|
||||
}
|
||||
|
||||
/// Building fresh asks for a new session and sends the build prompt once that session loads.
|
||||
@@ -147,11 +148,12 @@ mod tests {
|
||||
answered(&mut app, Some(vec![BUILD_FRESH.to_string()]));
|
||||
let asked: Vec<Action> = std::iter::from_fn(|| engine.try_recv().ok()).collect();
|
||||
assert!(asked.iter().any(|action| matches!(action, Action::NewSession)), "{asked:?}");
|
||||
assert!(app.pending_build.is_some());
|
||||
assert!(app.arrival.build.is_some());
|
||||
|
||||
let loaded = Event::SessionLoaded { session_id: "fresh".into(), messages: Vec::new() };
|
||||
app.update(crate::app::Msg::Engine(loaded));
|
||||
assert!(app.pending_build.is_none(), "sent into the session that loaded");
|
||||
assert!(app.arrival.build.is_none(), "sent into the session that loaded");
|
||||
assert!(app.arrival.owes_snapshot, "and the load's closing snapshot is known to be stale");
|
||||
let sent: Vec<Action> = std::iter::from_fn(|| engine.try_recv().ok()).collect();
|
||||
let submitted = sent.iter().any(|action| {
|
||||
matches!(action, Action::SubmitUserMessage { content, .. } if content.contains("Build the plan"))
|
||||
|
||||
@@ -23,6 +23,9 @@ pub struct StatusModel {
|
||||
pub active_tool: Option<String>,
|
||||
/// Current state (streaming, idle, compacting).
|
||||
pub state: AppState,
|
||||
/// 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,
|
||||
/// 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
|
||||
@@ -101,6 +104,7 @@ impl Default for StatusModel {
|
||||
cwd: None,
|
||||
active_tool: None,
|
||||
state: AppState::Idle,
|
||||
compacting_mid_turn: false,
|
||||
spinner_frame: 0,
|
||||
animating: false,
|
||||
turn_started: None,
|
||||
|
||||
@@ -262,6 +262,42 @@ fn a_prompt_typed_on_the_start_screen_is_sent_in_the_new_session() {
|
||||
assert!(app.editor.current_input().is_empty(), "and it left the composer");
|
||||
}
|
||||
|
||||
/// The turn a start-screen prompt starts shows as running from the moment it is sent.
|
||||
///
|
||||
/// The engine finishes a session load with an idle snapshot *after* `SessionLoaded`, which is what
|
||||
/// sends the draft, so that snapshot lands on a turn it never saw. The break this catches: taking it
|
||||
/// at its word hid the activity bar and the clock until the model's first token, a second or two
|
||||
/// of a screen that looked like nothing had happened.
|
||||
#[test]
|
||||
fn the_snapshot_finishing_a_load_does_not_stop_the_turn_the_load_started() {
|
||||
let (tx, _rx) = mpsc::channel(100);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Default::default());
|
||||
app.status.model = "qwen3.8-27b".into();
|
||||
app.enter_dashboard(crate::dashboard::DashboardState::new(Vec::new()));
|
||||
app.editor.insert_text("summarize the parser");
|
||||
app.handle_dashboard_outcome(crate::dashboard::DashOutcome::Ask);
|
||||
|
||||
app.update(Msg::Engine(Event::SessionLoaded { session_id: "s1".into(), messages: vec![] }));
|
||||
app.update(Msg::Engine(idle_snapshot("new session: s1")));
|
||||
assert!(crate::statusline::activity_parts(&app).is_some(), "the activity bar stays up");
|
||||
assert!(app.status.turn_started.is_some(), "and so does the clock");
|
||||
|
||||
// Only the one snapshot is stale: a later idle report is believed
|
||||
app.update(Msg::Engine(idle_snapshot("cancelled")));
|
||||
assert!(crate::statusline::activity_parts(&app).is_none(), "a later report still counts");
|
||||
}
|
||||
|
||||
/// The engine's at-rest state report, as it closes a session load or a cancel.
|
||||
fn idle_snapshot(status: &str) -> Event {
|
||||
Event::StateChanged(luxe_core::event::EngineState {
|
||||
model: luxe_core::event::ModelRef::new("lmstudio", "qwen3.8-27b"),
|
||||
streaming: false,
|
||||
status: status.into(),
|
||||
mode: luxe_core::mode::BUILD.into(),
|
||||
thinking: luxe_core::provider::ThinkingLevel::Off,
|
||||
})
|
||||
}
|
||||
|
||||
/// With no model chosen, asking opens the picker over the start screen and keeps the draft — the
|
||||
/// same courtesy the composer extends in a session.
|
||||
#[test]
|
||||
|
||||
@@ -346,6 +346,56 @@ fn test_status_model_format_cost() {
|
||||
assert_eq!(StatusModel::format_cost(Some(0.004)), "<$0.01");
|
||||
}
|
||||
|
||||
fn idle_app() -> App {
|
||||
let (tx, _rx) = mpsc::channel(8);
|
||||
App::new(tx, luxe_core::keymap::KeyMap::defaults(), luxe_core::config::Config::default())
|
||||
}
|
||||
|
||||
fn engine_reports_streaming(app: &mut App, streaming: bool) {
|
||||
app.update(Msg::Engine(Event::StateChanged(luxe_core::event::EngineState {
|
||||
streaming,
|
||||
..Default::default()
|
||||
})));
|
||||
}
|
||||
|
||||
/// `/compact` shows as under way, and its end leaves the dock idle reading what the summary left.
|
||||
///
|
||||
/// The break this catches: nothing set the compacting state, so `/compact` showed no sign of life
|
||||
/// for the minute a summary takes, and the context figure stayed full until the next turn.
|
||||
#[tokio::test]
|
||||
async fn compact_on_request_shows_while_it_runs_and_refreshes_the_context_reading() {
|
||||
let mut app = idle_app();
|
||||
app.update(Msg::Engine(Event::ContextUsage { used_tokens: 190_000, context_window: 200_000 }));
|
||||
app.update(Msg::Engine(Event::CompactionStarted { tokens_before: 190_000 }));
|
||||
assert!(matches!(app.status.state, AppState::Compacting), "{:?}", app.status.state);
|
||||
|
||||
app.update(Msg::Engine(Event::CompactionDone { tokens_before: 190_000, tokens_after: 20_000 }));
|
||||
assert!(matches!(app.status.state, AppState::Idle), "{:?}", app.status.state);
|
||||
assert!((app.status.context_pct - 10.0).abs() < 0.01, "got {}", app.status.context_pct);
|
||||
}
|
||||
|
||||
/// A compaction inside a turn hands the dock back to the turn, whether or not it succeeded.
|
||||
#[tokio::test]
|
||||
async fn a_stopped_compaction_mid_turn_returns_to_the_turn() {
|
||||
let mut app = idle_app();
|
||||
engine_reports_streaming(&mut app, true);
|
||||
app.update(Msg::Engine(Event::CompactionStarted { tokens_before: 190_000 }));
|
||||
app.update(Msg::Engine(Event::CompactionStopped));
|
||||
assert!(matches!(app.status.state, AppState::Streaming), "{:?}", app.status.state);
|
||||
}
|
||||
|
||||
/// The engine's turn reports leave a compaction on show while the turn runs, and end it with the turn.
|
||||
#[tokio::test]
|
||||
async fn turn_reports_keep_a_compaction_on_show_until_the_turn_ends() {
|
||||
let mut app = idle_app();
|
||||
engine_reports_streaming(&mut app, true);
|
||||
app.update(Msg::Engine(Event::CompactionStarted { tokens_before: 190_000 }));
|
||||
engine_reports_streaming(&mut app, true);
|
||||
assert!(matches!(app.status.state, AppState::Compacting), "{:?}", app.status.state);
|
||||
engine_reports_streaming(&mut app, false);
|
||||
assert!(matches!(app.status.state, AppState::Idle), "{:?}", app.status.state);
|
||||
}
|
||||
|
||||
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)));
|
||||
|
||||
@@ -123,6 +123,8 @@ pub enum WizardOutcome {
|
||||
Close,
|
||||
/// A credential landed. Args: `(outcome)`. The app closes the wizard and picks a model.
|
||||
Finished(Box<LoginOutcome>),
|
||||
/// Put the device code on the clipboard, which the app owns. Args: `(code)`.
|
||||
CopyCode(String),
|
||||
/// Key consumed; the wizard stays as it is.
|
||||
Consumed,
|
||||
}
|
||||
@@ -224,6 +226,17 @@ impl AuthWizardState {
|
||||
self.pending_prompt().is_some()
|
||||
}
|
||||
|
||||
/// The device code the flow is waiting to be entered, while nothing else is being asked.
|
||||
pub fn device_code(&self) -> Option<&str> {
|
||||
if self.pending.is_some() {
|
||||
return None;
|
||||
}
|
||||
self.lines().iter().rev().find_map(|line| match line {
|
||||
WizardLine::DeviceCode { code, .. } => Some(code.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Transcript lines of a running (or finished) flow.
|
||||
pub fn lines(&self) -> &[WizardLine] {
|
||||
match &self.stage {
|
||||
@@ -305,10 +318,12 @@ impl AuthWizardState {
|
||||
}
|
||||
|
||||
fn running_key(&mut self, key: &KeyEvent) -> WizardOutcome {
|
||||
let code = self.device_code().map(str::to_string);
|
||||
let Some(current) = self.pending.as_mut() else {
|
||||
// Nothing to answer: Esc aborts the flow, everything else waits.
|
||||
return match key.code {
|
||||
KeyCode::Esc => WizardOutcome::Close,
|
||||
// Nothing to answer: Esc aborts the flow, `c` copies a code to enter, the rest waits
|
||||
return match (key.code, code) {
|
||||
(KeyCode::Esc, _) => WizardOutcome::Close,
|
||||
(KeyCode::Char('c'), Some(code)) => WizardOutcome::CopyCode(code),
|
||||
_ => WizardOutcome::Consumed,
|
||||
};
|
||||
};
|
||||
@@ -455,6 +470,8 @@ mod tests_support {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod click_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
|
||||
114
crates/luxe-tui/src/auth_wizard/click_tests.rs
Normal file
114
crates/luxe-tui/src/auth_wizard/click_tests.rs
Normal file
@@ -0,0 +1,114 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::tests_support::*;
|
||||
use super::*;
|
||||
use crate::mouse::{HitRegions, MouseTarget};
|
||||
use ratatui::{backend::TestBackend, buffer::Buffer, Terminal};
|
||||
use std::cell::RefCell;
|
||||
|
||||
fn theme() -> crate::theme::styles::ThemeStyles {
|
||||
let resolved = luxe_core::theme::ThemeRegistry::new().resolve("dark").expect("dark resolves");
|
||||
crate::theme::styles::ThemeStyles::from_resolved(&resolved, "dark")
|
||||
}
|
||||
|
||||
/// The wizard drawn as `/login` draws it, with what each cell would be hit as.
|
||||
fn draw(wizard: &AuthWizardState) -> (Buffer, RefCell<HitRegions>) {
|
||||
let hit = RefCell::new(HitRegions::default());
|
||||
let mut terminal = Terminal::new(TestBackend::new(90, 32)).unwrap();
|
||||
terminal.draw(|frame| wizard.view(frame, frame.area(), &theme(), &hit)).unwrap();
|
||||
(terminal.backend().buffer().clone(), hit)
|
||||
}
|
||||
|
||||
/// Where `needle` is drawn, as `(column, row)`.
|
||||
fn cell_of(buffer: &Buffer, needle: &str) -> (u16, u16) {
|
||||
for y in 0..buffer.area.height {
|
||||
let row: String = (0..buffer.area.width).map(|x| buffer[(x, y)].symbol()).collect();
|
||||
if let Some(byte) = row.find(needle) {
|
||||
return (row[..byte].chars().count() as u16, y);
|
||||
}
|
||||
}
|
||||
panic!("{needle} is not drawn");
|
||||
}
|
||||
|
||||
/// A running sign-in asking which GitHub, as Copilot's does.
|
||||
fn asking_which_github(
|
||||
) -> (AuthWizardState, tokio::sync::oneshot::Receiver<Result<SecretString, AuthError>>) {
|
||||
let mut wizard = AuthWizardState::open(providers(), LoginScope::Any);
|
||||
wizard.on_key(&key(KeyCode::Enter));
|
||||
let (reply, answer) = tokio::sync::oneshot::channel();
|
||||
let choice = |id: &str, label: &str, detail: &str| AuthChoice {
|
||||
id: id.into(),
|
||||
label: label.into(),
|
||||
detail: Some(detail.into()),
|
||||
};
|
||||
let choices = vec![
|
||||
choice("github", "GitHub", "github.com"),
|
||||
choice("enterprise", "GitHub Enterprise", "your company's server"),
|
||||
];
|
||||
wizard.apply(AuthUiMsg::Prompt { prompt: AuthPrompt::select("Which GitHub?", choices), reply });
|
||||
(wizard, answer)
|
||||
}
|
||||
|
||||
/// Each choice of a question the sign-in asks is clickable where it is drawn, its detail line
|
||||
/// included, as the provider and method lists are. It used to draw without registering anywhere,
|
||||
/// so a click on "GitHub" did nothing.
|
||||
#[test]
|
||||
fn a_question_s_choices_are_clickable_where_they_are_drawn() {
|
||||
let (wizard, _answer) = asking_which_github();
|
||||
let (buffer, hit) = draw(&wizard);
|
||||
let (x, y) = cell_of(&buffer, "GitHub Enterprise");
|
||||
assert_eq!(hit.borrow().at(x, y), Some(&MouseTarget::AuthMethodRow(1)));
|
||||
let (x, y) = cell_of(&buffer, "your company's server");
|
||||
assert_eq!(hit.borrow().at(x, y), Some(&MouseTarget::AuthMethodRow(1)), "the detail line too");
|
||||
let (x, y) = cell_of(&buffer, "github.com");
|
||||
assert_eq!(hit.borrow().at(x, y), Some(&MouseTarget::AuthMethodRow(0)));
|
||||
}
|
||||
|
||||
/// A click lands as the keyboard would: the row it hit becomes the answer.
|
||||
#[tokio::test]
|
||||
async fn a_clicked_choice_is_the_answer() {
|
||||
let (mut wizard, answer) = asking_which_github();
|
||||
wizard.select_method(1);
|
||||
wizard.on_key(&key(KeyCode::Enter));
|
||||
let chosen = answer.await.unwrap().unwrap();
|
||||
assert_eq!(secrecy::ExposeSecret::expose_secret(&chosen), "enterprise");
|
||||
}
|
||||
|
||||
/// A sign-in waiting on a device code offers it to copy, by click or by `c`, and says so.
|
||||
#[test]
|
||||
fn a_waiting_device_code_can_be_copied() {
|
||||
let mut wizard = AuthWizardState::open(providers(), LoginScope::Any);
|
||||
wizard.on_key(&key(KeyCode::Enter));
|
||||
wizard.apply(AuthUiMsg::Event(AuthEvent::DeviceCode {
|
||||
user_code: "WXYZ-9876".into(),
|
||||
verification_uri: "https://github.com/login/device".into(),
|
||||
expires_in_secs: 900,
|
||||
interval_secs: 5,
|
||||
}));
|
||||
let (buffer, hit) = draw(&wizard);
|
||||
let (x, y) = cell_of(&buffer, "Copy code WXYZ-9876");
|
||||
assert_eq!(hit.borrow().at(x, y), Some(&MouseTarget::AuthCopyCode));
|
||||
cell_of(&buffer, "c copy code");
|
||||
match wizard.on_key(&key(KeyCode::Char('c'))) {
|
||||
WizardOutcome::CopyCode(code) => assert_eq!(code, "WXYZ-9876"),
|
||||
other => panic!("expected the code to copy, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// While the flow is asking something, `c` is a letter of the answer, not a copy.
|
||||
#[test]
|
||||
fn c_types_into_a_question_rather_than_copying() {
|
||||
let mut wizard = AuthWizardState::open(providers(), LoginScope::Any);
|
||||
wizard.on_key(&key(KeyCode::Enter));
|
||||
wizard.apply(AuthUiMsg::Event(AuthEvent::DeviceCode {
|
||||
user_code: "WXYZ-9876".into(),
|
||||
verification_uri: "https://github.com/login/device".into(),
|
||||
expires_in_secs: 900,
|
||||
interval_secs: 5,
|
||||
}));
|
||||
let (reply, _answer) = tokio::sync::oneshot::channel();
|
||||
wizard.apply(AuthUiMsg::Prompt { prompt: AuthPrompt::text("Domain:", None), reply });
|
||||
assert!(matches!(wizard.on_key(&key(KeyCode::Char('c'))), WizardOutcome::Consumed));
|
||||
assert_eq!(wizard.pending_prompt().map(|(_, typed)| typed), Some("c"));
|
||||
assert_eq!(wizard.device_code(), None, "no button while a question is up");
|
||||
}
|
||||
@@ -79,7 +79,7 @@ impl AuthWizardState {
|
||||
Stage::Provider { query, .. } => self.render_providers(frame, inner, query, theme, hit),
|
||||
Stage::Method { .. } => self.render_methods(frame, inner, theme, hit),
|
||||
Stage::Running { provider, lines } => {
|
||||
self.render_running(frame, inner, provider, lines, theme)
|
||||
self.render_running(frame, inner, (provider, lines), theme, hit)
|
||||
}
|
||||
Stage::Failed(message) => self.render_failed(frame, inner, message, theme),
|
||||
}
|
||||
@@ -93,6 +93,7 @@ impl AuthWizardState {
|
||||
Stage::Running { .. } => match self.pending_prompt().map(|(prompt, _)| &prompt.kind) {
|
||||
Some(AuthPromptKind::Select(_)) => "enter confirm · ↑/↓ choose · esc cancel",
|
||||
Some(_) => "enter confirm · esc cancel",
|
||||
None if self.device_code().is_some() => "c copy code · esc cancel",
|
||||
None => "Working… · esc cancel",
|
||||
},
|
||||
Stage::Failed(_) => "r try again · esc close",
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
use super::*;
|
||||
|
||||
impl AuthWizardState {
|
||||
/// Rows the pending question needs, or zero when nothing is being asked.
|
||||
/// Rows the pending question needs, the copy-code button's while a code waits to be entered,
|
||||
/// or zero.
|
||||
pub(super) fn prompt_height(&self) -> u16 {
|
||||
match self.pending_prompt() {
|
||||
// A blank line, the question, and what each choice takes.
|
||||
@@ -12,6 +13,8 @@ impl AuthWizardState {
|
||||
// A blank line, the question, and the input row.
|
||||
_ => 3,
|
||||
},
|
||||
// A blank line and the button
|
||||
None if self.device_code().is_some() => 2,
|
||||
None => 0,
|
||||
}
|
||||
}
|
||||
@@ -20,9 +23,9 @@ impl AuthWizardState {
|
||||
&self,
|
||||
frame: &mut Frame,
|
||||
inner: Rect,
|
||||
provider: &str,
|
||||
lines: &[WizardLine],
|
||||
(provider, lines): (&str, &[WizardLine]),
|
||||
theme: &ThemeStyles,
|
||||
hit: &std::cell::RefCell<HitRegions>,
|
||||
) {
|
||||
let prompt = self.pending_prompt();
|
||||
let prompt_height = self.prompt_height();
|
||||
@@ -47,6 +50,9 @@ impl AuthWizardState {
|
||||
|
||||
let Some((prompt, input)) = prompt else {
|
||||
park_cursor(frame, inner);
|
||||
if let Some(code) = self.device_code() {
|
||||
render_copy_code(frame, chunks[2], code, theme, hit);
|
||||
}
|
||||
return;
|
||||
};
|
||||
let mut rows: Vec<Line> = vec![
|
||||
@@ -59,6 +65,7 @@ impl AuthWizardState {
|
||||
match &prompt.kind {
|
||||
AuthPromptKind::Select(choices) => {
|
||||
rows.extend(self.prompt_choice_lines(choices, chunks[2], theme));
|
||||
publish_choice_rows(choices, chunks[2], hit);
|
||||
}
|
||||
kind => rows.push(prompt_input_line(prompt, kind, input, theme)),
|
||||
}
|
||||
@@ -124,6 +131,43 @@ impl AuthWizardState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes each choice clickable over every row it draws, its detail line included, under the blank
|
||||
/// line and the question. A click highlights the row and then answers, as Enter would.
|
||||
fn publish_choice_rows(
|
||||
choices: &[luxe_core::auth::AuthChoice],
|
||||
area: Rect,
|
||||
hit: &std::cell::RefCell<HitRegions>,
|
||||
) {
|
||||
let mut regions = hit.borrow_mut();
|
||||
let mut y = area.y.saturating_add(2);
|
||||
for (index, choice) in choices.iter().enumerate() {
|
||||
let rows = choice_rows(choice).min(area.bottom().saturating_sub(y));
|
||||
if rows == 0 {
|
||||
break;
|
||||
}
|
||||
regions.push(Rect::new(area.x, y, area.width, rows), MouseTarget::AuthMethodRow(index));
|
||||
y = y.saturating_add(rows);
|
||||
}
|
||||
}
|
||||
|
||||
/// The button that copies a device code, under the transcript that shows it: typing the code by
|
||||
/// hand into a browser is the step most likely to go wrong.
|
||||
fn render_copy_code(
|
||||
frame: &mut Frame,
|
||||
area: Rect,
|
||||
code: &str,
|
||||
theme: &ThemeStyles,
|
||||
hit: &std::cell::RefCell<HitRegions>,
|
||||
) {
|
||||
let label = format!(" Copy code {code} ");
|
||||
let button = Span::styled(label.clone(), theme.accent.patch(theme.selected_bg));
|
||||
let line = Line::from(vec![button, Span::styled(" or press c", theme.muted)]);
|
||||
let row = Rect { y: area.y.saturating_add(1), height: 1, ..area };
|
||||
frame.render_widget(Paragraph::new(line), row);
|
||||
let width = u16::try_from(UnicodeWidthStr::width(label.as_str())).unwrap_or(row.width);
|
||||
hit.borrow_mut().push(Rect { width: width.min(row.width), ..row }, MouseTarget::AuthCopyCode);
|
||||
}
|
||||
|
||||
/// The sign-in's transcript so far, its last [`MAX_LINES`] lines.
|
||||
fn transcript_lines(lines: &[WizardLine], theme: &ThemeStyles) -> Vec<Line<'static>> {
|
||||
let mut body: Vec<Line<'static>> = Vec::new();
|
||||
|
||||
@@ -127,7 +127,6 @@ impl SetupState {
|
||||
None => {
|
||||
format!("Follow the desktop ({})", self.desktop.clone().unwrap_or_default())
|
||||
}
|
||||
Some(name) if name == "luxe" => "luxe (Luxe's own)".to_string(),
|
||||
Some(name) => name.clone(),
|
||||
};
|
||||
let spans = vec![
|
||||
|
||||
@@ -68,15 +68,13 @@ pub(super) fn clicked_target(app: &mut App, target: MouseTarget) -> RouteAction
|
||||
synthetic_enter()
|
||||
}
|
||||
MouseTarget::ThemeRow(index) => theme_row(app, index),
|
||||
MouseTarget::AuthCopyCode => copy_device_code(app),
|
||||
// Session/project pickers are route_key-owned (dashboard flow), so a click resolves
|
||||
// straight to the selection RouteAction rather than a synthetic key.
|
||||
MouseTarget::SessionRow(index)
|
||||
if app.current_view == crate::app::ViewMode::SessionPicker =>
|
||||
{
|
||||
match app.overlays.session_picker.as_ref().and_then(|p| p.session_id_at(index)) {
|
||||
Some(id) => RouteAction::SessionSelected(id),
|
||||
None => RouteAction::None,
|
||||
}
|
||||
session_row(app, index)
|
||||
}
|
||||
MouseTarget::ReviewDiffRow(row)
|
||||
if app.current_view == crate::app::ViewMode::GuidedReview =>
|
||||
@@ -216,6 +214,23 @@ fn configuration_page(app: &mut App, index: usize) -> RouteAction {
|
||||
}
|
||||
|
||||
/// Previews the clicked theme, then accepts it the way Enter would.
|
||||
/// Copies the sign-in wizard's device code, when it is showing one.
|
||||
fn copy_device_code(app: &mut App) -> RouteAction {
|
||||
let code = app.overlays.auth_wizard.as_ref().and_then(|w| w.device_code().map(String::from));
|
||||
if let Some(code) = code {
|
||||
app.record_copy(code);
|
||||
}
|
||||
RouteAction::None
|
||||
}
|
||||
|
||||
/// Opens the session on the clicked picker row.
|
||||
fn session_row(app: &App, index: usize) -> RouteAction {
|
||||
match app.overlays.session_picker.as_ref().and_then(|p| p.session_id_at(index)) {
|
||||
Some(id) => RouteAction::SessionSelected(id),
|
||||
None => RouteAction::None,
|
||||
}
|
||||
}
|
||||
|
||||
fn theme_row(app: &mut App, index: usize) -> RouteAction {
|
||||
if let Some(name) = app.overlays.theme_picker.as_mut().and_then(|p| p.select(index)) {
|
||||
app.preview_theme(&name);
|
||||
|
||||
@@ -120,8 +120,10 @@ pub enum MouseTarget {
|
||||
ModelRow(usize),
|
||||
/// A login-wizard provider row, by its index into the filtered list.
|
||||
AuthProviderRow(usize),
|
||||
/// A login-wizard method row, by its index.
|
||||
/// A login-wizard method row, by its index; also a choice of the question a sign-in is asking.
|
||||
AuthMethodRow(usize),
|
||||
/// The login wizard's button that copies the device code a sign-in is waiting on.
|
||||
AuthCopyCode,
|
||||
/// A Configuration row — a way in, or a file to open — by its index in whichever is showing.
|
||||
ConfigRow(usize),
|
||||
/// A settings page in the list down the left, by its index.
|
||||
|
||||
@@ -13,9 +13,9 @@ DashboardMinimal@64x20: frame=939001adda3bcbb4 hits=0f39b6e30d251353
|
||||
Configuration@140x44: frame=73fbef3e76d36c7c hits=03493dafb9356d07
|
||||
Configuration@100x30: frame=644345f8e6340004 hits=04d865ae91d0aa35
|
||||
Configuration@64x20: frame=28ea511ad251f8c2 hits=77b9c8af75245265
|
||||
Setup@140x44: frame=1ec7d489bf6353bb hits=36aaf8db347382c4
|
||||
Setup@100x30: frame=4124eb2f29256470 hits=2d10b9f0a226a5e0
|
||||
Setup@64x20: frame=1c978a2a7cabba3b hits=1b0ef6d44f0cf1bd
|
||||
Setup@140x44: frame=d61d62a149232446 hits=36aaf8db347382c4
|
||||
Setup@100x30: frame=1a7c35ff007f3aef hits=2d10b9f0a226a5e0
|
||||
Setup@64x20: frame=2df799477067503a hits=1b0ef6d44f0cf1bd
|
||||
SetupTools@140x44: frame=7f80f916b3e06e49 hits=2c443d3127ccc230
|
||||
SetupTools@100x30: frame=1985e10dacdabc20 hits=ee965f337121049c
|
||||
SetupTools@64x20: frame=8b216818fd028690 hits=a19d86f6dbe23c71
|
||||
@@ -251,7 +251,7 @@ login-subscription@100x30: frame=d0d2a22124d02530 hits=57ef1e7d5ac5daaf
|
||||
login-local@100x30: frame=2e2797e9080feb20 hits=9d3e38903152bd40
|
||||
login-method@100x30: frame=25f0337c7e66d84b hits=d7190c558c1be1a3
|
||||
login-secret@100x30: frame=8e5caa0414d23337 hits=b05996f46f500728
|
||||
login-device@100x30: frame=f57f8bc46fc07b6e hits=b05996f46f500728
|
||||
login-device@100x30: frame=9678dcaabe255bf8 hits=4f495f0ab9ddfec4
|
||||
login-failed@100x30: frame=7a68823bb655e435 hits=b05996f46f500728
|
||||
github@100x30: frame=29b83b4de4d5e45a hits=6ce218f729777fd8
|
||||
github-detail@100x30: frame=8bff1a38ff99681f hits=6ce218f729777fd8
|
||||
@@ -273,7 +273,7 @@ login-subscription@64x20: frame=36f5e865860fbdc2 hits=2d2883380c90c475
|
||||
login-local@64x20: frame=1e111e16e697b7d2 hits=7aff247fdf8c800d
|
||||
login-method@64x20: frame=c0818a1d2ffab01b hits=d068b54bba55b395
|
||||
login-secret@64x20: frame=f7cb80562502782e hits=a16a29ea4502d9fb
|
||||
login-device@64x20: frame=5d3e94107818674f hits=a16a29ea4502d9fb
|
||||
login-device@64x20: frame=d61ec0dc1534f2a5 hits=44ef8648f0a8302d
|
||||
login-failed@64x20: frame=8580d73e67e35808 hits=a16a29ea4502d9fb
|
||||
github@64x20: frame=59c575f5a335deb0 hits=7c38e58fb5f36453
|
||||
github-detail@64x20: frame=15178bfb7c3e702e hits=7c38e58fb5f36453
|
||||
|
||||
Reference in New Issue
Block a user