Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
docs(agent-cli): plan login UX implementation
thinhlpg0f8b80065a85
diff --git a/docs/superpowers/plans/2026-08-17-login-ux.md b/docs/superpowers/plans/2026-08-17-login-ux.mdnew file mode 100644index 000000000..86abd075a--- /dev/null+++ b/docs/superpowers/plans/2026-08-17-login-ux.md@@ -0,0 +1,654 @@+# Login UX Extension Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Make `/login` a direct five-provider sign-in picker and make `/model` a full-screen provider-scoped model browser that exposes models discovered by account login immediately.++**Architecture:** Keep OAuth, PKCE, callback validation, token exchange, model discovery, and persistence in `src-tauri/src/core/cli/auth/account.rs`. Keep provider capability metadata in the typed auth catalog. Keep TUI interaction state in `src-tauri/src/core/cli/tui.rs`: direct provider routing, an opaque OAuth prompt that never renders codes or state, and a separate model-hub state machine that consumes the existing reachable `(provider, model)` list.++**Tech Stack:** Rust 2021, Tokio, Ratatui 0.30, Crossterm, Reqwest, existing Jan credential/config stores, embedded Rust unit tests.++## Global Constraints++- Preserve the five-provider catalog order: Codex, Claude, OpenCode, DeepSeek, Tokamak.+- Codex and Claude use the existing PKCE browser flow; OpenCode, DeepSeek, and Tokamak use API-key login.+- Do not render API keys, authorization codes, OAuth state, PKCE verifiers, access tokens, or raw persistence errors.+- Do not perform network I/O in the Ratatui render loop.+- Cancelled or stale account-login tasks must not emit success or failure notes.+- `/model` lists only reachable configured provider models and preserves the raw model id passed to the runtime.+- Role assignment, role-management UI, desktop login, credential-store migration, and new providers are out of scope.+- Use existing dependencies and existing test modules; do not add a generic authentication framework.++---++## File map++- Modify `src-tauri/src/core/cli/auth/account.rs`+ - Parse manual OAuth callback input.+ - Race a validated manual input channel against the loopback callback.+ - Share token exchange, model discovery, and persistence between callback and manual paths.+ - Add account-flow tests without exposing secrets.+- Modify `src-tauri/src/core/cli/auth/mod.rs`+ - Add typed API-key metadata indicating whether the provider key page should open automatically.+ - Mark OpenCode as browser-assisted while leaving DeepSeek and Tokamak's existing prompt behavior unchanged.+- Modify `src-tauri/src/core/cli/tui.rs`+ - Remove the provider-to-method picker from `/login`.+ - Add the OAuth manual-input prompt and event-loop channel wiring.+ - Route API-key providers directly and open OpenCode's key page.+ - Replace the flat `/model` picker with a provider-scoped full-screen model hub.+ - Update embedded TUI tests and rendering helpers.+- Modify `docs/superpowers/specs/2026-08-17-login-ux-design.md` only if implementation discoveries require a user-approved contract change.++---++### Task 1: Add cancel-safe manual OAuth callback support++**Files:**+- Modify: `src-tauri/src/core/cli/auth/account.rs:100-165,351-398`+- Test: `src-tauri/src/core/cli/auth/account.rs` embedded `tests` module++**Interfaces:**+- Consumes: existing `AccountLogin`, `parse_callback`, `accept_callback`, `exchange`, credential persistence, and model discovery.+- Produces:+ - `pub fn parse_manual_callback(raw: &str, expected_state: &str) -> Result<String, String>`+ - `pub async fn complete_callback_login_with_manual(listener: tokio::net::TcpListener, login: AccountLogin, manual: tokio::sync::mpsc::UnboundedReceiver<String>) -> Result<AccountProvider, String>`+ - existing `complete_callback_login` keeps its strict loopback callback semantics and delegates finalization to one shared code path.++- [ ] **Step 1: Add parser tests before implementation**++Add these tests beside the existing callback tests:++```rust+#[test]+fn manual_callback_accepts_a_complete_redirect_url() {+ let login = begin(AccountProvider::Codex).unwrap();+ let raw = format!(+ "{}?code=authorization-code&state={}",+ login.redirect_uri, login.state+ );+ assert_eq!(+ parse_manual_callback(&raw, &login.state).unwrap(),+ "authorization-code"+ );+}++#[test]+fn manual_callback_accepts_a_raw_code_and_optional_state_suffix() {+ assert_eq!(+ parse_manual_callback("authorization-code", "expected-state").unwrap(),+ "authorization-code"+ );+ assert_eq!(+ parse_manual_callback("authorization-code#expected-state", "expected-state").unwrap(),+ "authorization-code"+ );+}++#[test]+fn manual_callback_rejects_empty_code_and_mismatched_state() {+ assert!(parse_manual_callback("", "expected-state").is_err());+ assert!(parse_manual_callback("authorization-code#wrong-state", "expected-state").is_err());+ assert!(parse_manual_callback(+ "http://localhost:1455/auth/callback?code=authorization-code&state=wrong-state",+ "expected-state"+ )+ .is_err());+}+```++- [ ] **Step 2: Run the parser tests and verify they fail**++Run:++```bash+cargo test --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --lib core::cli::auth::account::tests::manual_callback+```++Expected: compilation or test failure because `parse_manual_callback` is not defined.++- [ ] **Step 3: Implement manual input parsing without weakening browser callback validation**++Keep `parse_callback` strict: it must continue requiring a URL, a state, a matching expected state, and a non-empty `code`. Add `parse_manual_callback` with this order:++1. Trim input and reject empty input.+2. If the input parses as a URL, extract `code` and optional `state`; reject a supplied state that differs from `expected_state`; require a non-empty code.+3. If the input starts with `code=` or `?code=`, parse it as query parameters with the same optional-state check.+4. Otherwise split once on `#`; treat the left side as a raw code and the right side, when present, as the optional state. A raw code without a state is accepted because PKCE still binds the code to this login attempt.+5. Reject an empty code and return only safe, user-actionable messages.++Expose the method through `AccountLogin::parse_manual_input(&self, raw: &str)` if the TUI needs to validate before sending. The method must call the same parser with the login's private state rather than exposing the state field.++- [ ] **Step 4: Extract shared account completion**++Move the body after callback-code acquisition from `complete_callback_login` into a private async helper with this shape:++```rust+async fn complete_code_login(+ login: AccountLogin,+ code: String,+) -> Result<AccountProvider, String> {+ let token = exchange(&login, &code).await?;+ let definition = crate::core::cli::auth::provider_by_id(+ login.provider.credential_provider(),+ )+ .ok_or_else(|| "selected account is unavailable".to_string())?;+ // Preserve the existing test-only model endpoint override here.+ // Discover models, store the OAuth token, then write non-secret provider config.+ // Delete the stored token if config persistence fails, exactly as today.+ Ok(login.provider)+}+```++`complete_callback_login` becomes callback parsing followed by `complete_code_login(login, code)`. Do not change token exchange, model discovery, cleanup, or safe error text.++- [ ] **Step 5: Add the callback/manual race**++Implement `complete_callback_login_with_manual` with a pinned callback future and a loop over manual messages:++```rust+pub async fn complete_callback_login_with_manual(+ listener: tokio::net::TcpListener,+ login: AccountLogin,+ mut manual: tokio::sync::mpsc::UnboundedReceiver<String>,+) -> Result<AccountProvider, String> {+ let callback = accept_callback(listener, &login);+ tokio::pin!(callback);+ let code = loop {+ match manual.try_recv() {+ Ok(input) => {+ if let Ok(code) = parse_manual_callback(&input, &login.state) {+ break code;+ }+ }+ Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {}+ Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => {+ break callback.await?;+ }+ }+ tokio::select! {+ result = &mut callback => break result?,+ input = manual.recv() => match input {+ Some(input) => {+ if let Ok(code) = parse_manual_callback(&input, &login.state) {+ break code;+ }+ }+ None => break callback.await?,+ },+ }+ };+ complete_code_login(login, code).await+}+```++The actual implementation may use `AccountLogin::parse_manual_input`, but it must retain the callback future while invalid manual messages are ignored. The TUI will validate first to display the safe parser error; the account task validates again before exchanging.++- [ ] **Step 6: Add one end-to-end manual completion test**++Reuse the existing test-only token and model servers. Bind a listener, create an `AccountLogin`, start `complete_callback_login_with_manual` with an unbounded receiver, send `authorization-code#<state>`, await completion, and assert that the provider credential and discovered model config are persisted exactly as the existing callback test asserts. The test must not include a real token or callback value in an assertion message.++- [ ] **Step 7: Run account tests**++Run:++```bash+cargo test --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --lib core::cli::auth::account+```++Expected: all account tests pass, including strict callback, PKCE, token exchange, discovery cleanup, and manual completion cases.++- [ ] **Step 8: Commit the account-flow unit**++```bash+git add src-tauri/src/core/cli/auth/account.rs+git commit -m "feat(agent-cli): support manual account callback input"+```++---++### Task 2: Route direct provider login and render the OAuth prompt++**Files:**+- Modify: `src-tauri/src/core/cli/auth/mod.rs:26-33,72-131`+- Modify: `src-tauri/src/core/cli/tui.rs:294-444,1170-1190,1420-1500,4770-4825,5300-5420,5440-5660,5700-5760,6960-7165,8160-8440`+- Test: `src-tauri/src/core/cli/tui.rs` embedded `tests` module++**Interfaces:**+- Consumes: `AccountProvider`, `AccountLogin::parse_manual_input`, `complete_callback_login_with_manual`, existing `LoginPrompt`, `LoginService`, and `open_browser`.+- Produces:+ - typed `ApiKeyMetadata::open_in_browser` capability;+ - `AccountLoginPrompt` containing an opaque `AccountLogin`, masked manual input, safe error state, and submitting state;+ - direct `LoginProvider` Enter behavior with no `LoginMethod` picker;+ - `account_login_manual_tx: Option<tokio::sync::mpsc::UnboundedSender<String>>` for validated manual input.++- [ ] **Step 1: Replace method-picker tests with direct-flow tests**++Update the existing tests that assert `PickerKind::LoginMethod` around `login_method_picker_offers_account_only_for_account_login_providers`, the Tokamak method-picker test, and the Esc-return test. Replace them with assertions equivalent to:++```rust+#[tokio::test]+async fn provider_selection_starts_account_login_directly() {+ let mut app = test_app();+ super::open_login_picker(&mut app);+ let openai = app+ .picker+ .as_ref()+ .unwrap()+ .items+ .iter()+ .position(|item| item.value == "openai")+ .unwrap();+ app.picker.as_mut().unwrap().selected = openai;++ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;++ assert!(app.picker.is_none());+ assert!(app.account_login.is_some());+ assert!(app.account_login_submit.is_some());+ assert!(app.login.is_none());+}++#[tokio::test]+async fn api_key_provider_selection_starts_masked_prompt_directly() {+ let mut app = test_app();+ super::open_login_picker(&mut app);+ let tokamak = app+ .picker+ .as_ref()+ .unwrap()+ .items+ .iter()+ .position(|item| item.value == "tokamak")+ .unwrap();+ app.picker.as_mut().unwrap().selected = tokamak;++ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;++ assert!(app.picker.is_none());+ assert_eq!(app.login.as_ref().map(|p| p.provider.as_str()), Some("tokamak"));+ assert!(app.account_login.is_none());+}+```++Retain tests for provider ordering, status text, API-key verification, logout, and account cancellation, updating field names from `account_login_active` and `account_login_provider` to the new prompt option.++- [ ] **Step 2: Run the changed TUI tests and verify old expectations fail**++Run:++```bash+cargo test --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --lib core::cli::tui::tests::login+```++Expected: failures from the old method-picker assertions and missing direct-flow state.++- [ ] **Step 3: Add typed API-key browser capability**++Add `open_in_browser: bool` to `ApiKeyMetadata`. Set it to `true` only for OpenCode in `provider_catalog`; set it to `false` for Codex, Claude, DeepSeek, and Tokamak. Update any `ApiKeyMetadata` test fixtures or struct literals to provide the field.++In `open_login_prompt`, call `open_browser(definition.api_key.keys_url)` when `open_in_browser` is true. Keep the masked prompt open even when browser launch fails; render a safe error such as `could not open the browser; use the URL below` and preserve the existing manual entry path.++- [ ] **Step 4: Remove the second login method picker**++Remove `PickerKind::LoginMethod`, its title/action-hint branch, `open_login_method_picker`, the `LoginMethod` Enter arm, and the special Esc-to-provider-list arm. Change `PickerKind::LoginProvider` action text to `Enter sign in`. In the generic picker Enter arm, call a direct dispatcher:++```rust+PickerKind::LoginProvider => {+ if crate::core::cli::auth::account::AccountProvider::from_credential_provider(&value)+ .is_some()+ {+ open_account_login(app, &value);+ } else {+ open_login_prompt(app, &value);+ }+}+```++Keep capability resolution in `AccountProvider::from_credential_provider` and the typed API-key metadata; do not branch on display labels.++- [ ] **Step 5: Replace account-login flags with an opaque prompt**++Define the prompt beside `LoginPrompt`:++```rust+struct AccountLoginPrompt {+ login: crate::core::cli::auth::account::AccountLogin,+ input: String,+ error: Option<String>,+ submitting: bool,+}++impl AccountLoginPrompt {+ fn new(login: crate::core::cli::auth::account::AccountLogin) -> Self {+ Self { login, input: String::new(), error: None, submitting: false }+ }++ fn provider_id(&self) -> &'static str {+ self.login.provider().credential_provider()+ }++ fn masked(&self) -> String {+ super::secret_input::mask(self.input.chars().count())+ }+}+```++Expose a non-secret `pub(crate) fn AccountLogin::provider(&self) -> AccountProvider` accessor in `account.rs` rather than exposing private provider fields. The prompt may hold the opaque descriptor and clone it for retries, but it must render only provider name, callback URI, and an authorization host/path with query parameters removed.++Replace `account_login_active` and `account_login_provider` in `App` with `account_login: Option<AccountLoginPrompt>` and add `account_login_manual_tx`. Keep `account_login_submit` as the one-shot handoff descriptor. Initialize both new fields to `None`.++- [ ] **Step 6: Start the browser task with a manual-input channel**++In `chat_loop`, abort the account task when `app.account_login.is_none()`. When `account_login_submit` is present, create an unbounded channel, store its sender in `app.account_login_manual_tx`, and spawn the task:++```rust+let (manual_tx, manual_rx) = tokio::sync::mpsc::unbounded_channel();+app.account_login_manual_tx = Some(manual_tx);+account_login_task = Some(tokio::spawn(async move {+ let listener = crate::core::cli::auth::account::bind_callback(&login).await?;+ open_browser(&login.authorization_url)?;+ let provider = tokio::time::timeout(+ ACCOUNT_CALLBACK_TIMEOUT,+ crate::core::cli::auth::account::complete_callback_login_with_manual(+ listener,+ login,+ manual_rx,+ ),+ )+ .await+ .map_err(|_| "account sign-in timed out".to_string())??;+ Ok(provider.credential_provider().to_string())+}));+```++The prompt must already be visible before the first draw. If the task fails after the browser callback or token exchange, retain the prompt with a safe error, clear its input, clear the sender, and allow Enter to retry the stored opaque descriptor. On success, clear the prompt and call the existing model-adoption function. If cancellation cleared the prompt before a result arrives, `finish_account_login` must return without a note.++- [ ] **Step 7: Implement direct OAuth prompt input and paste routing**++Add `handle_account_login_key` before the API-key prompt branch in `handle_key` and route `Event::Paste` to the account prompt before `app.login`:++- Esc and Ctrl-C/Ctrl-D clear `account_login`, `account_login_submit`, and `account_login_manual_tx`.+- Ctrl-V reads the clipboard through the existing helper.+- Backspace and printable characters edit `input` only while `submitting` is false.+- Enter rejects an empty input locally; otherwise call `prompt.login.parse_manual_input(&prompt.input)`. On parser error, clear input, set the safe error, and keep the prompt open. On success, set `submitting = true`; if the task sender exists, send the original input; if the previous task ended, put a clone of `prompt.login` in `account_login_submit` so the event loop restarts it.+- While submitting, ignore edits but still honor cancellation.++The account task repeats validation before exchange, so the TUI-side validation is only for immediate feedback.++- [ ] **Step 8: Render the OAuth prompt safely**++Add `draw_account_login` and a fixed row budget. The box must show:++- `Codex sign-in` or `Claude sign-in` title;+- `open the browser to continue` or a safe browser-launch error;+- the callback URI, without query parameters;+- `authorization code or redirect URL: ********` with the caret represented by a cyan block;+- `Enter submit · Esc cancel` or `waiting for browser sign-in · Esc cancel`;+- a red safe error line when present.++Never render `authorization_url` verbatim because its query contains state and PKCE data. Render only its parsed origin and path if an auth destination is needed. Make the account prompt branch outrank the API-key prompt and ask queue in `draw`.++- [ ] **Step 9: Run the direct-login tests**++Run:++```bash+cargo test --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --lib core::cli::auth::tests+cargo test --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --lib core::cli::tui::tests::login+cargo test --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --lib core::cli::tui::tests::account+```++Expected: provider routing, prompt input/cancel, sanitization, account success/failure, and existing API-key tests pass.++- [ ] **Step 10: Commit the direct-login unit**++```bash+git add src-tauri/src/core/cli/auth/mod.rs src-tauri/src/core/cli/tui.rs+git commit -m "feat(agent-cli): route login providers directly"+```++---++### Task 3: Replace the flat `/model` picker with a provider-scoped model hub++**Files:**+- Modify: `src-tauri/src/core/cli/tui.rs:294-410,1170-1190,1420-1515,5520-5660,6908-6937,7907-7975,8663-8748,17912-17973`+- Test: `src-tauri/src/core/cli/tui.rs` embedded `tests` module++**Interfaces:**+- Consumes: `super::providers::list_provider_models(Some(&app.project_root))`, `App::set_model`, existing multi-term search semantics, Ratatui layout/widgets.+- Produces:+ - `ModelScope { provider: Option<String>, label: String, count: usize }`;+ - `ModelPicker { scopes, active_scope, focus, all_items, items, query, selected }`;+ - `ModelPicker::from_pairs(pairs, current_model) -> Option<ModelPicker>`;+ - `ModelPicker::refresh_items`, `ModelPicker::select_scope`, and `ModelPicker::move_selection`.++- [ ] **Step 1: Add model-hub state tests before implementation**++Replace the two tests that instantiate `PickerKind::SelectModel` with tests over `ModelPicker::from_pairs`:++```rust+#[test]+fn model_picker_builds_all_and_provider_scopes_with_counts() {+ let picker = super::ModelPicker::from_pairs(+ vec![+ ("anthropic".into(), "claude-sonnet".into()),+ ("openai".into(), "gpt-5-codex".into()),+ ("openai".into(), "gpt-5-mini".into()),+ ],+ "gpt-5-codex",+ )+ .unwrap();++ assert_eq!(picker.scopes[0].label, "All models");+ assert_eq!(picker.scopes[0].count, 3);+ assert_eq!(picker.scopes[1].label, "anthropic");+ assert_eq!(picker.scopes[1].count, 1);+ assert_eq!(picker.scopes[2].label, "openai");+ assert_eq!(picker.scopes[2].count, 2);+ assert_eq!(picker.items[picker.selected].value, "gpt-5-codex");+}++#[test]+fn model_picker_filters_all_terms_and_changes_scope() {+ let mut picker = super::ModelPicker::from_pairs(+ vec![+ ("openai".into(), "gpt-5.6-luna".into()),+ ("openai".into(), "gpt-5.6-terra".into()),+ ("anthropic".into(), "claude-sonnet".into()),+ ],+ "gpt-5.6-luna",+ )+ .unwrap();++ picker.query = "openai luna".into();+ picker.refresh_items();+ assert_eq!(picker.items.len(), 1);+ assert_eq!(picker.items[0].value, "gpt-5.6-luna");++ picker.select_scope(1);+ assert_eq!(picker.scopes[picker.active_scope].label, "anthropic");+ assert!(picker.items.iter().all(|item| item.provider == "anthropic"));+}+```++Add a test that Enter uses the raw model value (`gpt-5-codex`) while the visible label remains `openai / gpt-5-codex`; this preserves the runtime resolver's existing exact-model behavior.++- [ ] **Step 2: Run model-hub tests and verify they fail**++Run:++```bash+cargo test --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --lib core::cli::tui::tests::model_picker+```++Expected: compilation or test failure because `ModelPicker` does not exist.++- [ ] **Step 3: Define provider scopes and model rows**++Add the model-hub types near the existing generic picker types:++```rust+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum ModelPickerFocus {+ Scopes,+ Models,+}++#[derive(Clone, Debug, PartialEq, Eq)]+struct ModelScope {+ provider: Option<String>,+ label: String,+ count: usize,+}++#[derive(Clone, Debug, PartialEq, Eq)]+struct ModelItem {+ provider: String,+ model: String,+ value: String,+}++struct ModelPicker {+ scopes: Vec<ModelScope>,+ active_scope: usize,+ focus: ModelPickerFocus,+ all_items: Vec<ModelItem>,+ items: Vec<ModelItem>,+ query: String,+ selected: usize,+}+```++`from_pairs` must sort pairs as the existing provider listing does, deduplicate exact `(provider, model)` duplicates, create `All models` followed by one scope per provider, count from the deduplicated rows, and select the current raw model when present or row zero otherwise. `refresh_items` must match every whitespace-separated lowercase term against `provider + " " + model`, preserve the active scope, and clamp `selected` after filtering. A scope selection resets `selected` to the current raw model within that scope when possible, otherwise zero.++Do not add context-window, price, roles, or remote catalog metadata. The only detail footer data available in this build is provider, raw model id, and whether it equals `app.model`.++- [ ] **Step 4: Move `/model` out of the generic picker**++Add `model_picker: Option<ModelPicker>` to `App` and initialize it to `None`. Remove `PickerKind::SelectModel`, its title/action-hint and generic query handling, the generic model Enter arm, and the old `Picker::refresh_model_items` method. Update the two old model tests to use `ModelPicker`.++Change `open_model_picker` to call `list_provider_models`, construct `ModelPicker::from_pairs`, and assign `app.model_picker`. Keep the existing no-model note when the constructor returns `None`.++- [ ] **Step 5: Implement model-hub keyboard behavior**++Before the generic `app.picker` branch in `handle_key`, route `app.model_picker` to `handle_model_picker_key`:++- Up/Down moves within the focused scope or model list.+- Left/Right switches focus between scopes and models. When entering the model pane, clamp the row to the active list.+- Printable characters and Backspace edit `query` only when the model pane is focused, then call `refresh_items`.+- Enter on a scope changes the active scope; Enter on a model calls `app.set_model(item.value.clone())` and clears `app.model_picker`.+- Esc, Ctrl-C, and Ctrl-D clear `app.model_picker` without changing `app.model`.++Use `j/k` only as aliases for Up/Down when the model pane is focused. Do not route model-hub keystrokes into the chat input or generic picker.++- [ ] **Step 6: Render the split full-screen model hub**++At the start of `draw`, after updating `view_width` but before building the normal transcript layout, return through `draw_model_picker` when `app.model_picker` is present. This prevents the regular input dock and transcript from consuming model-hub rows.++`draw_model_picker` must render a bordered full-frame block with:++- title `Models`;+- a left sidebar with `All models` and provider rows, counts right-aligned, active scope highlighted, and the scope focus indicated separately from the model focus;+- a vertical divider;+- a right pane with `All available models` or `<provider> models`, a search row beginning with a magnifier marker and the masked caret/query text, model rows showing `provider / model`, and the selected row highlighted;+- a detail row below the model list showing `provider/model`, `current` or `default` state, and no invented metadata;+- a bottom help row: `Enter choose · Left/Right panes · Up/Down move · type to search · Esc close`.++Use `Layout::horizontal` and `Layout::vertical` with bounded widths, `Clear`, `Block`, `List`, `ListState`, `Paragraph`, `Line`, and `Span` already imported by `tui.rs`. Clamp every list height and selection index for short terminals. Keep provider/model text truncated to the available pane width rather than wrapping rows.++- [ ] **Step 7: Verify model selection and discovery behavior**++Run:++```bash+cargo test --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --lib core::cli::tui::tests::model_picker+cargo test --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --lib core::cli::tui::tests::login_successful_api_key_login_reports_only_model_guidance+```++Expected: model scopes, counts, filtering, selection persistence, and post-login model adoption pass. The model-picker tests must prove that a newly written provider model is visible when `open_model_picker` is called again.++- [ ] **Step 8: Commit the model-hub unit**++```bash+git add src-tauri/src/core/cli/tui.rs+git commit -m "feat(agent-cli): add provider-scoped model picker"+```++---++### Task 4: Run integrated CLI verification and terminal smoke checks++**Files:**+- Test: `src-tauri/src/core/cli/auth/account.rs`+- Test: `src-tauri/src/core/cli/auth/mod.rs`+- Test: `src-tauri/src/core/cli/tui.rs`+- No new production files.++**Interfaces:**+- Consumes: all committed changes from Tasks 1 through 3.+- Produces: verified CLI build, targeted test evidence, and a terminal smoke result for `/model` navigation. No code changes are expected unless a failing check identifies a contract bug.++- [ ] **Step 1: Run the focused auth and TUI test groups**++```bash+cargo test --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --lib core::cli::auth+cargo test --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --lib core::cli::tui+```++Expected: both commands pass, including unchanged provider security tests, callback tests, direct login tests, prompt cancellation, model scopes, filtering, and rendering-state tests.++- [ ] **Step 2: Run the CLI build check**++```bash+cargo check --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --bin jan+```++Expected: the headless `jan` binary compiles without desktop features and without warnings promoted to errors.++- [ ] **Step 3: Exercise the real TUI model hub in a PTY**++Use a temporary home/data directory and a temporary project containing a reachable provider config with two model ids. The provider config shape is:++```toml+default_model = "gpt-5-codex"++[providers.openai]+base_url = "http://127.0.0.1:1/v1"+models = ["gpt-5-codex", "gpt-5-mini"]+api_key = "smoke-only"+```++Start the actual binary through the project process supervisor with a PTY, using isolated environment variables:++```text+application: cargo+args: run --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --bin jan -- --project $TMP_PROJECT+env: HOME=$TMP_HOME JAN_DATA_FOLDER=$TMP_DATA+```++Send `/model`, observe the full-screen `Models` block, verify the left sidebar shows `All models` count `2` and `openai` count `2`, type `mini`, verify the right pane leaves only `gpt-5-mini`, press Enter, and verify the TUI reports `model set to gpt-5-mini` and returns to the normal input surface. Stop the process with Ctrl-C. Do not run this smoke check against the user's real credential directory.++- [ ] **Step 4: Exercise cancellation without persistence**++Start the TUI with the same isolated home, type `/login`, select Codex, then press Esc before completing browser authentication. Verify the prompt disappears, no `signed in` or `failed` note is added, and the temporary credential/config stores remain unchanged. The browser may open; close it after cancellation.++- [ ] **Step 5: Run the final relevant check after any smoke-driven fixes**++```bash+cargo test --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --lib core::cli::auth+cargo test --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --lib core::cli::tui+```++Expected: all focused tests and the CLI build pass after the smoke path.++- [ ] **Step 6: Review the diff and commit only if a verification fix was required**++If smoke verification required a source fix, commit it as one focused conventional commit in the affected module, for example:++```bash+git add src-tauri/src/core/cli/auth/account.rs src-tauri/src/core/cli/tui.rs+git commit -m "fix(agent-cli): stabilize login and model hub smoke path"+```++Do not create a no-op verification commit.