Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/CLI_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ Options:
Number of iceberg legs, between 2 and 50

--iceberg-quantity <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>
Auction number for auction variety orders
Expand Down
1 change: 1 addition & 0 deletions docs/guide/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
21 changes: 20 additions & 1 deletion docs/guide/tui.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `│`:
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -639,10 +641,27 @@ 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).

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.

### 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. 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.

---

Expand Down
2 changes: 1 addition & 1 deletion src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 6 additions & 0 deletions src/commands/upgrade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ pub async fn upgrade(rt: &Runtime, args: &UpgradeArgs) -> Result<Output> {
))
}

/// 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<PathBuf> {
let arg0 = PathBuf::from(std::env::args_os().next()?);
Expand Down
4 changes: 4 additions & 0 deletions src/tui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ mod subscriptions;
mod ticket;
mod ticks;
mod ui;
mod update;
mod workspace;

use crate::app::runtime::Runtime;
Expand Down Expand Up @@ -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)
Expand Down
37 changes: 37 additions & 0 deletions src/tui/app/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand Down
1 change: 1 addition & 0 deletions src/tui/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ pub struct App {
pub orders: Option<Vec<Order>>,
pub gtts: Option<Vec<Gtt>>,
pub margin_available: Option<f64>,
pub update_available: Option<crate::app::release::Version>,

pub funds: Option<Funds>,

Expand Down
1 change: 1 addition & 0 deletions src/tui/app/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ impl App {
orders: None,
gtts: None,
margin_available: None,
update_available: None,
funds: None,
profile: None,
instruments: None,
Expand Down
1 change: 1 addition & 0 deletions src/tui/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ pub enum DataEvent {
interval: ChartInterval,
result: Result<Vec<Candle>, String>,
},
UpdateAvailable(crate::tui::update::Notice),
}

pub(crate) fn api_err(err: impl Into<anyhow::Error>) -> String {
Expand Down
1 change: 1 addition & 0 deletions src/tui/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,7 @@ pub struct Settings {
#[serde(default, deserialize_with = "split_entries")]
pub splits: HashMap<String, f32>,
pub workspaces: Option<serde_json::Value>,
pub update_check: Option<bool>,
}

impl Settings {
Expand Down
54 changes: 54 additions & 0 deletions src/tui/ui/header.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -134,6 +135,7 @@ fn status_line(
ws_state: WsState,
fatal_reason: Option<&str>,
margin: Option<f64>,
update: Option<Version>,
now: u64,
uptime_secs: u64,
width: u16,
Expand Down Expand Up @@ -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)];
Expand Down Expand Up @@ -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),
Expand All @@ -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;
Expand All @@ -301,6 +311,7 @@ mod tests {
ws,
None,
margin,
None,
FIXTURE_NOW,
FIXTURE_UPTIME,
width,
Expand Down Expand Up @@ -349,6 +360,7 @@ mod tests {
WsState::Connected,
None,
None,
None,
FIXTURE_NOW,
99 * 3600 + 59 * 60,
64,
Expand All @@ -358,13 +370,51 @@ mod tests {
WsState::Connected,
None,
None,
None,
FIXTURE_NOW,
99 * 3600 + 59 * 60,
6 + 1 + 7 + 11 + 11,
));
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);
Expand Down Expand Up @@ -403,6 +453,7 @@ mod tests {
state,
expired.then_some(crate::tui::app::SESSION_EXPIRED),
None,
None,
FIXTURE_NOW,
FIXTURE_UPTIME,
40,
Expand All @@ -419,6 +470,7 @@ mod tests {
WsState::Closed,
Some("ticker subscription limit exceeded"),
None,
None,
FIXTURE_NOW,
FIXTURE_UPTIME,
100,
Expand Down Expand Up @@ -449,6 +501,7 @@ mod tests {
WsState::Connected,
None,
Some(1.0),
None,
FIXTURE_NOW,
FIXTURE_UPTIME,
64,
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading