Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
Merge remote-tracking branch 'origin/dev' into feature/8661-improve-login-ux
thinhlpg0f329c97101c
diff --cc src-tauri/src/core/cli/tui.rsindex d20ab9f91,bb83e2427..0d1d671b3--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@@ -91,7 -105,18 +108,18 @@@ fn alt_scroll_restore() -> &'static st}}+const ACCOUNT_CALLBACK_TIMEOUT: Duration = Duration::from_secs(300);+ /// The private modes to set on entry, in one write. Keyboard enhancement is+ /// unconditional -- it is what the editing keys are decoded from -- while mouse+ /// tracking follows the `mouse` config key.+ fn startup_modes(mouse: bool) -> String {+ let mut modes = String::from(alt_scroll_save_off());+ modes.push_str(KITTY_KEYS_ON);+ if mouse {+ modes.push_str(MOUSE_TRACK_ON);+ }+ modes+ }-/// How long the dock advertises a finished copy.const COPY_NOTICE: Duration = Duration::from_millis(1500);/// Terminals cap the OSC 52 payload they will accept; past this the sequence is@@@ -1367,15 -1218,12 +1396,20 @@@ struct App/// Orchestration handle for out-of-run model calls (the `/compact` command)./// `None` in unit tests, set by `run` for the live session.args: Option<Arc<OrchestrationArgs>>,+ /// Context window limit for the current model. Updated on every model+ /// switch via [`Self::refresh_context_window`]: configured override, then+ /// the built-in model catalog, then a 128K fallback.+ /// The approval-mode phrasing used by the splash (e.g. "--safe: writes, ...").+ /// Captured once at startup so `/clear`, `/new` and `/resume` re-print the+ /// same branding without re-deriving it.+ approval_phrasing: String,+ /// Context window limit for the current model (default 128K).context_window: u64,+ /// Where `context_window` came from: configured override, catalog, or fallback.+ context_window_source: crate::core::cli::model_capabilities::ContextWindowSource,+ /// The explicit `[agent].context_window` override copied from the session+ /// limits (`None` when unset). Stays authoritative across model switches.+ configured_context_window: Option<u64>,/// Tokens to reserve for the model's response (compaction triggers at limit - reserve).reserve_tokens: u64,/// Per-request output cap forwarded to the model as OpenAI `max_tokens`.@@@ -1872,16 -1715,8 +1906,17 @@@ impl Appgoal_eval_pending: false,run_mode: crate::core::agent::plan::RunMode::Normal,args: None,+ approval_phrasing: String::new(),context_window: limits.context_window,+ context_window_source: limits.context_window_source,+ // The explicit override, when present, is the resolved window with a+ // `Configured` source; otherwise there was none to carry forward.+ configured_context_window: match limits.context_window_source {+ crate::core::cli::model_capabilities::ContextWindowSource::Configured => {+ Some(limits.context_window)+ }+ _ => None,+ },reserve_tokens: limits.reserve_tokens,max_tokens: limits.max_tokens,max_session_tokens: limits.max_session_tokens,@@@ -6101,17 -5944,15 +6236,15 @@@ pub async fn runlet sandboxed = args.sandbox.unwrap_or_else(|| crate::core::agent::r#loop::effective_sandbox(&app.project_root));- app.push_banner(- match (args.auto_approve, sandboxed) {- (true, true) => "auto-approved inside the OS sandbox (start with --safe to be asked first)",- (true, false) => "auto-approved and unsandboxed: commands run with your own access (--safe to be asked first, --sandbox to confine)",- (false, true) => "--safe: writes, shell commands and MCP tool calls need approval",- (false, false) => "--safe: approval needed, but unsandboxed - what you approve runs with your own access (--sandbox to confine)",- },- !seeded,- );+ app.approval_phrasing = match (args.auto_approve, sandboxed) {+ (true, true) => "auto-approved inside the OS sandbox (start with --safe to be asked first)".to_string(),+ (true, false) => "auto-approved and unsandboxed: commands run with your own access (--safe to be asked first, --sandbox to confine)".to_string(),+ (false, true) => "--safe: writes, shell commands and MCP tool calls need approval".to_string(),+ (false, false) => "--safe: approval needed, but unsandboxed - what you approve runs with your own access (--sandbox to confine)".to_string(),+ };+ app.push_session_banner(!seeded);if app.model.is_empty() {- app.note("not signed in — run /login to sign in to Tokamak, or `jan config set` to configure a provider manually");+ app.note("not signed in — run /login to choose a provider");}// Only when there is nothing to load: a project that already has JAN.md needs// no invitation, and the splash hint covers re-running /init deliberately.@@@ -8107,15 -7725,77 +8316,80 @@@ const SLASH_COMMANDS: &[SlashCommand]/// of truth for the `/help` listing and the first-run footer hint, so the two/// can't drift. Deliberately not rendered on every frame -- the footer is for/// transient state (running, prompts, pickers), not a permanent cheat sheet.+ /// A word character for the emacs-style motions (Alt+B/F/D, Alt+Backspace,+ /// Ctrl/Alt+arrows), matching readline: alphanumerics plus `_`.+ fn is_word_char(c: char) -> bool {+ c.is_alphanumeric() || c == '_'+ }++ /// Byte offset of the emacs word boundary before `at`: skip any run of+ /// non-word chars, then the word itself, so `"foo bar"` with the caret at the+ /// end lands on `b` and `"foo "` lands on 0.+ fn prev_word_start(s: &str, at: usize) -> usize {+ let mut i = at;+ let mut in_word = false;+ while let Some(c) = s[..i].chars().next_back() {+ if is_word_char(c) {+ in_word = true;+ } else if in_word {+ break;+ }+ i -= c.len_utf8();+ }+ i+ }++ /// The mirror of [`prev_word_start`], scanning forward from `at`.+ fn next_word_end(s: &str, at: usize) -> usize {+ let mut i = at;+ let mut in_word = false;+ while let Some(c) = s[i..].chars().next() {+ if is_word_char(c) {+ in_word = true;+ } else if in_word {+ break;+ }+ i += c.len_utf8();+ }+ i+ }++ /// `Ctrl-W`'s boundary: whitespace-delimited, like the shell's+ /// unix-word-rubout, so it takes a whole `src/core/cli/tui.rs` token rather+ /// than stopping at every `/`.+ fn prev_unix_word_start(s: &str, at: usize) -> usize {+ let mut i = at;+ for stop_on_space in [false, true] {+ while let Some(c) = s[..i].chars().next_back() {+ if c.is_whitespace() == stop_on_space {+ break;+ }+ i -= c.len_utf8();+ }+ }+ i+ }++ /// Byte offsets bounding the line `at` sits on, newlines excluded. The+ /// composer is multi-line (Alt/Shift+Enter), so "line" is not the whole buffer.+ fn line_bounds(s: &str, at: usize) -> (usize, usize) {+ let start = s[..at].rfind('\n').map_or(0, |i| i + 1);+ let end = s[at..].find('\n').map_or(s.len(), |i| at + i);+ (start, end)+ }+const KEY_BINDINGS: &[(&str, &str)] = &[("Enter", "Send the message"),- ("Alt+Enter / Ctrl-J", "Insert a newline"),+ ("Alt+Enter / Ctrl-J", "Insert a newline (Shift+Enter where reported)"),+ ("Ctrl-A/E, Alt+B/F", "Start/end of line, word left/right"),+ ("Ctrl-W, Alt+Backspace", "Delete the word before the caret"),+ ("Ctrl-U / Ctrl-K", "Delete to the start / end of the line"),("Esc / Ctrl-C", "Cancel the running turn"),("Esc Esc", "Rewind to an earlier message"),- ("↑/↓", "Recall sent messages (scrolls while the input has text)"),+ (+ "↑/↓",+ "Recall sent messages (scrolls while the input has text)",+ ),("PgUp/PgDn", "Scroll the transcript"),("Ctrl-O", "Expand or collapse all tool calls"),("Ctrl-V", "Paste an image from the clipboard"),@@@ -8201,10 -7883,10 +8477,11 @@@ async fn run_command(app: &mut App, lin}"mcp" => open_mcp_picker(app),"plugin" => plugin_command(app, arg).await,- "login" => open_login_prompt(app),+ "login" => open_login_picker(app),+ "logout" => logout_command(app, arg),"update" => update_command(app),"config" => open_config_screen(app),+ "terminal-setup" => terminal_setup_command(app),"settings" => settings_command(app, arg),"goal" => goal_command(app, arg),"init" => init_command(app),@@@ -12701,14 -11861,18 +13025,18 @@@ fn header_spans(app: &App) -> Vec<Span<.map(|t| format!(" {}", format_elapsed(t.elapsed().as_secs()))).unwrap_or_default();// No name chip: the splash names the app (see `Banner`), and the header's- // columns are better spent on state that changes. The model leads instead,- // bold so the row still has an anchor on the left; an unset model says so- // rather than opening the row with blanks.- let mut spans = vec![if app.model.is_empty() {- Span::styled(" no model ", Style::new().red().bold())- } else {- Span::styled(format!(" {} ", app.header_model_label()), Style::new().bold())- }];+ // columns are better spent on state that changes. The wave mark stands in+ // for the name in one glyph, then the model, bold so the row still has an+ // anchor on the left; an unset model says so rather than opening the row+ // with blanks.+ let mut spans = vec![+ Span::styled(format!(" {}", brand::WAVE), Style::new().yellow()),+ if app.model.is_empty() {+ Span::styled(" no model", Style::new().red().bold())+ } else {- Span::styled(format!(" {}", app.model), Style::new().bold())++ Span::styled(format!(" {}", app.header_model_label()), Style::new().bold())+ },+ ];// Reasoning-effort badge: `effort high` after the model, so the configured// reasoning depth is visible at a glance. Reported low/medium/high exactly// as set, so the display always matches what is sent upstream.@@@ -23612,16 -21833,34 +24218,40 @@@ mod testsassert!(app.thread_id.is_none(), "must detach from the saved thread");assert_eq!(app.tokens, 0);let text: String = app.transcript.iter().map(row_text).collect();- assert!(!text.contains("old content"), "transcript not reset: {text}");- assert!(text.contains("started a new session"), "missing note: {text}");+ assert!(+ !text.contains("old content"),+ "transcript not reset: {text}"+ );+ assert!(+ text.contains("started a new session"),+ "missing note: {text}"+ );}+ #[tokio::test]+ async fn clear_re_prints_the_branded_splash() {+ let mut app = test_app();+ app.approval_phrasing = "--safe: approval needed".to_string();+ app.push(Line::raw("old content"));++ run_command(&mut app, "clear").await;++ let text: String = app.transcript.iter().map(row_text).collect();+ assert!(+ !text.contains("old content"),+ "transcript not reset: {text}"+ );+ assert!(+ text.contains(brand::HAND[0].trim()),+ "hand logo missing after /clear: {text}"+ );+ assert!(+ text.contains("--safe: approval needed"),+ "approval phrasing missing after /clear: {text}"+ );+ assert!(text.contains("type a message to start"), "{text}");+ }+#[test]fn parse_command_handles_multibyte_without_panic() {// Leading space + multibyte would panic under byte slicing.@@@ -25136,21 -23259,30 +25800,33 @@@}}+ /// The wave mark is the only branding the header carries: one glyph, then+ /// the model. A name chip would spend the columns the status needs.#[test]- fn header_leads_with_the_model_not_a_name_chip() {+ fn header_leads_with_the_wave_then_the_model() {let mut app = test_app();app.model = "tokamak-1-preview".into();- let top = render_rows(&mut app, 110, 12).remove(0);+ let top = render_rows(&mut app, 60, 12).remove(0);+ let head = top.trim_start();+ assert!(+ head.starts_with(brand::WAVE),+ "the wave should open the row: {top:?}"+ );assert!(- top.starts_with(" tokamak-1-preview"),- "the name chip is back: {top:?}"+ head[brand::WAVE.len()..]+ .trim_start()+ .starts_with("tokamak-1-preview"),+ "the model should follow the wave, with no name chip between: {top:?}");- // The freed columns are what let the status survive a 110-column frame.- // The freed columns are what let the status survive a 60-column frame.-- assert!(top.contains("[ready]"), "{top:?}");++ // The freed columns are what let the status survive. This branch's++ // header also carries the fallback chip, so `[ready]` needs the wider++ // frame that dev's 60-column case has no room for.++ let wide = render_rows(&mut app, 110, 12).remove(0);++ assert!(wide.contains("[ready]"), "{wide:?}");app.model.clear();- let top = render_rows(&mut app, 110, 12).remove(0);- assert!(top.starts_with(" no model"), "{top:?}");+ let top = render_rows(&mut app, 60, 12).remove(0);+ assert!(top.contains("no model"), "{top:?}");}#[test]