mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-15 18:59:33 +01:00
feat(desktop): blink the lid Apple logo while agents work
On a MacBook Pro with a PROLED XDR display, the lit Apple logo on the lid can blink while agents work and stop when they finish, so a run can be read from across the room. View > Blink Apple Logo While Agents Work picks a style (Calm, Slow, Wink, Heartbeat, Fast). It is off by default, and the menu exists only on a Mac that has the logo. Apple documents one control for the logo, `sudo defaults write com.apple.CoreBrightness LEBacklightMode -int 0`. The same setting is a property of BrightnessSystemClient in the private CoreBrightness framework, which a process of the logged-in user can set with no administrator, so nothing here needs a helper or a password. The setting is system-wide and survives a reboot, and the release profile has panic = "abort", so the work runs in a child process (this binary with --logo-blink) tied to the app by a pipe. When the pipe closes, however the app ended, the child restores the logo and exits. A marker file covers power loss and a SIGKILL of the child itself. The child asks api/sessions itself: WebKit stalls the event stream of a hidden page, which lost whole turns and ran a blink 39 s past the end. It sends the session cookie of its first answer with every poll, because a good password without a cookie creates a login session each time and Codeman evicts the oldest of 100. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
92797c2619
commit
cd4cee15a7
9 files changed
+1518
-19
No files matched your search
@@ -0,0 +1,285 @@
|
||||
//! How many agents are at work on a server, asked from outside the web view.
|
||||
//!
|
||||
//! The page knows this too, but it cannot be relied on for it: WebKit stalls the
|
||||
//! event stream of a hidden page. Measured on macOS 27.2 with the page hidden: a
|
||||
//! `session:idle` the server sent never reached it, its own watchdog reopened the
|
||||
//! stream 39 seconds later, and in another run a whole turn went unseen. A hidden
|
||||
//! window is the normal case for this question, so it is asked natively, of
|
||||
//! `api/sessions`, a stable route that works with any Codeman.
|
||||
//!
|
||||
//! A login has a price here that a single request does not show. A request with
|
||||
//! a good password and no session cookie makes Codeman create a login session,
|
||||
//! it keeps 100 of them, and the oldest goes first, so asking every two seconds
|
||||
//! with the password alone would log every browser out within minutes. So the
|
||||
//! cookie of the first answer goes along from then on, and Codeman reads the
|
||||
//! cookie first: the password is only used when the cookie has lapsed (a server
|
||||
//! restart), and then it creates the one new session that replaces it. Sending
|
||||
//! both also means a stale cookie costs no failed login. A refused login ends
|
||||
//! the polling for good, since Codeman counts each one against the login rate
|
||||
//! limit (see `probe`).
|
||||
|
||||
use serde::Deserialize;
|
||||
use std::time::Duration;
|
||||
use url::Url;
|
||||
|
||||
/// How long the logo can lag behind the server. The list is cached for a
|
||||
/// second on the server's side and is a few kilobytes.
|
||||
pub const POLL_EVERY: Duration = Duration::from_secs(2);
|
||||
const TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const SESSIONS_PATH: &str = "api/sessions";
|
||||
const COOKIE_NAME: &str = "codeman_session";
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Poll {
|
||||
/// This many agents are working.
|
||||
Working(u32),
|
||||
/// No answer this time. Worth asking again.
|
||||
Failed,
|
||||
/// The server turned the login down. Never ask again.
|
||||
Refused,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Session {
|
||||
#[serde(default)]
|
||||
status: String,
|
||||
#[serde(default)]
|
||||
mode: String,
|
||||
}
|
||||
|
||||
/// Codeman wraps the list in its API envelope, and older servers sent it bare.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Sessions {
|
||||
Envelope { data: Vec<Session> },
|
||||
Bare(Vec<Session>),
|
||||
}
|
||||
|
||||
/// Agents only: a shell tab with a `tail -f` is a run of output, which the
|
||||
/// server may call busy, and that is nobody's agent.
|
||||
fn count_working(body: &str) -> Option<u32> {
|
||||
let (Sessions::Envelope { data: sessions } | Sessions::Bare(sessions)) = serde_json::from_str(body).ok()?;
|
||||
let working = sessions.iter().filter(|s| s.status == "busy" && s.mode != "shell");
|
||||
u32::try_from(working.count()).ok()
|
||||
}
|
||||
|
||||
/// `name=value` out of a `Set-Cookie` header, for Codeman's session cookie.
|
||||
fn session_cookie(header: &str) -> Option<&str> {
|
||||
let pair = header.split(';').next()?.trim();
|
||||
let (name, value) = pair.split_once('=')?;
|
||||
(name == COOKIE_NAME && !value.is_empty()).then_some(pair)
|
||||
}
|
||||
|
||||
/// What a status code says about asking again.
|
||||
fn answer(status: u16, body: impl FnOnce() -> Option<String>) -> Poll {
|
||||
match status {
|
||||
200 => body()
|
||||
.as_deref()
|
||||
.and_then(count_working)
|
||||
.map_or(Poll::Failed, Poll::Working),
|
||||
401 | 403 | 429 => Poll::Refused,
|
||||
_ => Poll::Failed,
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Poller {
|
||||
agent: ureq::Agent,
|
||||
url: String,
|
||||
authorization: Option<String>,
|
||||
cookie: Option<String>,
|
||||
}
|
||||
|
||||
impl Poller {
|
||||
pub fn new(server: &Url, authorization: Option<String>) -> Option<Self> {
|
||||
Some(Poller {
|
||||
agent: crate::probe::agent(TIMEOUT),
|
||||
url: server.join(SESSIONS_PATH).ok()?.to_string(),
|
||||
authorization,
|
||||
cookie: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn poll(&mut self) -> Poll {
|
||||
let mut request = self.agent.get(&self.url).header("Accept", "application/json");
|
||||
if let Some(authorization) = &self.authorization {
|
||||
request = request.header("Authorization", authorization);
|
||||
}
|
||||
if let Some(cookie) = &self.cookie {
|
||||
request = request.header("Cookie", cookie);
|
||||
}
|
||||
let Ok(mut response) = request.call() else {
|
||||
return Poll::Failed;
|
||||
};
|
||||
let fresh = response
|
||||
.headers()
|
||||
.get_all("set-cookie")
|
||||
.iter()
|
||||
.filter_map(|value| value.to_str().ok())
|
||||
.find_map(session_cookie)
|
||||
.map(str::to_owned);
|
||||
if fresh.is_some() {
|
||||
self.cookie = fresh;
|
||||
}
|
||||
let status = response.status().as_u16();
|
||||
answer(status, || {
|
||||
let body = response.body_mut().with_config();
|
||||
body.limit(crate::probe::MAX_BODY).read_to_string().ok()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// The start of a real answer of `GET /api/sessions`, captured from a
|
||||
/// server: other fields around the two that matter, in Codeman's envelope.
|
||||
const REAL_ANSWER: &str = r#"{"success":true,"data":[{"id":"0f8d0215-661e-4a1c-bfad-d7f6fd2ed4b5",
|
||||
"pid":61017,"status":"busy","workingDir":"/Users/lee/codeman-cases/testcase",
|
||||
"paneCwd":"/Users/lee/codeman-cases/testcase","currentTaskId":null,"mode":"opencode"}]}"#;
|
||||
|
||||
#[test]
|
||||
fn reads_the_answer_a_real_server_gives() {
|
||||
assert_eq!(count_working(REAL_ANSWER), Some(1));
|
||||
assert_eq!(count_working(r#"{"success":true,"data":[]}"#), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_agents_at_work_and_nothing_else() {
|
||||
let body = r#"{"success":true,"data":[
|
||||
{"id":"a","status":"busy","mode":"claude"},
|
||||
{"id":"b","status":"busy","mode":"codex"},
|
||||
{"id":"c","status":"idle","mode":"claude"},
|
||||
{"id":"d","status":"busy","mode":"shell"},
|
||||
{"id":"e","status":"stopped","mode":"claude"},
|
||||
{"id":"f","status":"error","mode":"opencode"}
|
||||
]}"#;
|
||||
assert_eq!(count_working(body), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_bare_list_of_an_older_server() {
|
||||
assert_eq!(count_working(r#"[{"status":"busy","mode":"claude"}]"#), Some(1));
|
||||
assert_eq!(count_working("[]"), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_without_a_mode_counts_and_one_without_a_status_does_not() {
|
||||
assert_eq!(
|
||||
count_working(r#"{"data":[{"status":"busy"},{"mode":"claude"}]}"#),
|
||||
Some(1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_that_is_not_the_list_is_no_answer() {
|
||||
assert_eq!(count_working("<html>"), None);
|
||||
assert_eq!(count_working(r#"{"success":false,"error":"nope"}"#), None);
|
||||
assert_eq!(answer(200, || Some("<html>".into())), Poll::Failed);
|
||||
assert_eq!(answer(200, || None), Poll::Failed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_login_refusal_ends_the_polling() {
|
||||
for status in [401, 403, 429] {
|
||||
assert_eq!(answer(status, || None), Poll::Refused, "{status}");
|
||||
}
|
||||
for status in [301, 404, 500, 502, 503] {
|
||||
assert_eq!(answer(status, || None), Poll::Failed, "{status}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_codemans_cookie_in_a_set_cookie_header() {
|
||||
assert_eq!(
|
||||
session_cookie("codeman_session=abc123; Max-Age=86400; Path=/; HttpOnly; SameSite=Lax"),
|
||||
Some("codeman_session=abc123")
|
||||
);
|
||||
assert_eq!(session_cookie("codeman_session=abc123"), Some("codeman_session=abc123"));
|
||||
assert_eq!(session_cookie("other=1; Path=/"), None);
|
||||
assert_eq!(session_cookie("codeman_session=; Max-Age=0"), None);
|
||||
assert_eq!(session_cookie(""), None);
|
||||
}
|
||||
|
||||
/// A server that answers each connection with the next canned response
|
||||
/// and records the headers it was sent.
|
||||
fn serve(responses: Vec<String>) -> (u16, Arc<Mutex<Vec<Vec<String>>>>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let seen = Arc::new(Mutex::new(Vec::new()));
|
||||
let log = seen.clone();
|
||||
std::thread::spawn(move || {
|
||||
for response in responses {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
||||
let mut headers = Vec::new();
|
||||
let mut line = String::new();
|
||||
while reader.read_line(&mut line).is_ok() && line.trim() != "" {
|
||||
headers.push(line.trim().to_ascii_lowercase());
|
||||
line.clear();
|
||||
}
|
||||
log.lock().unwrap().push(headers);
|
||||
stream.write_all(response.as_bytes()).unwrap();
|
||||
}
|
||||
});
|
||||
(port, seen)
|
||||
}
|
||||
|
||||
const EMPTY: &str = r#"{"success":true,"data":[]}"#;
|
||||
|
||||
fn ok(extra_headers: &str, body: &str) -> String {
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: {}\r\n{extra_headers}\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_one_login_session_across_polls() {
|
||||
let body = r#"{"success":true,"data":[{"status":"busy","mode":"claude"}]}"#;
|
||||
let (port, seen) = serve(vec![
|
||||
ok("Set-Cookie: codeman_session=first; Max-Age=86400; Path=/\r\n", body),
|
||||
ok("Set-Cookie: codeman_session=first; Max-Age=86400; Path=/\r\n", body),
|
||||
ok("Set-Cookie: codeman_session=second; Max-Age=86400; Path=/\r\n", EMPTY),
|
||||
ok("", EMPTY),
|
||||
]);
|
||||
let server = Url::parse(&format!("http://127.0.0.1:{port}/")).unwrap();
|
||||
let mut poller = Poller::new(&server, Some("Basic abc".into())).unwrap();
|
||||
assert_eq!(poller.poll(), Poll::Working(1));
|
||||
assert_eq!(poller.poll(), Poll::Working(1));
|
||||
assert_eq!(poller.poll(), Poll::Working(0));
|
||||
assert_eq!(poller.poll(), Poll::Working(0));
|
||||
|
||||
let seen = seen.lock().unwrap();
|
||||
let cookie = |n: usize| seen[n].iter().find(|h| h.starts_with("cookie:")).cloned();
|
||||
assert_eq!(cookie(0), None);
|
||||
assert_eq!(cookie(1).as_deref(), Some("cookie: codeman_session=first"));
|
||||
assert_eq!(cookie(2).as_deref(), Some("cookie: codeman_session=first"));
|
||||
// A server restart hands out a new one; a response without one keeps it.
|
||||
assert_eq!(cookie(3).as_deref(), Some("cookie: codeman_session=second"));
|
||||
assert!(seen.iter().all(|h| h.contains(&"authorization: basic abc".to_string())));
|
||||
assert!(seen[0][0].starts_with("get /api/sessions "), "{:?}", seen[0][0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asks_under_the_servers_base_path() {
|
||||
let (port, seen) = serve(vec![ok("", EMPTY)]);
|
||||
let server = Url::parse(&format!("http://127.0.0.1:{port}/codeman/")).unwrap();
|
||||
assert_eq!(Poller::new(&server, None).unwrap().poll(), Poll::Working(0));
|
||||
let seen = seen.lock().unwrap();
|
||||
assert!(seen[0][0].starts_with("get /codeman/api/sessions "), "{:?}", seen[0][0]);
|
||||
assert!(!seen[0].iter().any(|h| h.starts_with("authorization:")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_server_that_answers_nothing_is_only_a_failed_poll() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
drop(listener);
|
||||
let server = Url::parse(&format!("http://127.0.0.1:{port}/")).unwrap();
|
||||
assert_eq!(Poller::new(&server, None).unwrap().poll(), Poll::Failed);
|
||||
}
|
||||
}
|
||||
@@ -184,17 +184,21 @@ pub const HOST_SHIM: &str = r#"(function () {
|
||||
}
|
||||
})();"#;
|
||||
|
||||
/// A toast inside Codeman when a download finished (Codeman's own
|
||||
/// `showToast`; nothing happens on a page without it).
|
||||
/// A toast inside Codeman (its own `showToast`; nothing happens on a page
|
||||
/// without it). `kind` is one of Codeman's fixed toast kinds.
|
||||
pub fn toast_script(text: &str, kind: &str) -> String {
|
||||
let text = serde_json::to_string(text).unwrap_or_else(|_| "\"\"".into());
|
||||
format!("try {{ window.app && window.app.showToast && window.app.showToast({text}, \"{kind}\"); }} catch (e) {{}}")
|
||||
}
|
||||
|
||||
/// A toast inside Codeman when a download finished.
|
||||
pub fn download_toast_script(file_name: &str, ok: bool) -> String {
|
||||
let text = if ok {
|
||||
format!("Downloaded {file_name} to Downloads")
|
||||
} else {
|
||||
format!("Download of {file_name} failed")
|
||||
};
|
||||
let text = serde_json::to_string(&text).unwrap_or_else(|_| "\"Download finished\"".into());
|
||||
let kind = if ok { "\"success\"" } else { "\"error\"" };
|
||||
format!("try {{ window.app && window.app.showToast && window.app.showToast({text}, {kind}); }} catch (e) {{}}")
|
||||
toast_script(&text, if ok { "success" } else { "error" })
|
||||
}
|
||||
|
||||
/// Runs in the window that asked for a window the native side did not open
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! (`~/Library/Application Support/Codeman/desktop.json` on macOS). Passwords
|
||||
//! never go here; they live in the Keychain (see `credentials`).
|
||||
|
||||
use crate::logo::BlinkStyle;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::io;
|
||||
@@ -43,6 +44,11 @@ pub struct Config {
|
||||
pub auto_connect: bool,
|
||||
/// Always open in full screen (otherwise the last state is restored).
|
||||
pub start_fullscreen: bool,
|
||||
/// What the lit Apple logo does while agents work (logo.rs). The menu only
|
||||
/// shows on a Mac that has one. A value this version does not know reads as
|
||||
/// off: a bad style must not make the whole file unreadable.
|
||||
#[serde(deserialize_with = "lenient_blink")]
|
||||
pub logo_blink: BlinkStyle,
|
||||
/// Anything that is not a whole frame reads as None: a bad frame must not
|
||||
/// make the whole file unreadable, which would cost the server list.
|
||||
#[serde(deserialize_with = "lenient_window")]
|
||||
@@ -54,12 +60,18 @@ fn lenient_window<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Windo
|
||||
Ok(serde_json::from_value(value).ok())
|
||||
}
|
||||
|
||||
fn lenient_blink<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BlinkStyle, D::Error> {
|
||||
let value = serde_json::Value::deserialize(d)?;
|
||||
Ok(serde_json::from_value(value).unwrap_or_default())
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Config {
|
||||
servers: Vec::new(),
|
||||
auto_connect: true,
|
||||
start_fullscreen: false,
|
||||
logo_blink: BlinkStyle::Off,
|
||||
window: None,
|
||||
}
|
||||
}
|
||||
@@ -399,6 +411,27 @@ mod tests {
|
||||
assert!(can_save);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_logo_blink_style_round_trips_and_a_bad_one_reads_as_off() {
|
||||
let mut c = Config::default();
|
||||
assert_eq!(c.logo_blink, BlinkStyle::Off);
|
||||
c.logo_blink = BlinkStyle::Heartbeat;
|
||||
let text = serde_json::to_string(&c).unwrap();
|
||||
assert!(text.contains(r#""logoBlink":"heartbeat""#), "{text}");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Config>(&text).unwrap().logo_blink,
|
||||
BlinkStyle::Heartbeat
|
||||
);
|
||||
for bad in [
|
||||
r#"{"logoBlink":"strobe"}"#,
|
||||
r#"{"logoBlink":3}"#,
|
||||
r#"{"logoBlink":null}"#,
|
||||
] {
|
||||
let c: Config = serde_json::from_str(bad).unwrap();
|
||||
assert_eq!(c.logo_blink, BlinkStyle::Off, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_and_atomic_save() {
|
||||
let dir = tmp_dir("roundtrip");
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -6,8 +6,9 @@
|
||||
//! installs Codeman on this machine (`setup`, `local_server`) and installs it
|
||||
//! on another one over SSH, real full screen, native menus, pop-outs as app
|
||||
//! windows (Codeman's `window.CodemanHost` bridge), downloads to ~/Downloads,
|
||||
//! passwords in the Keychain, and on macOS the JavaScript dialogs and HTTP
|
||||
//! Basic challenges wry leaves out (`macos`).
|
||||
//! passwords in the Keychain, on macOS the JavaScript dialogs and HTTP Basic
|
||||
//! challenges wry leaves out (`macos`), and on a MacBook Pro with a lit Apple
|
||||
//! logo a blink while agents work (`logo`).
|
||||
//!
|
||||
//! Every URL and message decision is in `policy` (pure, unit-tested); this file
|
||||
//! only wires those decisions to windows. The main window moves through
|
||||
@@ -19,10 +20,12 @@
|
||||
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
mod agents;
|
||||
mod assets;
|
||||
mod config;
|
||||
mod credentials;
|
||||
mod local_server;
|
||||
mod logo;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
mod policy;
|
||||
@@ -51,6 +54,7 @@ use wry::{NewWindowResponse, PageLoadEvent, PermissionResponse, WebView, WebView
|
||||
|
||||
use config::{Config, Rect, WindowFrame};
|
||||
use credentials::Keychain;
|
||||
use logo::BlinkStyle;
|
||||
use policy::{ConnectCmd, HostCmd, Ipc, Navigation, NewWindow, OpenBudget, Phase, Recovery, Via};
|
||||
use probe::ProbeOutcome;
|
||||
|
||||
@@ -96,6 +100,7 @@ const AUTH_RATE_LIMITED: &str = "Too many failed logins from this address. The s
|
||||
enter it again (a single-user Codeman accepts the right password at once), or wait up to 15 minutes.";
|
||||
const KEYCHAIN_UNREADABLE: &str = "The saved password could not be read from the Keychain. Enter it again.";
|
||||
const PAGE_KEEPS_STOPPING: &str = "Codeman's page stopped twice in a row, so it was closed. Connect again.";
|
||||
const LOGO_SWITCHED_OFF: &str = "The Apple logo is switched off on this Mac, so it cannot blink.";
|
||||
const START_REFUSED: &str = "Codeman can only be started here for an http://127.0.0.1 or http://localhost address.";
|
||||
|
||||
mod menu_id {
|
||||
@@ -234,6 +239,9 @@ struct AppMenu {
|
||||
window_menu: Submenu,
|
||||
help_menu: Submenu,
|
||||
start_fullscreen: CheckMenuItem,
|
||||
/// One item per style. Empty on a Mac without a lit logo, which has no
|
||||
/// such menu.
|
||||
logo_styles: Vec<(BlinkStyle, CheckMenuItem)>,
|
||||
}
|
||||
|
||||
enum Load<'a> {
|
||||
@@ -289,9 +297,16 @@ struct App {
|
||||
/// While the main window may still have to be put into the full screen it
|
||||
/// asked for at launch: when to look next, and how many retries were made.
|
||||
fullscreen_retry: Option<(Instant, u8)>,
|
||||
/// The child that watches the connected server and blinks the logo.
|
||||
logo_watch: logo::Watcher,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// The blinker is this binary without a window (logo.rs).
|
||||
if std::env::args().nth(1).as_deref() == Some(logo::BLINK_ARG) {
|
||||
logo::blink_main();
|
||||
}
|
||||
|
||||
let event_loop = EventLoopBuilder::<UserEvent>::with_user_event().build();
|
||||
let proxy = event_loop.create_proxy();
|
||||
|
||||
@@ -320,6 +335,7 @@ fn main() {
|
||||
};
|
||||
let config_path = config_path.filter(|_| can_save);
|
||||
let notice = (!can_save).then(|| SETTINGS_UNREADABLE.to_string());
|
||||
logo::recover_at_launch();
|
||||
let menu = build_menu(&config).unwrap_or_else(|e| fatal(&format!("Could not build the menu: {e}")));
|
||||
let phase = Rc::new(RefCell::new(Phase::Connect));
|
||||
// Started once: the probe workers and the event loop share this queue,
|
||||
@@ -371,6 +387,7 @@ fn main() {
|
||||
menu,
|
||||
keychain,
|
||||
fullscreen_retry: wants_fullscreen.then(|| (Instant::now() + FULLSCREEN_FIRST_CHECK, 0)),
|
||||
logo_watch: logo::Watcher::default(),
|
||||
};
|
||||
|
||||
event_loop.run(move |event, target, control_flow| app.handle(event, target, control_flow));
|
||||
@@ -459,6 +476,22 @@ fn build_menu(config: &Config) -> muda::Result<AppMenu> {
|
||||
),
|
||||
],
|
||||
)?;
|
||||
// Only a Mac with a lit Apple logo has this menu at all.
|
||||
let mut logo_styles = Vec::new();
|
||||
if logo::available() {
|
||||
let submenu = Submenu::new("Blink Apple Logo While Agents Work", true);
|
||||
for style in BlinkStyle::ALL {
|
||||
let chosen = style == config.logo_blink;
|
||||
let item = CheckMenuItem::with_id(style.menu_id(), style.label(), true, chosen, None);
|
||||
submenu.append(&item)?;
|
||||
if style == BlinkStyle::Off {
|
||||
submenu.append(&PredefinedMenuItem::separator())?;
|
||||
}
|
||||
logo_styles.push((style, item));
|
||||
}
|
||||
// Right under "Always Open in Full Screen", before the separator.
|
||||
view.insert(&submenu, 4)?;
|
||||
}
|
||||
let window_menu = Submenu::with_items(
|
||||
"Window",
|
||||
true,
|
||||
@@ -485,6 +518,7 @@ fn build_menu(config: &Config) -> muda::Result<AppMenu> {
|
||||
window_menu,
|
||||
help_menu,
|
||||
start_fullscreen,
|
||||
logo_styles,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -925,6 +959,7 @@ impl App {
|
||||
if let Some(next) = next {
|
||||
*self.phase.borrow_mut() = next;
|
||||
}
|
||||
self.sync_logo_watch();
|
||||
}
|
||||
if let Some(w) = self.windows.get_mut(&window) {
|
||||
w.committed = Url::parse(&url).ok();
|
||||
@@ -1102,7 +1137,40 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// The logo is watched while a style is chosen and a server is open.
|
||||
fn sync_logo_watch(&mut self) {
|
||||
let style = self.config.logo_blink;
|
||||
let phase = self.phase.borrow();
|
||||
let server = phase.loaded().filter(|_| style != BlinkStyle::Off && logo::available());
|
||||
self.logo_watch
|
||||
.sync(server.map(|url| (url.as_str(), self.auth.as_deref(), style)));
|
||||
}
|
||||
|
||||
fn choose_logo_blink(&mut self, style: BlinkStyle) {
|
||||
// A click flips the item it landed on, the chosen one included, so all
|
||||
// of them are set.
|
||||
for (item_style, item) in &self.menu.logo_styles {
|
||||
item.set_checked(*item_style == style);
|
||||
}
|
||||
let was_off = self.config.logo_blink == BlinkStyle::Off;
|
||||
self.config.logo_blink = style;
|
||||
self.config_dirty = true;
|
||||
self.sync_logo_watch();
|
||||
// Only from off: with a style running, a dark logo may be our own.
|
||||
if was_off && style != BlinkStyle::Off && logo::switched_off() {
|
||||
if let Some(main) = self.windows.get(&self.main_id) {
|
||||
let _ = main
|
||||
.webview
|
||||
.evaluate_script(&assets::toast_script(LOGO_SWITCHED_OFF, "warning"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_menu(&mut self, id: &str) {
|
||||
if let Some(style) = BlinkStyle::from_menu_id(id) {
|
||||
self.choose_logo_blink(style);
|
||||
return;
|
||||
}
|
||||
match id {
|
||||
menu_id::SWITCH => self.show_connect_page(None, true),
|
||||
menu_id::RELOAD => self.reload_focused(),
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::time::Duration;
|
||||
use url::Url;
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const MAX_BODY: u64 = 8 * 1024 * 1024;
|
||||
pub const MAX_BODY: u64 = 8 * 1024 * 1024;
|
||||
|
||||
/// The path the probe asks for, relative to the server's base URL.
|
||||
const STATUS_PATH: &str = "api/status";
|
||||
@@ -231,16 +231,13 @@ pub fn probe(server: &Url, authorization: Option<&str>) -> ProbeOutcome {
|
||||
probe_within(server, authorization, TIMEOUT)
|
||||
}
|
||||
|
||||
/// `probe` with the time the whole exchange may take.
|
||||
fn probe_within(server: &Url, authorization: Option<&str>, timeout: Duration) -> ProbeOutcome {
|
||||
let status_url = match server.join(STATUS_PATH) {
|
||||
Ok(u) => u,
|
||||
Err(e) => return ProbeOutcome::Failed { detail: e.to_string() },
|
||||
};
|
||||
/// The app's one way of asking a server something: the OS's certificate trust,
|
||||
/// a bound on the whole exchange, and status codes as answers.
|
||||
pub fn agent(timeout: Duration) -> ureq::Agent {
|
||||
let tls = ureq::tls::TlsConfig::builder()
|
||||
.root_certs(ureq::tls::RootCerts::PlatformVerifier)
|
||||
.build();
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder()
|
||||
ureq::Agent::config_builder()
|
||||
.timeout_global(Some(timeout))
|
||||
.http_status_as_error(false)
|
||||
// Never follow: a 3xx comes back as an answer and is explained.
|
||||
@@ -248,8 +245,18 @@ fn probe_within(server: &Url, authorization: Option<&str>, timeout: Duration) ->
|
||||
.tls_config(tls)
|
||||
.user_agent(concat!("CodemanDesktop/", env!("CARGO_PKG_VERSION")))
|
||||
.build()
|
||||
.into();
|
||||
let mut req = agent.get(status_url.as_str()).header("Accept", "application/json");
|
||||
.into()
|
||||
}
|
||||
|
||||
/// `probe` with the time the whole exchange may take.
|
||||
fn probe_within(server: &Url, authorization: Option<&str>, timeout: Duration) -> ProbeOutcome {
|
||||
let status_url = match server.join(STATUS_PATH) {
|
||||
Ok(u) => u,
|
||||
Err(e) => return ProbeOutcome::Failed { detail: e.to_string() },
|
||||
};
|
||||
let mut req = agent(timeout)
|
||||
.get(status_url.as_str())
|
||||
.header("Accept", "application/json");
|
||||
if let Some(auth) = authorization {
|
||||
req = req.header("Authorization", auth);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user