Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Perch: the window shows (it waited for a frame a hidden window never gets) (#720)

Oleksandr Ivanchenko395de13cbc9b
diff --git a/.github/workflows/mac.yml b/.github/workflows/mac.yml
index ef8cc2b7..c9c24b93 100644
--- a/.github/workflows/mac.yml
+++ b/.github/workflows/mac.yml
@@ -432,6 +432,71 @@ jobs:
path: ${{ runner.temp }}/nudge
if-no-files-found: ignore
retention-days: 14
+ # The perch (apps/mac/src/perch_window.rs): the built app runs as --demo-perch, with the perch
+ # on (Always) and a made-up glance (one bot working, one need). Once the page rests it opens
+ # the perch the way ⌥⌘K does (perch_window::toggle) and prints the window's state every half
+ # second. The job fails unless, after the shortcut, the window is visible, has a size and sits
+ # inside the screen at its top, checked here from the numbers the window server gives. The
+ # runner has no notch, so this is the floating tab under the menu bar.
+ - name: Perch on screen after the shortcut (--demo-perch)
+ timeout-minutes: 5
+ run: |
+ set -euo pipefail
+ shots="$RUNNER_TEMP/perch"
+ mkdir -p "$shots"
+ out="$shots/demo-perch.txt"
+ app=apps/mac/target/universal-apple-darwin/release/bundle/macos/kwant.app/Contents/MacOS/kwant
+ waitfor() {
+ for _ in $(seq 1 120); do grep -q "$1" "$out" && return 0; sleep 0.5; done
+ echo "never saw: $1"; cat "$out"; return 1
+ }
+ shot() { screencapture -x "$shots/$1.png" || true; }
+ osascript -e 'tell application "System Events" to tell appearance preferences to set dark mode to false' || true
+ "$app" --demo-perch > "$out" 2>&1 &
+ pid=$!
+ waitfor "demo-perch: before toggle"
+ shot 1-before-shortcut
+ waitfor "demo-perch: toggled"
+ sleep 2; shot 2-after-shortcut
+ waitfor "demo-perch: result"
+ shot 3-result
+ waitfor "demo-perch: done" || true
+ kill $pid 2>/dev/null || true
+ wait $pid 2>/dev/null || true
+ ls -l "$shots"
+ grep 'demo-perch:' "$out"
+ result=$(grep -m1 'demo-perch: result' "$out")
+ python3 - "$result" <<'PY'
+ import re, sys
+ line = sys.argv[1]
+ m = re.search(r"visible=(\w+) frame=(-?\d+),(-?\d+),(\d+)x(\d+) screen=(-?\d+),(-?\d+),(\d+)x(\d+) scale=([\d.]+)", line)
+ if not m:
+ print("::error::no perch frame in: " + line)
+ sys.exit(1)
+ visible = m.group(1) == "true"
+ x, y, w, h, sx, sy, sw, sh = map(int, m.groups()[1:9])
+ scale = float(m.group(10))
+ problems = []
+ if not visible:
+ problems.append("not visible")
+ if w <= 0 or h <= 0:
+ problems.append(f"size {w}x{h}")
+ if not (sx <= x and x + w <= sx + sw and sy <= y and y + h <= sy + sh):
+ problems.append(f"frame {x},{y},{w}x{h} not inside the screen {sx},{sy},{sw}x{sh}")
+ if y - sy > 80 * scale:
+ problems.append(f"top edge {y - sy}px below the screen's top")
+ if problems:
+ print("::error::the perch after the shortcut: " + "; ".join(problems) + " (" + line + ")")
+ sys.exit(1)
+ print("perch OK: " + line)
+ PY
+ - uses: actions/upload-artifact@v4
+ if: always()
+ with:
+ name: perch
+ path: ${{ runner.temp }}/perch
+ if-no-files-found: ignore
+ retention-days: 14
- uses: actions/upload-artifact@v4
with:
name: ${{ steps.bundle.outputs.name }}
diff --git a/apps/mac/loading/perch.js b/apps/mac/loading/perch.js
index 3bf8e9ef..69b0f0fa 100644
--- a/apps/mac/loading/perch.js
+++ b/apps/mac/loading/perch.js
@@ -428,7 +428,14 @@
stage.replaceChildren(root);
lastRendered = st;
if (active) { var again = document.getElementById('ask'); if (again) { again.focus(); try { again.setSelectionRange(caret[0], caret[1]); } catch (e) { /* not a text field any more */ } } }
- requestAnimationFrame(function () { measure(st, root); });
+ // The window shows only once Rust has this size (perch_window.rs place), and WKWebView runs no
+ // animation frames in a window that isn't on screen, so a frame alone never came while the
+ // window was still hidden. Measure on the first frame or the first timer, whichever comes
+ // first (offsetWidth lays out either way).
+ var measured = false;
+ function measureOnce() { if (measured) return; measured = true; measure(st, root); }
+ requestAnimationFrame(measureOnce);
+ setTimeout(measureOnce, 0);
}
var compact = false;
function measure(st, root) {
diff --git a/apps/mac/src/main.rs b/apps/mac/src/main.rs
index 85061c5e..e94a5df5 100644
--- a/apps/mac/src/main.rs
+++ b/apps/mac/src/main.rs
@@ -303,6 +303,9 @@ enum Goto {
/// Set (to its start) when the app runs as `--demo-nudge`.
static DEMO: OnceLock<Instant> = OnceLock::new();
+/// Set (to its start) when the app runs as `--demo-perch` (`perch_window::demo`).
+static DEMO_PERCH: OnceLock<Instant> = OnceLock::new();
+
/// The demo's last step plays as under Reduce Motion, which CI can't switch on.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn demo_reduce_motion() -> bool {
@@ -319,7 +322,14 @@ fn main() {
}
let demo = std::env::args().any(|a| a == "--demo-nudge");
- let (config, places) = if demo { demo_start() } else { normal_start() };
+ let demo_perch = !demo && std::env::args().any(|a| a == "--demo-perch");
+ let (config, places) = if demo {
+ demo_start()
+ } else if demo_perch {
+ demo_perch_start()
+ } else {
+ normal_start()
+ };
let data_dir = config.data_dir.clone();
let show = nudge::Prefs::load(&data_dir).show_nudges;
@@ -362,7 +372,12 @@ fn main() {
}
build_tray(handle)?;
perch_window::apply_shortcut(handle);
- if demo {
+ if demo_perch {
+ // a place window, hidden as in the nudge demo; the perch is what CI looks at
+ make_window(handle, &Place::ThisMac, Goto::Stay, false);
+ let h = handle.clone();
+ std::thread::spawn(move || perch_window::demo::run(&h));
+ } else if demo {
// hidden, so the pill shows (it never covers a focused kwant window); a click on
// the pill shows it
make_window(handle, &Place::ThisMac, Goto::Stay, false);
@@ -412,7 +427,7 @@ fn main() {
RunEvent::ExitRequested { .. } => save_open(handle),
RunEvent::Exit => {
stop_server(handle);
- if DEMO.get().is_some() {
+ if DEMO.get().is_some() || DEMO_PERCH.get().is_some() {
let _ = std::fs::remove_dir_all(&handle.state::<Nudges>().data_dir);
}
}
@@ -457,6 +472,29 @@ fn demo_start() -> (kwnt::Config, Places) {
(config, Places::default())
}
+/// `--demo-perch`: kwant on a free port with a throwaway data dir, the perch on (Always) and a
+/// made-up glance for This Mac (`perch_window::demo`: one bot working, one need). It opens the
+/// perch the way ⌥⌘K does, prints where its window is, and quits on its own.
+fn demo_perch_start() -> (kwnt::Config, Places) {
+ let _ = DEMO_PERCH.set(Instant::now());
+ tracing_subscriber::fmt().with_env_filter("info").init();
+ let data_dir = std::env::temp_dir().join(format!("kwant-demo-perch-{}", std::process::id()));
+ let port = startup::free_port().unwrap_or_else(|e| fatal(&format!("kwant --demo-perch: no free port: {e}")));
+ println!("demo-perch: port {port}");
+ let prefs = perch::Prefs { mode: switcher::PerchMode::Always, shortcut: switcher::PerchShortcut::K };
+ if let Err(e) = prefs.save(&data_dir) {
+ fatal(&format!("kwant --demo-perch: couldn't save the perch settings: {e}"));
+ }
+ let config = kwnt::Config {
+ data_dir,
+ host: "127.0.0.1".to_string(),
+ port,
+ laya_managed: false,
+ ..Default::default()
+ };
+ (config, Places::default())
+}
+
/// Finder (and a Linux app menu) starts apps with a bare PATH, so the claude, codex and grok CLIs
/// would be missing. Runs before any thread exists, so setting the variable is safe.
#[cfg(not(windows))]
@@ -512,7 +550,7 @@ fn start_server(config: kwnt::Config) -> Server {
/// The kwant on this Mac: started by this app, or the one already running here.
fn start_local(config: &kwnt::Config) -> Local {
- if DEMO.get().is_some() {
+ if DEMO.get().is_some() || DEMO_PERCH.get().is_some() {
return Local { port: Some(config.port), server: Some(start_server(config.clone())), failed: false };
}
match startup::choose_port(config.port) {
@@ -573,7 +611,7 @@ fn start_updates<R: Runtime>(app: &AppHandle<R>) {
/// True for the first caller only, and never on Windows or in the demo.
fn claim_updates(shared: &Shared) -> bool {
- !cfg!(windows) && DEMO.get().is_none() && !shared.updates.swap(true, Ordering::SeqCst)
+ !cfg!(windows) && DEMO.get().is_none() && DEMO_PERCH.get().is_none() && !shared.updates.swap(true, Ordering::SeqCst)
}
/// Stops the kwant this app started before the app exits. An attached kwant keeps running.
@@ -707,7 +745,7 @@ fn refresh_titles<R: Runtime>(app: &AppHandle<R>) {
/// Remembers which windows show, for the next launch.
fn save_open<R: Runtime>(app: &AppHandle<R>) {
- if DEMO.get().is_some() {
+ if DEMO.get().is_some() || DEMO_PERCH.get().is_some() {
return;
}
let shown: Vec<Place> = current(app)
@@ -1407,6 +1445,7 @@ fn build_tray(handle: &AppHandle) -> tauri::Result<()> {
if perch_window::polling(&app) {
let eager = perch_window::eager(&app);
let snap = perch_window::snapshot(&all, &mut glances, &last, eager, |place, etag| match place {
+ Place::ThisMac if DEMO_PERCH.get().is_some() => perch_window::demo::glance(),
Place::ThisMac => match port {
Some(port) if !failed => perch_window::local_glance(&local_client, port, etag),
_ => remote::Glance::Failed,
@@ -1456,7 +1495,8 @@ fn build_tray(handle: &AppHandle) -> tauri::Result<()> {
start_updates(&app);
}
// the demo moves on a timeline CI screenshots, so it looks every second
- let _ = wake_rx.recv_timeout(Duration::from_secs(if demo.is_some() { 1 } else { 5 }));
+ let quick = demo.is_some() || DEMO_PERCH.get().is_some();
+ let _ = wake_rx.recv_timeout(Duration::from_secs(if quick { 1 } else { 5 }));
while wake_rx.try_recv().is_ok() {}
}
});
diff --git a/apps/mac/src/perch_window.rs b/apps/mac/src/perch_window.rs
index ef78bd0b..02058528 100644
--- a/apps/mac/src/perch_window.rs
+++ b/apps/mac/src/perch_window.rs
@@ -361,6 +361,11 @@ fn window<R: Runtime>(app: &AppHandle<R>) -> Option<WebviewWindow<R>> {
.focused(false)
.accept_first_mouse(true)
.visible(false)
+ // It is made hidden and stays hidden until the page reports its size (`place`), and in
+ // Busy mode it is hidden most of the time. WebKit throttles a hidden page's timers and
+ // may suspend it after a few minutes (macOS 14+), and then the page never measures, so
+ // the window never shows. The page is small and mostly idle.
+ .background_throttling(tauri::utils::config::BackgroundThrottlingPolicy::Disabled)
.on_navigation(move |url| {
if url.scheme() == "kwant-island" {
on_perch_url(&nav_app, url);
@@ -634,23 +639,31 @@ fn place<R: Runtime>(app: &AppHandle<R>, state: PageState, content: (f64, f64))
let Some(w) = app.get_webview_window(perch::WINDOW) else {
return;
};
- let wants = {
+ let (wants, by_key) = {
let shared = app.state::<Shared>();
let st = shared.perch.lock().unwrap();
- perch::wants_window(&st.prefs, st.available, &st.snap, st.open_by_key)
+ (perch::wants_window(&st.prefs, st.available, &st.snap, st.open_by_key), st.open_by_key)
};
if state == PageState::Hidden || !wants {
let _ = w.hide();
return;
}
let Some(screen) = screen(app, &w) else {
+ tracing::warn!("the perch found no screen to hang on");
return;
};
let (x, y, fw, fh) = perch::frame(screen.shape, screen.w, screen.notch_left, screen.top, state, content);
let _ = w.set_size(LogicalSize::new(fw, fh));
let _ = w.set_position(LogicalPosition::new(screen.x + x, screen.y + y));
+ let was_visible = w.is_visible().unwrap_or(true);
// shown, not focused: the person keeps typing where they were
let _ = w.show();
+ // ...except when the shortcut opened it: `toggle` asked for the keyboard before the window
+ // was on screen, and AppKit gives a hidden window none
+ if by_key && !was_visible && state == PageState::Expanded {
+ let _ = w.set_focusable(true);
+ let _ = w.set_focus();
+ }
}
/// The screen the perch hangs on, in logical points from the primary screen's top-left.
@@ -777,6 +790,138 @@ mod mac {
}
}
+/// `--demo-perch` (CI, `.github/workflows/mac.yml`): the perch on (Always) with a made-up glance
+/// for This Mac, opened the way ⌥⌘K opens it (`toggle`), and the window's state printed as
+/// `demo-perch: …` lines. The job checks the `result` line's numbers itself: the window is
+/// visible, has a size, and sits inside the screen at its top.
+pub mod demo {
+ use super::toggle;
+ use crate::perch::{self, PageState};
+ use crate::{remote, Shared};
+ use std::time::{Duration, Instant};
+ use tauri::{AppHandle, Manager, Runtime};
+
+ /// One bot working, one approval waiting (the `/api/glance` shape `perch::parse_glance` reads).
+ const GLANCE: &str = r#"{
+ "counts": { "needs_you": 1, "working": 1, "finished_unseen": 0 },
+ "needs_you": [
+ { "kind": "approval", "id": "demo-a1", "space_id": "spc_default", "space_name": "My space",
+ "kwant_id": "bot-juno", "kwant_name": "Juno", "avatar": null, "title": "Use Bash (deploy the site)",
+ "since": "2026-11-15T22:00:00Z", "path": "/s/spc_default/b/bot-juno?card=demo-a1",
+ "approval": { "risk": "medium", "can_allow_inline": false, "why_open": null }, "question": null }
+ ],
+ "working": [
+ { "turn_id": "demo-t1", "kwant_name": "Mira", "avatar": null, "space_id": "spc_default",
+ "step": "Reading design.md", "step_started_at": "2026-11-15T22:01:00Z",
+ "started_at": "2026-11-15T22:00:00Z", "path": "/s/spc_default/b/bot-mira" }
+ ],
+ "finished": [],
+ "ask_targets": []
+ }"#;
+
+ /// This Mac's glance in the demo, every poll.
+ pub fn glance() -> remote::Glance {
+ remote::Glance::Fresh { etag: None, body: GLANCE.to_string() }
+ }
+
+ /// The perch window as the window server has it (physical pixels, from the primary screen's
+ /// top-left), and what the page last said.
+ pub struct Seen {
+ pub exists: bool,
+ pub ready: bool,
+ pub page: PageState,
+ pub visible: bool,
+ pub frame: (i64, i64, i64, i64),
+ pub screen: (i64, i64, i64, i64),
+ pub scale: f64,
+ }
+
+ impl Seen {
+ /// Visible, with a size, inside the screen, and its top edge at most 80 points below
+ /// the screen's top (under the menu bar, or around the notch).
+ pub fn ok(&self) -> bool {
+ let (x, y, w, h) = self.frame;
+ let (sx, sy, sw, sh) = self.screen;
+ let top_band = (80.0 * self.scale).round() as i64;
+ self.exists
+ && self.visible
+ && w > 0
+ && h > 0
+ && sw > 0
+ && sh > 0
+ && x >= sx
+ && x + w <= sx + sw
+ && y >= sy
+ && y + h <= sy + sh
+ && y - sy <= top_band
+ }
+
+ pub fn line(&self) -> String {
+ let (x, y, w, h) = self.frame;
+ let (sx, sy, sw, sh) = self.screen;
+ let page = format!("{:?}", self.page).to_lowercase();
+ format!(
+ "exists={} ready={} page={page} visible={} frame={x},{y},{w}x{h} screen={sx},{sy},{sw}x{sh} scale={}",
+ self.exists, self.ready, self.visible, self.scale
+ )
+ }
+ }
+
+ pub fn seen<R: Runtime>(app: &AppHandle<R>) -> Seen {
+ let (ready, page) = {
+ let shared = app.state::<Shared>();
+ let st = shared.perch.lock().unwrap();
+ (st.ready, st.page.0)
+ };
+ let Some(w) = app.get_webview_window(perch::WINDOW) else {
+ return Seen { exists: false, ready, page, visible: false, frame: (0, 0, 0, 0), screen: (0, 0, 0, 0), scale: 1.0 };
+ };
+ let visible = w.is_visible().unwrap_or(false);
+ let (x, y) = w.outer_position().map(|p| (p.x as i64, p.y as i64)).unwrap_or((0, 0));
+ let (fw, fh) = w.outer_size().map(|s| (s.width as i64, s.height as i64)).unwrap_or((0, 0));
+ let monitor = w.current_monitor().ok().flatten().or_else(|| w.primary_monitor().ok().flatten());
+ let (screen, scale) = monitor.map_or(((0, 0, 0, 0), 1.0), |m| {
+ let (p, s) = (m.position(), m.size());
+ ((p.x as i64, p.y as i64, s.width as i64, s.height as i64), m.scale_factor())
+ });
+ Seen { exists: true, ready, page, visible, frame: (x, y, fw, fh), screen, scale }
+ }
+
+ /// Waits for the page to come to rest after its first peek (at most 15 s: on main it never
+ /// reported a size), presses the shortcut once, reports for 5 s, then quits.
+ pub fn run<R: Runtime>(app: &AppHandle<R>) {
+ let start = Instant::now();
+ let say = |what: &str, s: &Seen| println!("demo-perch: {what}: ok={} {}", s.ok(), s.line());
+ let mut last = String::new();
+ while start.elapsed() < Duration::from_secs(15) {
+ std::thread::sleep(Duration::from_millis(500));
+ let s = seen(app);
+ if s.line() != last {
+ last = s.line();
+ say(&format!("before {:.1}s", start.elapsed().as_secs_f64()), &s);
+ }
+ if s.ready && s.page == PageState::Rest {
+ break;
+ }
+ }
+ say("before toggle", &seen(app));
+ println!("demo-perch: toggle (as the shortcut) at {:.1}s", start.elapsed().as_secs_f64());
+ toggle(app);
+ let by_key = app.state::<Shared>().perch.lock().unwrap().open_by_key;
+ println!("demo-perch: toggled open_by_key={by_key}");
+ for i in 1..=10 {
+ std::thread::sleep(Duration::from_millis(500));
+ say(&format!("after +{:.1}s", f64::from(i) * 0.5), &seen(app));
+ }
+ let s = seen(app);
+ println!("demo-perch: result ok={} {}", s.ok(), s.line());
+ // CI screenshots the screen meanwhile
+ std::thread::sleep(Duration::from_secs(8));
+ println!("demo-perch: done");
+ app.exit(0);
+ }
+}
+
/// The glance caches the menu's poll keeps, one per place key.
pub type Caches = HashMap<String, GlanceCache>;