linear-tui 0.9.0

A TUI client for Linear.app — manage issues, projects, and cycles from your terminal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
mod api;
mod app;
mod auth;
mod cli;
mod config;
mod dispatch;
mod event;
mod fuzzy;
mod grouping;
mod herdr;
mod keys;
mod logging;
mod message;
mod palette;
mod private_file;
mod snapshot;
mod store;
mod ui;
mod usecase;

use std::collections::HashMap;
use std::io::{self, Write};
use std::sync::Arc;
use std::time::{Duration, Instant};

use anyhow::Result;
use crossterm::{
    event::{
        DisableMouseCapture, EnableMouseCapture, KeyboardEnhancementFlags,
        PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
    },
    execute,
    terminal::{
        EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
        supports_keyboard_enhancement,
    },
};
use ratatui::{Terminal, backend::CrosstermBackend};
use tokio::sync::mpsc;

use base64::Engine;

use api::client::LinearClient;
use api::ids::OrganizationId;
use app::App;
use auth::token::TokenStore;
use config::Config;
use message::Message;

/// Spinner advance interval.
const TICK: Duration = Duration::from_millis(80);

#[tokio::main]
async fn main() -> Result<()> {
    let _log_guard = logging::init();

    let args: Vec<String> = std::env::args().collect();

    // `open <ID>` runs the TUI; every other subcommand runs without it.
    let open = match args.get(1).map(String::as_str) {
        Some("open") => {
            let [_, _, key] = args.as_slice() else {
                anyhow::bail!("Usage: linear-tui open <ID>");
            };
            Some(cli::issue_key(key)?)
        }
        Some(_) => return cli::handle_subcommand(&args[1..]).await,
        None => None,
    };

    // Load config and authenticate
    let mut config = Config::load()?;
    let token_store = TokenStore::new()?;
    let Some(auth) = authenticate(&token_store, &config).await? else {
        return Ok(());
    };
    tracing::info!(method = auth.label(), "authenticated successfully");
    let organization = auth.organization().map(|org| org.id.clone());

    // An entry for this directory in config.toml wins over the view
    // remembered for it.
    let origin = snapshot::Origin::current(std::env::current_dir()?);
    let pinned = config.workspace(&origin.workspace, &origin.cwd).cloned();
    let shelf = snapshot::state_dir()
        .map(|dir| snapshot::Shelf::new(&dir, &origin.workspace))
        .inspect_err(|e| tracing::warn!("snapshots disabled: {e:#}"))
        .ok();
    let restored = match &pinned {
        Some(entry) => {
            if entry.team.is_some() {
                config.ui.default_team.clone_from(&entry.team);
            }
            None
        }
        // Asked for an issue, the remembered view is not reopened.
        None if open.is_some() => None,
        None => shelf
            .as_ref()
            .and_then(|s| s.for_restore(origin.pid, organization.as_ref())),
    };
    let recorder = shelf.as_ref().map(|shelf| {
        shelf.prune();
        snapshot::Recorder::new(shelf, origin.pid)
    });

    // Run TUI
    run_tui(
        config,
        token_store,
        auth,
        Session {
            origin,
            restored,
            open,
            recorder,
            shelf,
            pinned: pinned.is_some(),
        },
    )
    .await
}

/// Where this instance runs, what it reopens, and where it records its view.
struct Session {
    origin: snapshot::Origin,
    restored: Option<snapshot::ViewSnapshot>,
    /// The issue `linear-tui open` asked for.
    open: Option<String>,
    recorder: Option<snapshot::Recorder>,
    /// Where a view to reopen is looked for after switching workspace.
    shelf: Option<snapshot::Shelf>,
    /// Whether config.toml pins this directory, which reopens no view.
    pinned: bool,
}

/// Resolve stored credentials, running first-run setup when there are none.
/// `None` means the user backed out of setup, which ends the run quietly.
async fn authenticate(
    token_store: &TokenStore,
    config: &Config,
) -> Result<Option<auth::AuthMethod>> {
    if auth::has_credentials(token_store, config)? {
        return auth::resolve_auth(token_store, config.auth.api_key.as_deref())
            .await
            .map(Some);
    }

    if !auth::setup::run(token_store).await? {
        return Ok(None);
    }

    // Setup may have written an API key, so the file on disk is newer than ours.
    let config = Config::load()?;
    auth::resolve_auth(token_store, config.auth.api_key.as_deref())
        .await
        .map(Some)
}

/// RAII guard so the terminal is restored even if the loop returns an error.
struct TerminalGuard {
    /// Whether the kitty keyboard protocol was successfully enabled.
    enhanced_keys: bool,
}

impl TerminalGuard {
    fn enter() -> Result<Self> {
        enable_raw_mode()?;
        execute!(io::stdout(), EnterAlternateScreen, EnableMouseCapture)?;

        // Linear binds actions to Ctrl+punctuation (copy ID, copy branch name)
        // and to Ctrl+M, none of which a legacy terminal can distinguish. The
        // kitty keyboard protocol reports them as distinct events; terminals
        // without it fall back to the plain-key aliases in `keys.rs`.
        let enhanced_keys = supports_keyboard_enhancement().unwrap_or(false);
        if enhanced_keys {
            execute!(
                io::stdout(),
                PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
            )?;
        }

        Ok(Self { enhanced_keys })
    }
}

impl Drop for TerminalGuard {
    fn drop(&mut self) {
        if self.enhanced_keys {
            let _ = execute!(io::stdout(), PopKeyboardEnhancementFlags);
        }
        let _ = execute!(io::stdout(), DisableMouseCapture, LeaveAlternateScreen);
        let _ = disable_raw_mode();
    }
}

type Term = Terminal<CrosstermBackend<io::Stdout>>;

/// Run the TUI until it quits. Switching workspace ends one session and
/// starts another on the same terminal: a new client, and a new `App`, since
/// nothing loaded from one workspace means anything in the next.
async fn run_tui(
    config: Config,
    token_store: TokenStore,
    auth: auth::AuthMethod,
    session: Session,
) -> Result<()> {
    let Session {
        origin,
        restored,
        open,
        mut recorder,
        shelf,
        pinned,
    } = session;
    let _guard = TerminalGuard::enter()?;
    let backend = CrosstermBackend::new(io::stdout());
    let mut terminal = Terminal::new(backend)?;
    terminal.hide_cursor()?;

    // Only the herdr plugin writes the agents file.
    let mut agents = herdr::available().then(herdr::AgentWatch::new).flatten();
    // The view each workspace was left on this run, to come back to.
    let mut left: HashMap<OrganizationId, snapshot::ViewSnapshot> = HashMap::new();
    let mut organization = auth.organization().map(|org| org.id.clone());
    let mut client = Arc::new(LinearClient::new(
        auth.into_credentials(token_store.clone()),
    ));
    let mut app = new_app(&config, &token_store, restored, open.as_deref());

    loop {
        run_session(
            &mut terminal,
            &mut app,
            &client,
            &origin,
            &mut recorder,
            &mut agents,
        )?;
        let Some(target) = app.switch_to.take() else {
            break;
        };
        // The one await on the UI's path: a token past its expiry is renewed
        // before the new session can send anything. The status line says so.
        match auth::switch_to(&token_store, config.auth.api_key.as_deref(), &target).await {
            Ok(auth) => {
                tracing::info!(organization = %target, "switched workspace");
                if let (Some(org), Some(view)) = (organization.take(), app.snapshot(&origin)) {
                    left.insert(org, view);
                }
                organization = Some(target.clone());
                client = Arc::new(LinearClient::new(
                    auth.into_credentials(token_store.clone()),
                ));
                let restored = if pinned {
                    None
                } else {
                    left.remove(&target).or_else(|| {
                        shelf
                            .as_ref()
                            .and_then(|s| s.for_restore(origin.pid, Some(&target)))
                    })
                };
                app = new_app(&config, &token_store, restored, None);
            }
            Err(e) => {
                tracing::warn!(error = %e, "could not switch workspace");
                app.set_error(format!("Could not switch workspace: {e:#}"));
            }
        }
    }

    if let Some(recorder) = &mut recorder
        && let Some(snapshot) = app.snapshot(&origin)
    {
        recorder.close(snapshot);
    }
    Ok(())
}

/// A fresh session's state, reopening `restored` or the issue `open` names.
fn new_app(
    config: &Config,
    token_store: &TokenStore,
    restored: Option<snapshot::ViewSnapshot>,
    open: Option<&str>,
) -> App {
    // `App::new` seeds the initial Teams/Viewer requests.
    let mut app = App::new(config);
    app.workspaces = workspace_entries(token_store);
    if let Some(snapshot) = restored {
        tracing::info!(updated_at = %snapshot.updated_at, "restoring the last view");
        app.restore(snapshot);
    }
    if let Some(identifier) = open {
        app.open_on_launch(identifier);
    }
    app
}

/// The signed-in workspaces the switcher offers. One not yet identified has
/// nothing to show, so it is left out until the next launch names it.
fn workspace_entries(token_store: &TokenStore) -> Vec<app::WorkspaceEntry> {
    let Ok(accounts) = token_store.load() else {
        return Vec::new();
    };
    accounts
        .accounts
        .iter()
        .filter_map(|account| {
            let org = account.organization.as_ref()?;
            Some(app::WorkspaceEntry {
                id: org.id.clone(),
                name: org.name.clone(),
                url_key: org.url_key.clone(),
                current: accounts.is_current(account),
            })
        })
        .collect()
}

/// Drive one session until the user quits or picks another workspace.
fn run_session(
    terminal: &mut Term,
    app: &mut App,
    client: &Arc<LinearClient>,
    origin: &snapshot::Origin,
    recorder: &mut Option<snapshot::Recorder>,
    agents: &mut Option<herdr::AgentWatch>,
) -> Result<()> {
    // A channel per session: answers still on their way from the last one
    // have nowhere to land.
    let (tx, mut rx) = mpsc::unbounded_channel::<Message>();
    let mut cache = ui::Cache::default();
    let mut last_tick = Instant::now();
    let mut dirty = true;

    loop {
        // A palette query that has rested long enough is searched now.
        if app.flush_palette_search(Instant::now()) {
            dirty = true;
        }

        // Spawn everything the UI has queued since the last pass. Each request
        // runs on the tokio runtime, so the UI never blocks on the network.
        while let Some(req) = app.outbox.requests.pop_front() {
            app.outbox.inflight += 1;
            let client = Arc::clone(client);
            let tx = tx.clone();
            let per_page = app.items_per_page;
            tokio::spawn(async move {
                let msg = dispatch::execute_request(&client, req, per_page).await;
                let _ = tx.send(msg);
            });
            dirty = true;
        }

        if dirty {
            terminal.draw(|f| ui::draw(f, app, &mut cache))?;
            dirty = false;
        }

        // Drain completed requests without blocking.
        let mut moved = false;
        while let Ok(msg) = rx.try_recv() {
            app.outbox.inflight = app.outbox.inflight.saturating_sub(1);
            app.handle_message(msg);
            moved = true;
        }

        if let Some(text) = app.outbox.clipboard.take() {
            copy_to_clipboard(&text)?;
        }

        if event::poll_and_handle(app)? {
            moved = true;
        }

        // Record where the user is once the view has rested. This is the
        // only place a snapshot is written — never from rendering.
        let now = Instant::now();
        if let Some(recorder) = recorder {
            if moved {
                recorder.touch(now);
            }
            if recorder.is_due(now)
                && let Some(snapshot) = app.snapshot(origin)
            {
                recorder.record(snapshot);
            }
        }
        dirty |= moved;

        // What the herdr plugin says its agents are working on.
        if let Some(watch) = agents
            && let Some(list) = watch.poll(now)
        {
            app.set_agents(list);
            dirty = true;
        }

        if app.loading() && last_tick.elapsed() >= TICK {
            app.tick_spinner();
            last_tick = Instant::now();
            dirty = true;
        }

        if app.should_quit {
            return Ok(());
        }
        if app.switch_to.is_some() {
            // Show "Switching to …" while the next session is prepared.
            terminal.draw(|f| ui::draw(f, app, &mut cache))?;
            return Ok(());
        }
    }
}

/// Push `text` to the system clipboard with an OSC 52 escape sequence.
///
/// This goes through the terminal rather than a platform clipboard API, so it
/// also works over SSH. Terminals that disable OSC 52 will simply ignore it,
/// and tmux needs `set -g set-clipboard on`.
fn copy_to_clipboard(text: &str) -> Result<()> {
    let encoded = base64::engine::general_purpose::STANDARD.encode(text);
    let mut stdout = io::stdout();
    write!(stdout, "\x1b]52;c;{encoded}\x07")?;
    stdout.flush()?;
    Ok(())
}