From da89cee27007719ed90241b71eb0102f9561a52a Mon Sep 17 00:00:00 2001 From: Karan Sharma Date: Tue, 17 Nov 2026 12:52:09 +0530 Subject: [PATCH 1/4] docs(cli): regenerate the reference for the iceberg quantity default The --iceberg-quantity help text changed in 2d8143d but the generated reference still showed the old text. --- docs/CLI_REFERENCE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index 76d7456..5a127b6 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -439,7 +439,7 @@ Options: Number of iceberg legs, between 2 and 50 --iceberg-quantity - Quantity per iceberg leg + Quantity per iceberg leg. Defaults to Kite web's split: the quantity over the legs, rounded up to whole lots --auction-number Auction number for auction variety orders From dcb94a5a0e17f857e60ea510a97787429322c612 Mon Sep 17 00:00:00 2001 From: Karan Sharma Date: Tue, 17 Nov 2026 12:52:23 +0530 Subject: [PATCH 2/4] docs(tui): explain what running several TUI windows costs Each instance opens its own ticker connection and runs its own pollers, and instances do not share local state. Say so, and point at the ticker connection cap and poll_secs. --- docs/guide/tui.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/guide/tui.md b/docs/guide/tui.md index 5b74b00..cd53889 100644 --- a/docs/guide/tui.md +++ b/docs/guide/tui.md @@ -642,7 +642,13 @@ The following actions open a confirmation modal showing the exact parameters or Every file save writes to a temporary file in the same directory and atomically renames it into place, ensuring an interrupted write never leaves a corrupted or truncated file. `notes.json` is only rewritten when note contents actually change. Symlinked configuration, settings, and notes files are respected (writes replace the resolved target file, while broken symlinks report an error). -Running two TUI instances concurrently in separate terminals does not synchronise local state: the last instance to save wins, and concurrent note edits do not merge. A `kite tui --token` session never writes to `notes.json`. +### Running more than one window + +You can run several TUI instances at once in separate terminals or tmux panes. They share one signed-in session but nothing else: + +- **Local state:** Instances do not synchronise `tui.json` or `notes.json`. The last instance to save wins, and concurrent note edits do not merge. A `kite tui --token` session never writes to `notes.json`. +- **Live data:** Each instance opens its own WebSocket ticker connection. Kite caps concurrent ticker connections (see [rate limits](troubleshooting.md)), so an instance beyond that cap may get no live ticks. Press `Ctrl-L` in that window to see the ticker error. +- **Polling:** Each instance polls orders, positions, holdings, funds, GTTs and alerts on its own timer, and loads its own chart candles. With default intervals this is far below Kite's REST limits, but opening charts in several windows at once can briefly hit the historical-candle limit (`HTTP 429`). Raise `poll_secs` in `tui.json` if you run many instances. --- From b41c1a2aaf9ae151860062acb6358140c7c946a2 Mon Sep 17 00:00:00 2001 From: Karan Sharma Date: Tue, 17 Nov 2026 12:52:23 +0530 Subject: [PATCH 3/4] feat(tui): show when a newer kite release exists TUI users only learned about a release by running kite upgrade --check or kite doctor. The TUI now checks GitHub in the background at startup and, when a newer release exists, shows update vX.Y.Z in the header and a toast naming the command to run. The lookup is the one upgrade --check already makes. Its result is cached in ~/.cache/kite/update.json for a day so several windows share one request, and the toast fires once per release. A failed lookup is silent. Installs under a Nix store or Homebrew Cellar path are told to use their package manager. "update_check": false in tui.json or KITE_NO_UPDATE_CHECK=1 turns it off. --- CHANGELOG.md | 4 + docs/guide/configuration.md | 1 + docs/guide/tui.md | 13 ++ src/tui.rs | 4 + src/tui/app/events/mod.rs | 37 ++++++ src/tui/app/mod.rs | 1 + src/tui/app/state.rs | 1 + src/tui/data.rs | 1 + src/tui/settings.rs | 1 + src/tui/ui/header.rs | 54 ++++++++ src/tui/update.rs | 248 ++++++++++++++++++++++++++++++++++++ 11 files changed, 365 insertions(+) create mode 100644 src/tui/update.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 5347c95..4b296f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Added + +- The TUI tells you when a newer `kite` release exists. The header shows `update vX.Y.Z` and a toast names the command to run, once per release. It checks GitHub in the background at most once a day and never delays startup. Turn it off with `"update_check": false` in `tui.json` or `KITE_NO_UPDATE_CHECK=1`. + ### Fixed - `kite orders place` refuses orders that are incomplete as written, in dry runs and with `--confirm`: a LIMIT or SL order without a positive `--price`, an SL or SL-M order without a positive `--trigger-price`, `--variety iceberg` without `--iceberg-legs`, `--variety auction` without `--auction-number`, `--validity TTL` without `--validity-ttl`, and iceberg or TTL flags given without their variety or validity. It previously printed a dry run and exited 0. diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index 355a7af..c6a3c7b 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -71,6 +71,7 @@ path /home/user/.config/kite/config.json | `NO_COLOR` | Any value (including empty) disables ANSI colour in CLI output | | `TERM` | `dumb` disables ANSI colour in CLI output | | `COLUMNS` | Override detected terminal width for CLI table formatting | +| `KITE_NO_UPDATE_CHECK` | Any value other than empty or `0` stops the TUI's background release check (see [Update notice](tui.md#update-notice)) | | `XDG_CONFIG_HOME`, `XDG_CACHE_HOME` | Override default config and cache base directories on Linux | Empty or whitespace-only `KITE_*` environment variables are ignored. diff --git a/docs/guide/tui.md b/docs/guide/tui.md index cd53889..51ef230 100644 --- a/docs/guide/tui.md +++ b/docs/guide/tui.md @@ -65,6 +65,7 @@ Bracketed paste inserts text into the focused field. Single-line fields accept o - **Header:** Displays one tab per workspace followed by a status strip: - **WebSocket state:** `● live`, `◌ connecting`, `◌ reconnecting`, `○ offline`, or `○ auth expired`. - **Session indicators:** Session uptime, IST clock, market phase (`pre-open`, `open`, or closed), and available equity margin. + - **Update notice:** `update vX.Y.Z` when a newer `kite` release exists (see [Update notice](#update-notice)). - **Responsive truncation:** When the terminal width is narrow, the status strip drops the clock and market phase first, then available funds, and then uptime. Workspace tabs drop their number keys first, then the `kite` mark, without truncating workspace names—all tabs fit at 80 columns. Below 80 columns, the header keeps the active tab and as many adjacent tabs as fit, displaying `‹` or `›` on sides with hidden tabs. - **Main area:** Displays the panes of the active workspace. - **Message and key-hint bar:** Shows transient status messages (order acknowledgements, errors) colour-coded by severity. When no message is active, it displays contextual key hints grouped by function and separated by a dim `│`: @@ -539,6 +540,7 @@ Interactive preferences changed inside the TUI are written back to `tui.json` im | `workspaces` | Per-user map tracking the active workspace, focused pane, and zoomed state. Managed automatically by the TUI. | | `selected_watch` | Per-user map tracking the last open watchlist ID. Managed automatically by the TUI. | | `poll_secs` | Background refresh intervals in seconds (clamped to `2`–`600`) for `orders`, `positions`, `holdings`, `margins`, `gtt`, and `alerts`. Mutual fund holdings share the `holdings` interval. | +| `update_check` | Boolean (`true` by default when omitted). Set `false` to stop the TUI from checking GitHub for a newer release. See [Update notice](#update-notice). | - **`splits` keys:** `chart_right`, `chart_bottom`, `overview_main`, `overview_books`, `trading_root`, `trading_right`, `trading_bottom`, `portfolio_root`, `portfolio_left`, `portfolio_right`, `derivatives_root`, `orders_root`, `orders_right` (legacy `watch_detail` is ignored). - **`workspaces` schema migration:** Written with a `version` field. The TUI transparently migrates `version: 1` state (from before multi-pane workspaces) to the corresponding modern workspaces and preserves unknown future versions untouched. @@ -639,6 +641,7 @@ The following actions open a confirmation modal showing the exact parameters or | `~/.config/kite/notes.json` | Local trading notes and scratchpad entries | | `~/.config/kite/config.json` | Saved session credentials written by the sign-in screen (see [Configuration](configuration.md)) | | `~/.cache/kite/instruments.json` | Cached exchange instrument master | +| `~/.cache/kite/update.json` | Latest release seen and when it was checked (see [Update notice](#update-notice)) | Every file save writes to a temporary file in the same directory and atomically renames it into place, ensuring an interrupted write never leaves a corrupted or truncated file. `notes.json` is only rewritten when note contents actually change. Symlinked configuration, settings, and notes files are respected (writes replace the resolved target file, while broken symlinks report an error). @@ -650,6 +653,16 @@ You can run several TUI instances at once in separate terminals or tmux panes. T - **Live data:** Each instance opens its own WebSocket ticker connection. Kite caps concurrent ticker connections (see [rate limits](troubleshooting.md)), so an instance beyond that cap may get no live ticks. Press `Ctrl-L` in that window to see the ticker error. - **Polling:** Each instance polls orders, positions, holdings, funds, GTTs and alerts on its own timer, and loads its own chart candles. With default intervals this is far below Kite's REST limits, but opening charts in several windows at once can briefly hit the historical-candle limit (`HTTP 429`). Raise `poll_secs` in `tui.json` if you run many instances. +### Update notice + +At startup the TUI checks GitHub for a newer `kite` release in the background. It never delays startup or sign-in, and it never upgrades on its own. + +- **What you see:** When a newer release exists, the header status strip shows `update vX.Y.Z` in the warning colour, and a toast names the command to run. The toast appears once per release; later sessions show only the header item. On a narrow terminal the header item is the first status field to drop. +- **How to upgrade:** Quit the TUI and run `kite upgrade`. When the binary runs from a Nix store or Homebrew Cellar path, the toast says to upgrade with your package manager instead. +- **How often:** At most once a day. The result is cached in `~/.cache/kite/update.json`, so several open windows share one lookup. A failed lookup shows nothing and is retried at the next launch. +- **What it sends:** One unauthenticated request to `github.com/zerodha/kite-cli/releases/latest`, the same lookup `kite upgrade --check` makes. No user ID or session data is sent. +- **Turning it off:** Set `"update_check": false` in `tui.json` or `KITE_NO_UPDATE_CHECK=1` in the environment. `kite upgrade --check` and `kite doctor` still check on demand. + --- ## Connection diagnostics diff --git a/src/tui.rs b/src/tui.rs index 563fdb1..ed7a7ac 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -20,6 +20,7 @@ mod subscriptions; mod ticket; mod ticks; mod ui; +mod update; mod workspace; use crate::app::runtime::Runtime; @@ -206,6 +207,9 @@ fn spawn_session_tasks( events_tx.clone(), )); tasks.push(data::spawn_refresh_profile(client, events_tx.clone())); + if settings.update_check.unwrap_or(true) && !update::disabled_by_env() { + tasks.push(update::spawn_check(events_tx.clone())); + } tasks.push(data::spawn_load_instruments(app.uuid.clone(), events_tx)); Ok(tasks) diff --git a/src/tui/app/events/mod.rs b/src/tui/app/events/mod.rs index cb21600..53b8e8c 100644 --- a/src/tui/app/events/mod.rs +++ b/src/tui/app/events/mod.rs @@ -112,6 +112,15 @@ impl App { DataEvent::Profile(Ok(profile)) => { self.profile = Some(*profile); } + DataEvent::UpdateAvailable(notice) => { + if notice.announce { + self.toast( + ToastLevel::Info, + format!("kite {} is available: {}", notice.latest.tag(), notice.hint), + ); + } + self.update_available = Some(notice.latest); + } DataEvent::Gtts(Ok(gtts)) => { self.gtts = Some(gtts); self.gtts_gen += 1; @@ -329,6 +338,34 @@ mod tests { use kiteconnect::ticker::TickerEvent; use std::sync::Arc; + #[test] + fn a_newer_release_toasts_only_when_announced_and_always_marks_the_header() { + use crate::app::release::Version; + use crate::tui::update::Notice; + let latest = Version::parse("9.0.0").unwrap(); + for announce in [true, false] { + let mut app = test_app(); + let before = app.toasts().len(); + app.on_event(AppEvent::Data(DataEvent::UpdateAvailable(Notice { + latest, + announce, + hint: "run kite upgrade", + }))); + assert_eq!(app.update_available, Some(latest)); + let toasts: Vec<_> = app + .toasts() + .iter() + .skip(before) + .map(|t| t.text.as_str()) + .collect(); + if announce { + assert_eq!(toasts, ["kite v9.0.0 is available: run kite upgrade"]); + } else { + assert!(toasts.is_empty(), "{toasts:?}"); + } + } + } + #[test] fn a_holdings_load_error_stays_until_holdings_load() { let mut app = test_app(); diff --git a/src/tui/app/mod.rs b/src/tui/app/mod.rs index 8ab4392..57c73c2 100644 --- a/src/tui/app/mod.rs +++ b/src/tui/app/mod.rs @@ -257,6 +257,7 @@ pub struct App { pub orders: Option>, pub gtts: Option>, pub margin_available: Option, + pub update_available: Option, pub funds: Option, diff --git a/src/tui/app/state.rs b/src/tui/app/state.rs index 1ebe6c4..d773afe 100644 --- a/src/tui/app/state.rs +++ b/src/tui/app/state.rs @@ -94,6 +94,7 @@ impl App { orders: None, gtts: None, margin_available: None, + update_available: None, funds: None, profile: None, instruments: None, diff --git a/src/tui/data.rs b/src/tui/data.rs index a4c7ecf..57cbacc 100644 --- a/src/tui/data.rs +++ b/src/tui/data.rs @@ -203,6 +203,7 @@ pub enum DataEvent { interval: ChartInterval, result: Result, String>, }, + UpdateAvailable(crate::tui::update::Notice), } pub(crate) fn api_err(err: impl Into) -> String { diff --git a/src/tui/settings.rs b/src/tui/settings.rs index ddabc19..f63a9ee 100644 --- a/src/tui/settings.rs +++ b/src/tui/settings.rs @@ -541,6 +541,7 @@ pub struct Settings { #[serde(default, deserialize_with = "split_entries")] pub splits: HashMap, pub workspaces: Option, + pub update_check: Option, } impl Settings { diff --git a/src/tui/ui/header.rs b/src/tui/ui/header.rs index eeb5d42..85a4ef1 100644 --- a/src/tui/ui/header.rs +++ b/src/tui/ui/header.rs @@ -1,4 +1,5 @@ use super::{HitAction, bar_style}; +use crate::app::release::Version; use crate::tui::app::App; use crate::tui::event::WsState; use crate::tui::format; @@ -134,6 +135,7 @@ fn status_line( ws_state: WsState, fatal_reason: Option<&str>, margin: Option, + update: Option, now: u64, uptime_secs: u64, width: u16, @@ -183,6 +185,12 @@ fn status_line( )); } fields.push((format::uptime(uptime_secs), format::dim())); + if let Some(latest) = update { + fields.push(( + format!("update {}", latest.tag()), + Style::default().fg(format::warning()), + )); + } let sep_width = u16::try_from(format::display_width(STATUS_SEP)).unwrap_or(u16::MAX); let mut spans = vec![Span::styled(ws_label, ws_style)]; @@ -262,6 +270,7 @@ pub(super) fn draw_header(frame: &mut Frame, area: Rect, app: &App) { app.ws_state, app.ws_fatal.as_deref(), app.margin_available, + app.update_available, now, app.started_at.elapsed().as_secs(), status_area.width.saturating_sub(1), @@ -275,6 +284,7 @@ pub(super) fn draw_header(frame: &mut Frame, area: Rect, app: &App) { #[cfg(test)] mod tests { use super::{bar_style, draw_header, pieces_width, status_line, strip_pieces}; + use crate::app::release::Version; use crate::tui::app::App; use crate::tui::event::WsState; use crate::tui::format; @@ -301,6 +311,7 @@ mod tests { ws, None, margin, + None, FIXTURE_NOW, FIXTURE_UPTIME, width, @@ -349,6 +360,7 @@ mod tests { WsState::Connected, None, None, + None, FIXTURE_NOW, 99 * 3600 + 59 * 60, 64, @@ -358,6 +370,7 @@ mod tests { WsState::Connected, None, None, + None, FIXTURE_NOW, 99 * 3600 + 59 * 60, 6 + 1 + 7 + 11 + 11, @@ -365,6 +378,43 @@ mod tests { assert_eq!(tight, "● live | open | 10:30:00 "); } + #[test] + fn a_newer_release_is_the_first_field_to_drop() { + let _guard = settings::theme_guard(Theme::DEFAULT); + let update = Version::parse("9.0.0").ok(); + let wide = status_line( + WsState::Connected, + None, + None, + update, + FIXTURE_NOW, + FIXTURE_UPTIME, + 64, + ); + assert_eq!( + text(&wide), + "● live | open | 10:30:00 | up 1m 20s | update v9.0.0 " + ); + let badge = wide + .spans + .iter() + .find(|span| span.content.as_ref() == "update v9.0.0"); + assert_eq!( + badge.and_then(|span| span.style.fg), + Some(format::warning()) + ); + let narrow = status_line( + WsState::Connected, + None, + None, + update, + FIXTURE_NOW, + FIXTURE_UPTIME, + 40, + ); + assert_eq!(text(&narrow), "● live | open | 10:30:00 | up 1m 20s "); + } + #[test] fn the_connection_label_is_whole_or_absent() { let _guard = settings::theme_guard(Theme::DEFAULT); @@ -403,6 +453,7 @@ mod tests { state, expired.then_some(crate::tui::app::SESSION_EXPIRED), None, + None, FIXTURE_NOW, FIXTURE_UPTIME, 40, @@ -419,6 +470,7 @@ mod tests { WsState::Closed, Some("ticker subscription limit exceeded"), None, + None, FIXTURE_NOW, FIXTURE_UPTIME, 100, @@ -449,6 +501,7 @@ mod tests { WsState::Connected, None, Some(1.0), + None, FIXTURE_NOW, FIXTURE_UPTIME, 64, @@ -488,6 +541,7 @@ mod tests { app.ws_state, app.ws_fatal.as_deref(), app.margin_available, + app.update_available, FIXTURE_NOW, FIXTURE_UPTIME, status_area.width - 1, diff --git a/src/tui/update.rs b/src/tui/update.rs new file mode 100644 index 0000000..4146cff --- /dev/null +++ b/src/tui/update.rs @@ -0,0 +1,248 @@ +//! Tells a running TUI that a newer kite release exists. + +use crate::app::release::{self, Version}; +use crate::tui::data::{DataEvent, send}; +use crate::tui::event::AppEvent; +use serde::{Deserialize, Serialize}; +use std::future::Future; +use std::path::{Path, PathBuf}; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; + +const DISABLE_ENV: &str = "KITE_NO_UPDATE_CHECK"; +const CHECK_EVERY_SECS: u64 = 24 * 60 * 60; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Notice { + pub latest: Version, + /// False once an earlier session already announced this version. + pub announce: bool, + pub hint: &'static str, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +struct Cache { + checked_at: u64, + latest: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + notified: Option, +} + +#[must_use] +pub fn disabled_by_env() -> bool { + std::env::var(DISABLE_ENV).is_ok_and(|value| !value.is_empty() && value != "0") +} + +pub fn spawn_check(tx: mpsc::Sender) -> JoinHandle<()> { + tokio::spawn(async move { + let Ok(installed) = Version::installed() else { + return; + }; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_secs()); + let path = cache_path(); + let Some((latest, announce)) = + resolve(path.as_deref(), now, installed, release::latest).await + else { + return; + }; + let notice = Notice { + latest, + announce, + hint: upgrade_hint(), + }; + send(&tx, DataEvent::UpdateAvailable(notice)).await; + }) +} + +/// Returns the newer release and whether to announce it, reusing a lookup +/// younger than a day so several open windows share one request. +async fn resolve( + path: Option<&Path>, + now: u64, + installed: Version, + fetch: F, +) -> Option<(Version, bool)> +where + F: FnOnce() -> Fut, + Fut: Future>, +{ + let mut cache = path.and_then(read_cache).unwrap_or_default(); + let cached = Version::parse(&cache.latest) + .ok() + .filter(|_| now.saturating_sub(cache.checked_at) < CHECK_EVERY_SECS); + let mut dirty = false; + let latest = if let Some(latest) = cached { + latest + } else { + let latest = fetch().await.ok()?; + cache.checked_at = now; + cache.latest = latest.to_string(); + dirty = true; + latest + }; + let newer = latest > installed; + let announce = newer && cache.notified.as_deref() != Some(cache.latest.as_str()); + if announce { + cache.notified = Some(cache.latest.clone()); + dirty = true; + } + if dirty && let Some(path) = path { + let _ = crate::util::save_json_atomic(path, &cache); + } + newer.then_some((latest, announce)) +} + +fn cache_path() -> Option { + let mut path = std::env::var_os("XDG_CACHE_HOME") + .filter(|path| Path::new(path).is_absolute()) + .map(PathBuf::from) + .or_else(dirs::cache_dir)?; + path.push("kite"); + path.push("update.json"); + Some(path) +} + +fn read_cache(path: &Path) -> Option { + serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok() +} + +fn upgrade_hint() -> &'static str { + let exe = std::env::current_exe().and_then(std::fs::canonicalize); + hint_for(exe.as_deref().unwrap_or(Path::new(""))) +} + +fn hint_for(exe: &Path) -> &'static str { + let exe = exe.to_string_lossy(); + if exe.contains("/nix/store/") || exe.contains("/Cellar/") { + "upgrade with your package manager" + } else { + "run kite upgrade" + } +} + +#[cfg(test)] +mod tests { + use super::{Cache, hint_for, read_cache, resolve}; + use crate::app::release::Version; + use std::cell::Cell; + use std::path::{Path, PathBuf}; + + const DAY: u64 = 24 * 60 * 60; + + fn v(text: &str) -> Version { + Version::parse(text).unwrap() + } + + fn temp_cache(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "kite-update-{name}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = std::fs::remove_dir_all(&dir); + dir.join("update.json") + } + + async fn run( + path: &Path, + now: u64, + installed: &str, + remote: &str, + calls: &Cell, + ) -> Option<(String, bool)> { + resolve(Some(path), now, v(installed), || async { + calls.set(calls.get() + 1); + Ok(v(remote)) + }) + .await + .map(|(latest, announce)| (latest.to_string(), announce)) + } + + #[tokio::test] + async fn a_newer_release_is_announced_once_and_then_shown_quietly() { + let path = temp_cache("announce"); + let calls = Cell::new(0); + assert_eq!( + run(&path, 1_000, "0.2.0", "0.3.0", &calls).await, + Some(("0.3.0".into(), true)) + ); + assert_eq!( + run(&path, 2_000, "0.2.0", "0.3.0", &calls).await, + Some(("0.3.0".into(), false)), + "a second window does not toast again" + ); + assert_eq!(calls.get(), 1, "the second window reuses the cached lookup"); + } + + #[tokio::test] + async fn the_lookup_repeats_after_a_day_and_announces_a_new_version() { + let path = temp_cache("expire"); + let calls = Cell::new(0); + run(&path, 1_000, "0.2.0", "0.3.0", &calls).await; + assert_eq!( + run(&path, 1_000 + DAY, "0.2.0", "0.4.0", &calls).await, + Some(("0.4.0".into(), true)) + ); + assert_eq!(calls.get(), 2); + } + + #[tokio::test] + async fn an_up_to_date_install_gets_no_notice_but_caches_the_lookup() { + let path = temp_cache("current"); + let calls = Cell::new(0); + assert_eq!(run(&path, 1_000, "0.3.0", "0.3.0", &calls).await, None); + assert_eq!(run(&path, 2_000, "0.3.0", "0.3.0", &calls).await, None); + assert_eq!(calls.get(), 1); + } + + #[tokio::test] + async fn upgrading_past_the_cached_release_clears_the_notice() { + let path = temp_cache("upgraded"); + let calls = Cell::new(0); + run(&path, 1_000, "0.2.0", "0.3.0", &calls).await; + assert_eq!(run(&path, 2_000, "0.3.0", "0.3.0", &calls).await, None); + } + + #[tokio::test] + async fn a_failed_lookup_is_silent_and_not_cached() { + let path = temp_cache("failed"); + let notice = resolve(Some(&path), 1_000, v("0.2.0"), || async { + Err(anyhow::anyhow!("offline")) + }) + .await; + assert_eq!(notice, None); + assert!(read_cache(&path).is_none()); + } + + #[tokio::test] + async fn a_corrupt_cache_falls_back_to_a_fresh_lookup() { + let path = temp_cache("corrupt"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, "not json").unwrap(); + let calls = Cell::new(0); + assert_eq!( + run(&path, 1_000, "0.2.0", "0.3.0", &calls).await, + Some(("0.3.0".into(), true)) + ); + let cache: Cache = read_cache(&path).unwrap(); + assert_eq!(cache.latest, "0.3.0"); + } + + #[test] + fn package_manager_installs_are_told_to_use_their_package_manager() { + assert_eq!( + hint_for(Path::new("/nix/store/abc-kite-0.2.0/bin/kite")), + "upgrade with your package manager" + ); + assert_eq!( + hint_for(Path::new("/opt/homebrew/Cellar/kite/0.2.0/bin/kite")), + "upgrade with your package manager" + ); + assert_eq!( + hint_for(Path::new("/home/u/.local/bin/kite")), + "run kite upgrade" + ); + } +} From 7e18751fcadc7764146fb6a90b59d2f0b92c39d7 Mon Sep 17 00:00:00 2001 From: Karan Sharma Date: Tue, 17 Nov 2026 13:05:01 +0530 Subject: [PATCH 4/4] fix(tui): keep the update notice honest when the cache or network fails From review: a failed lookup hid a newer release the cache already knew about, a cache dated in the future stayed fresh, an unwritable cache toasted on every launch, and the package-manager hint missed symlinked installs that kite upgrade refuses. The hint now asks kite upgrade's own install check, and the tests clean up their temp directories. --- docs/guide/tui.md | 6 +- src/commands/mod.rs | 2 +- src/commands/upgrade.rs | 6 ++ src/tui/update.rs | 133 ++++++++++++++++++++++++---------------- 4 files changed, 91 insertions(+), 56 deletions(-) diff --git a/docs/guide/tui.md b/docs/guide/tui.md index 51ef230..0c53d0d 100644 --- a/docs/guide/tui.md +++ b/docs/guide/tui.md @@ -657,9 +657,9 @@ You can run several TUI instances at once in separate terminals or tmux panes. T At startup the TUI checks GitHub for a newer `kite` release in the background. It never delays startup or sign-in, and it never upgrades on its own. -- **What you see:** When a newer release exists, the header status strip shows `update vX.Y.Z` in the warning colour, and a toast names the command to run. The toast appears once per release; later sessions show only the header item. On a narrow terminal the header item is the first status field to drop. -- **How to upgrade:** Quit the TUI and run `kite upgrade`. When the binary runs from a Nix store or Homebrew Cellar path, the toast says to upgrade with your package manager instead. -- **How often:** At most once a day. The result is cached in `~/.cache/kite/update.json`, so several open windows share one lookup. A failed lookup shows nothing and is retried at the next launch. +- **What you see:** When a newer release exists, the header status strip shows `update vX.Y.Z` in the warning colour, and a toast names the command to run. The toast appears once per release; later sessions show only the header item. The header item has the lowest priority in the status strip, so a narrow terminal hides it before the other fields. +- **How to upgrade:** Quit the TUI and run `kite upgrade`. When `kite upgrade` would refuse to replace the binary (a Nix store path, a symlink placed by a package manager such as Homebrew, or a directory you cannot write to), the toast says to upgrade with your package manager instead. +- **How often:** At most once a day. The result is cached in `~/.cache/kite/update.json`, so windows opened later that day reuse it; windows started at the same moment may each look it up. When a lookup fails, the TUI keeps showing a newer release it already knows about and retries at the next launch. If the cache cannot be written, the header item still appears but the toast does not, so it cannot repeat on every launch. - **What it sends:** One unauthenticated request to `github.com/zerodha/kite-cli/releases/latest`, the same lookup `kite upgrade --check` makes. No user ID or session data is sent. - **Turning it off:** Set `"update_check": false` in `tui.json` or `KITE_NO_UPDATE_CHECK=1` in the environment. `kite upgrade --check` and `kite doctor` still check on demand. diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 5b343be..1360a48 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -10,7 +10,7 @@ mod orders; mod portfolio; mod request; mod stream; -mod upgrade; +pub(crate) mod upgrade; mod user; use crate::app::output::Output; diff --git a/src/commands/upgrade.rs b/src/commands/upgrade.rs index 57155d4..c35360d 100644 --- a/src/commands/upgrade.rs +++ b/src/commands/upgrade.rs @@ -69,6 +69,12 @@ pub async fn upgrade(rt: &Runtime, args: &UpgradeArgs) -> Result { )) } +/// Whether `kite upgrade` may replace the running binary, as opposed to +/// refusing and pointing at a package manager. +pub(crate) fn can_self_upgrade() -> bool { + std::env::current_exe().is_ok_and(|exe| install_dir(&exe, invoked_path().as_deref()).is_ok()) +} + /// The `kite` path the shell ran, which may be a symlink to `current_exe`. fn invoked_path() -> Option { let arg0 = PathBuf::from(std::env::args_os().next()?); diff --git a/src/tui/update.rs b/src/tui/update.rs index 4146cff..7062179 100644 --- a/src/tui/update.rs +++ b/src/tui/update.rs @@ -69,27 +69,32 @@ where Fut: Future>, { let mut cache = path.and_then(read_cache).unwrap_or_default(); - let cached = Version::parse(&cache.latest) - .ok() - .filter(|_| now.saturating_sub(cache.checked_at) < CHECK_EVERY_SECS); + let known = Version::parse(&cache.latest).ok(); + let fresh = cache.checked_at <= now && now - cache.checked_at < CHECK_EVERY_SECS; let mut dirty = false; - let latest = if let Some(latest) = cached { - latest - } else { - let latest = fetch().await.ok()?; - cache.checked_at = now; - cache.latest = latest.to_string(); - dirty = true; - latest + let latest = match known.filter(|_| fresh) { + Some(latest) => latest, + None => match fetch().await { + Ok(latest) => { + cache.checked_at = now; + cache.latest = latest.to_string(); + dirty = true; + latest + } + Err(_) => known?, + }, }; let newer = latest > installed; - let announce = newer && cache.notified.as_deref() != Some(cache.latest.as_str()); + let mut announce = newer && cache.notified.as_deref() != Some(cache.latest.as_str()); if announce { cache.notified = Some(cache.latest.clone()); dirty = true; } - if dirty && let Some(path) = path { - let _ = crate::util::save_json_atomic(path, &cache); + if dirty { + let saved = path.is_some_and(|path| crate::util::save_json_atomic(path, &cache).is_ok()); + // Without a cache every launch would announce again, so stay quiet and + // rely on the header item. + announce &= saved; } newer.then_some((latest, announce)) } @@ -109,22 +114,16 @@ fn read_cache(path: &Path) -> Option { } fn upgrade_hint() -> &'static str { - let exe = std::env::current_exe().and_then(std::fs::canonicalize); - hint_for(exe.as_deref().unwrap_or(Path::new(""))) -} - -fn hint_for(exe: &Path) -> &'static str { - let exe = exe.to_string_lossy(); - if exe.contains("/nix/store/") || exe.contains("/Cellar/") { - "upgrade with your package manager" - } else { + if crate::commands::upgrade::can_self_upgrade() { "run kite upgrade" + } else { + "upgrade with your package manager" } } #[cfg(test)] mod tests { - use super::{Cache, hint_for, read_cache, resolve}; + use super::{Cache, read_cache, resolve}; use crate::app::release::Version; use std::cell::Cell; use std::path::{Path, PathBuf}; @@ -135,14 +134,25 @@ mod tests { Version::parse(text).unwrap() } - fn temp_cache(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!( - "kite-update-{name}-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - let _ = std::fs::remove_dir_all(&dir); - dir.join("update.json") + struct TempCache(PathBuf); + + impl TempCache { + fn new(name: &str) -> Self { + let dir = + std::env::temp_dir().join(format!("kite-update-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + Self(dir) + } + + fn file(&self) -> PathBuf { + self.0.join("update.json") + } + } + + impl Drop for TempCache { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } } async fn run( @@ -162,7 +172,8 @@ mod tests { #[tokio::test] async fn a_newer_release_is_announced_once_and_then_shown_quietly() { - let path = temp_cache("announce"); + let dir = TempCache::new("announce"); + let path = dir.file(); let calls = Cell::new(0); assert_eq!( run(&path, 1_000, "0.2.0", "0.3.0", &calls).await, @@ -178,7 +189,8 @@ mod tests { #[tokio::test] async fn the_lookup_repeats_after_a_day_and_announces_a_new_version() { - let path = temp_cache("expire"); + let dir = TempCache::new("expire"); + let path = dir.file(); let calls = Cell::new(0); run(&path, 1_000, "0.2.0", "0.3.0", &calls).await; assert_eq!( @@ -190,7 +202,8 @@ mod tests { #[tokio::test] async fn an_up_to_date_install_gets_no_notice_but_caches_the_lookup() { - let path = temp_cache("current"); + let dir = TempCache::new("current"); + let path = dir.file(); let calls = Cell::new(0); assert_eq!(run(&path, 1_000, "0.3.0", "0.3.0", &calls).await, None); assert_eq!(run(&path, 2_000, "0.3.0", "0.3.0", &calls).await, None); @@ -199,7 +212,8 @@ mod tests { #[tokio::test] async fn upgrading_past_the_cached_release_clears_the_notice() { - let path = temp_cache("upgraded"); + let dir = TempCache::new("upgraded"); + let path = dir.file(); let calls = Cell::new(0); run(&path, 1_000, "0.2.0", "0.3.0", &calls).await; assert_eq!(run(&path, 2_000, "0.3.0", "0.3.0", &calls).await, None); @@ -207,7 +221,8 @@ mod tests { #[tokio::test] async fn a_failed_lookup_is_silent_and_not_cached() { - let path = temp_cache("failed"); + let dir = TempCache::new("failed"); + let path = dir.file(); let notice = resolve(Some(&path), 1_000, v("0.2.0"), || async { Err(anyhow::anyhow!("offline")) }) @@ -218,7 +233,8 @@ mod tests { #[tokio::test] async fn a_corrupt_cache_falls_back_to_a_fresh_lookup() { - let path = temp_cache("corrupt"); + let dir = TempCache::new("corrupt"); + let path = dir.file(); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(&path, "not json").unwrap(); let calls = Cell::new(0); @@ -230,19 +246,32 @@ mod tests { assert_eq!(cache.latest, "0.3.0"); } - #[test] - fn package_manager_installs_are_told_to_use_their_package_manager() { - assert_eq!( - hint_for(Path::new("/nix/store/abc-kite-0.2.0/bin/kite")), - "upgrade with your package manager" - ); - assert_eq!( - hint_for(Path::new("/opt/homebrew/Cellar/kite/0.2.0/bin/kite")), - "upgrade with your package manager" - ); - assert_eq!( - hint_for(Path::new("/home/u/.local/bin/kite")), - "run kite upgrade" - ); + #[tokio::test] + async fn a_cache_dated_in_the_future_is_refreshed() { + let dir = TempCache::new("future"); + let path = dir.file(); + let calls = Cell::new(0); + run(&path, 10 * DAY, "0.2.0", "0.3.0", &calls).await; + run(&path, 1_000, "0.2.0", "0.3.0", &calls).await; + assert_eq!(calls.get(), 2); + } + + #[tokio::test] + async fn an_offline_launch_keeps_showing_a_known_newer_release() { + let dir = TempCache::new("offline"); + let path = dir.file(); + let calls = Cell::new(0); + run(&path, 1_000, "0.2.0", "0.3.0", &calls).await; + let notice = resolve(Some(&path), 1_000 + DAY, v("0.2.0"), || async { + Err(anyhow::anyhow!("offline")) + }) + .await; + assert_eq!(notice, Some((v("0.3.0"), false))); + } + + #[tokio::test] + async fn without_a_cache_the_release_is_shown_but_never_announced() { + let notice = resolve(None, 1_000, v("0.2.0"), || async { Ok(v("0.3.0")) }).await; + assert_eq!(notice, Some((v("0.3.0"), false))); } }