Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

5.5 KB
Raw Blame
//! `codync-host tui`: the Codync client for a terminal. It talks to a host over the
//! same HTTP + SSE API as the phone and desktop apps (locally: no pairing needed).

mod app;
mod appearance;
mod choice;
mod connections;
mod details;
mod drafts;
mod l10n;
mod manage;
mod md;
pub(crate) mod net;
mod sheets;
mod view;

use anyhow::{Context, Result};
use crossterm::event::{
    DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste, EnableFocusChange,
    EnableMouseCapture, Event, EventStream, KeyEventKind, KeyboardEnhancementFlags, PopKeyboardEnhancementFlags,
    PushKeyboardEnhancementFlags,
};
use crossterm::execute;
use crossterm::terminal::{self, EnterAlternateScreen, LeaveAlternateScreen};
use futures::StreamExt;
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use std::io::Write as _;
use std::time::Duration;

/// Puts the terminal back however we leave (including a panic).
struct Restore {
    enhanced: bool,
}

impl Drop for Restore {
    fn drop(&mut self) {
        restore(self.enhanced);
    }
}

fn restore(enhanced: bool) {
    let mut out = std::io::stdout();
    if enhanced {
        let _ = execute!(out, PopKeyboardEnhancementFlags);
    }
    let _ = execute!(out, DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, LeaveAlternateScreen);
    let _ = terminal::disable_raw_mode();
}

/// `url`: the host to attach to, when not this computer's on `port`.
pub async fn run(url: Option<String>, port: u16, token: Option<String>) -> Result<()> {
    let on_this_computer = url.is_none();
    let url = url.unwrap_or_else(|| format!("http://127.0.0.1:{port}"));
    let client = net::Client::new(&url, token.as_deref());
    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
    let mut app = app::App::new(client.clone(), tx.clone(), url);
    app.on_this_computer = on_this_computer;
    let mut drafts = match drafts::Drafts::load(&app.url).await {
        Ok(saved) => {
            app.drafts = saved.restore();
            Some(saved)
        }
        Err(error) => {
            app.flash(&format!("Couldn't restore drafts: {error}"));
            None
        }
    };

    terminal::enable_raw_mode().context("this needs an interactive terminal")?;
    let mut out = std::io::stdout();
    execute!(out, EnterAlternateScreen, EnableMouseCapture, EnableBracketedPaste, EnableFocusChange)?;
    // Lets terminals that support it report shift+enter apart from enter.
    let enhanced = terminal::supports_keyboard_enhancement().unwrap_or(false)
        && execute!(out, PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)).is_ok();
    let _restore = Restore { enhanced };
    let hook = std::panic::take_hook();
    let reporter = client.clone();
    std::panic::set_hook(Box::new(move |info| {
        restore(enhanced);
        reporter.report_panic(info);
        hook(info);
    }));
    let mut term = Terminal::new(CrosstermBackend::new(out))?;

    app.call("hello", serde_json::json!({}), app::After::Hello);
    client.spawn_stream(tx);
    let mut events = EventStream::new();
    let mut tick = tokio::time::interval(Duration::from_millis(100));
    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
    let mut dirty = true;
    // A setup terminal has the real screen (not the alternate one) while it runs.
    let mut in_shell = false;
    loop {
        if app.shell.is_some() != in_shell {
            in_shell = !in_shell;
            let out = term.backend_mut();
            if in_shell {
                execute!(out, DisableMouseCapture, LeaveAlternateScreen)?;
                write!(out, "\x1b[2J\x1b[H\x1b[2m^] closes the terminal and goes back to Codync\x1b[0m\r\n")?;
            } else {
                execute!(out, EnterAlternateScreen, EnableMouseCapture)?;
                term.clear()?;
            }
        }
        if let Some(sh) = app.shell.as_mut().filter(|s| !s.out.is_empty()) {
            let out = term.backend_mut();
            out.write_all(&std::mem::take(&mut sh.out))?;
            out.flush()?;
        }
        if dirty && !in_shell {
            app.tick();
            app.report_screen();
            term.draw(|f| view::draw(f, &mut app))?;
            dirty = false;
        }
        tokio::select! {
            ev = events.next() => match ev {
                Some(Ok(Event::Key(k))) if k.kind != KeyEventKind::Release => app.on_key(k),
                Some(Ok(Event::Paste(s))) => app.on_paste(&s),
                Some(Ok(Event::Mouse(m))) => app.on_mouse(m),
                Some(Ok(Event::FocusGained)) => app.term_focused = true,
                Some(Ok(Event::FocusLost)) => app.term_focused = false,
                Some(Ok(Event::Resize(cols, rows))) => app.on_resize(cols, rows),
                Some(Ok(_)) => {}
                Some(Err(_)) | None => break,
            },
            Some(msg) = rx.recv() => {
                app.on_msg(msg);
                // Apply a burst (catch-up) before drawing once.
                while let Ok(msg) = rx.try_recv() {
                    app.on_msg(msg);
                }
            }
            _ = tick.tick() => {
                if !app.animating() {
                    continue;
                }
                app.frame += 1;
            }
        }
        dirty = true;
        if let Some(saved) = drafts.as_mut()
            && let Err(error) = saved.save(&app.drafts).await
        {
            app.flash(&format!("Couldn't save drafts: {error}. Text stays in this session."));
        }
        if app.quit {
            break;
        }
    }
    Ok(())
}