Skip to content

Commit bf4de49

Browse files
authored
Merge pull request #522 from OpenCoven/fix/513-daemon-glyph-refresh
fix(tui): keep the Coven daemon indicator current
2 parents ab5bed1 + 99aefcf commit bf4de49

5 files changed

Lines changed: 285 additions & 9 deletions

File tree

‎scripts/tui-tests/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ screen, and runs `run.sh`. No secrets or network access required.
9797
| `cases/28_approval_queue.sh` | A second approval key | `fake_anthropic.py` asks for two Bash calls in one response, so the second request waits behind the first panel. The first panel is decided with `y` and a second `y` follows: in the same write, at once, and 150 ms later. In both renderers a `y` already waiting when the first panel closes lands in the composer as text and decides nothing. A `y` that reaches the open next panel is ignored by Next, which takes keys other than Escape only after 400 ms of quiet, and decides that panel in Classic, which takes keys at once. Each round checks whether the second call ran (its marker file); while it is undecided, its panel must still be open and the model must have been told nothing, and a deliberate `y` then runs it. Every round ends with the model told that both calls ran. In Next, a round whose two keys took 400 ms or more to send skips the decision check, since the next panel may have armed by then; needs `python3` |
9898
| `cases/29_tool_results_kept.sh` | Tool results after a tool turn | In Classic (`COVEN_CODE_UI` unset) and Next, `fake_anthropic.py` asks for a Bash call, the user approves it, and the model answers its result. Once the turn ends, single key presses (`x`, Backspace, as typing sends them) precede a follow-up prompt, whose request, read from the full `messages` the fake logs to a file of their own, must carry the call and, in the user message right after it, the tool result answering it; needs `python3` |
9999
| `cases/30_panic_restore.sh` | Panic restoration | The product has no known input that panics, so the tui crate's `panic_restore` example takes the terminal with the real `setup_terminal` and panics on request; `panic_restore_pty.py` runs it on a raw PTY, with `setup_terminal` for each renderer (Classic and Next; their event loops are not involved). Before the panic: raw termios (output processing off too), alternate screen, mouse capture, bracketed paste, hidden cursor and pushed keyboard flags. A main-thread panic restores every termios field and, before the panic message, turns output processing back on (the message's first line break arrives as CRLF), leaves the alternate screen, turns mouse capture and bracketed paste off, sends a keyboard pop and shows the cursor; the message is printed and the exit status is 101. A worker-thread panic restores nothing and the probe keeps drawing; its later main-thread panic still restores. After a suspend and resume through the real `suspend_terminal`, a panic still restores. With `COVEN_CODE_KEYBOARD_ENHANCEMENT=0` no flags are pushed. Lines containing "current behaviour" pin details that need a decision, not endorse them (Unix; Windows has its own restore branch, which pops before leaving the alternate screen, and is not exercised): the keyboard pop is sent after leaving the alternate screen the flags were pushed on (case 13 requires suspend to pop on the alternate screen), a pop is sent even when none was pushed, the startup title is not cleared, each `setup_terminal` call chains another hook (so after a resume the restore is written twice), and a worker-thread panic prints its message onto the live screen. Needs `python3` and the probe |
100+
| `cases/31_classic_daemon_glyph.sh` | Coven daemon glyph | In Classic (`COVEN_CODE_UI` unset), a fake daemon on `coven.sock` in a disposable `COVEN_HOME` answers every request. The footer shows `✦ coven` while it runs, turns to `○ coven` within 25 s of the fake stopping and its socket being removed, with no input, and back to `✦ coven` within 25 s of a fresh fake starting; needs `python3` |
100101
| `cases/32_one_runtime.sh` | One runtime per renderer (#408) | In Classic (`COVEN_CODE_UI` unset) and Next, `fake_anthropic.py` drives two real turns, an approved Bash call and then a text answer. Between them the window grows by 20 columns and 5 rows until the app draws a rule that wide, then goes back. There is one session file after the first turn, and after the second turn and the exit it is still that one file with that id; under the home and the project, the only session file (`sessions/*.json`) and session index (`sessions.db`) are that file and that index, which holds that one session. The fake saw three streamed requests, each carrying the one before it, its reply and the next user message, and the request of the second turn came on a TCP connection the first turn used (the fake numbers connections in a log of its own), so it came from the same HTTP connection pool. The saved session is the last request's conversation plus its answer, and every indexed message is that session's. A user message has no uuid, so the index keeps only the first one ever (current behaviour); the check uses the answers. The tool-result request inside the first turn is not checked on its own. Not shown: anything built but never used to send or save; clients that share one pool; and the other clients the process builds the same way in both renderers (the registry's Anthropic provider, the per-goal-turn wrapper, Agent sub-agents, memory extraction, which ignores `ANTHROPIC_BASE_URL` and starts at 20 messages, and the replacements made by `/refresh` and an in-session login); one store object, since the index is opened at every save; the scheduler and memory authority; relaunching the other renderer on the same session, `/resume` and `/clear`; any transport but the direct API-key one; needs `python3` |
101102

102103
## Configuration
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
#!/usr/bin/env bash
2+
# shellcheck shell=bash
3+
#
4+
# Classic's footer follows the Coven daemon (#513). A fake daemon listens on
5+
# coven.sock in a disposable COVEN_HOME and answers every request. The footer
6+
# shows the online glyph while it runs; after the fake stops and its socket is
7+
# removed, as `coven daemon stop` leaves it, the footer turns to the offline
8+
# glyph without any input; after a fresh fake starts, it turns back. Each
9+
# change must land within 25 s: the reachability cache holds a reading for
10+
# 10 s, and the event loop re-reads it every second. Classic runs with
11+
# COVEN_CODE_UI unset and no provider; needs `python3`.
12+
13+
register_case tc_classic_daemon_glyph
14+
15+
_dg_start_daemon() { # socket path, ready file -> sets DG_PID; 0 once listening
16+
rm -f "$2"
17+
python3 - "$1" "$2" <<'PY' >/dev/null 2>&1 &
18+
import socket, sys
19+
path, ready = sys.argv[1], sys.argv[2]
20+
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
21+
server.bind(path)
22+
server.listen(16)
23+
open(ready, "w").close()
24+
while True:
25+
conn, _ = server.accept()
26+
conn.settimeout(2)
27+
request = b""
28+
try:
29+
while b"\r\n\r\n" not in request:
30+
chunk = conn.recv(4096)
31+
if not chunk:
32+
break
33+
request += chunk
34+
conn.sendall(b"HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n"
35+
b"Content-Length: 2\r\n\r\n[]")
36+
except OSError:
37+
pass
38+
conn.close()
39+
PY
40+
DG_PID=$!
41+
local waited=0
42+
while [ "$waited" -lt 50 ] && [ ! -e "$2" ]; do sleep 0.1; waited=$((waited + 1)); done
43+
[ -e "$2" ]
44+
}
45+
46+
_dg_stop_daemon() { # socket path
47+
if [ -n "${DG_PID:-}" ]; then
48+
kill "$DG_PID" 2>/dev/null
49+
wait "$DG_PID" 2>/dev/null
50+
DG_PID=""
51+
fi
52+
rm -f "$1"
53+
}
54+
55+
tc_classic_daemon_glyph() {
56+
describe "Classic daemon glyph follows the daemon (COVEN_CODE_UI unset)"
57+
if ! have_tmux; then _skip "tmux not installed"; return 0; fi
58+
if ! command -v python3 >/dev/null 2>&1; then _skip "python3 not installed"; return 0; fi
59+
60+
local scratch; scratch="$(mktemp -d)"
61+
mkdir -p "$scratch/home/.coven-code" "$scratch/home/.coven" "$scratch/project"
62+
printf '%s\n' '{"hasCompletedOnboarding": true}' >"$scratch/home/.coven-code/settings.json"
63+
local sock="$scratch/home/.coven/coven.sock" ready="$scratch/ready"
64+
DG_PID=""
65+
66+
if ! _dg_start_daemon "$sock" "$ready"; then
67+
_fail "the fake daemon listens" "no socket at $sock"
68+
_dg_stop_daemon "$sock"; rm -rf "$scratch"; return 0
69+
fi
70+
71+
local saved_prefix="$TUI_LAUNCH_PREFIX" saved_boot="$TUI_BOOT_STRING" var
72+
TUI_LAUNCH_PREFIX="cd $(printf '%q' "$scratch/project") && env"
73+
for var in ANTHROPIC_API_KEY ANTHROPIC_BASE_URL OPENAI_API_KEY COVEN_CODE_PROVIDER \
74+
COVEN_CODE_API_BASE COVEN_CODE_HOME COVEN_CODE_TEST_HOME COVEN_CODE_CLAUDE_BIN \
75+
COVEN_PARENT COVEN_DAEMON_SOCKET COVEN_CODE_UI; do
76+
TUI_LAUNCH_PREFIX+=" -u $var"
77+
done
78+
TUI_LAUNCH_PREFIX+=" $(printf '%q ' "HOME=$scratch/home" "COVEN_HOME=$scratch/home/.coven")"
79+
TUI_BOOT_STRING="Coven v"
80+
81+
if tui_start; then
82+
if wait_for "✦ coven" 10; then _pass "the footer shows the online glyph while the daemon runs"
83+
else _fail "the footer shows the online glyph while the daemon runs" "$(tui_capture)"; fi
84+
85+
_dg_stop_daemon "$sock"
86+
if wait_for "○ coven" 25; then _pass "the footer turns offline after the daemon stops"
87+
else _fail "the footer turns offline after the daemon stops" "$(tui_capture)"; fi
88+
assert_absent "$(tui_capture)" "✦ coven" "the online glyph is gone"
89+
90+
if _dg_start_daemon "$sock" "$ready"; then
91+
if wait_for "✦ coven" 25; then _pass "the footer turns online after the daemon starts again"
92+
else _fail "the footer turns online after the daemon starts again" "$(tui_capture)"; fi
93+
else
94+
_fail "the fake daemon listens again" "no socket at $sock"
95+
fi
96+
fi
97+
tui_stop
98+
_dg_stop_daemon "$sock"
99+
100+
TUI_LAUNCH_PREFIX="$saved_prefix"
101+
TUI_BOOT_STRING="$saved_boot"
102+
rm -rf "$scratch"
103+
}

‎src-rust/crates/cli/src/main.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3583,6 +3583,8 @@ async fn run_interactive(
35833583
}
35843584
app.frame_count = app.frame_count.wrapping_add(1);
35853585
app.tick_companion_pose();
3586+
// Classic's footer glyph and the palette's suggestions read this.
3587+
app.refresh_daemon_status(std::time::Instant::now());
35863588
// The session browser's list loads in the background (Next only;
35873589
// Classic's browser is unchanged).
35883590
if app.renderer == claurst_tui::application::UiRenderer::Next {

‎src-rust/crates/tui/src/app.rs‎

Lines changed: 149 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1100,8 +1100,12 @@ pub struct App {
11001100
pub exit_key_sequence_start: Option<char>,
11011101

11021102
// ---- Coven daemon integration ----------------------------------------
1103+
/// Last daemon reachability reading, drawn by Classic's footer and used
1104+
/// for the palette's suggestions. [`App::refresh_daemon_status`] keeps it
1105+
/// current.
11031106
pub daemon_online: bool,
1104-
pub daemon_last_checked: u64,
1107+
/// When `daemon_online` was last read.
1108+
pub daemon_last_checked: std::time::Instant,
11051109

11061110
// ---- Familiar switcher (F2) ------------------------------------------
11071111
pub familiar_switcher_open: bool,
@@ -1203,6 +1207,12 @@ Move immutable borrow out of scope first, then take mutable. Good good good afte
12031207
}
12041208
}
12051209

1210+
/// How often the event loop re-reads daemon reachability into
1211+
/// [`App::daemon_online`]. The read is a cached lookup that never waits on the
1212+
/// socket ([`crate::coven_status::daemon_looks_online`], whose own TTL paces
1213+
/// the probes); this interval only bounds how far the footer trails it.
1214+
const DAEMON_STATUS_REFRESH: std::time::Duration = std::time::Duration::from_secs(1);
1215+
12061216
/// Accent color for build mode (default pink).
12071217
pub const ACCENT_BUILD: Color = crate::overlays::COVEN_CODE_ACCENT;
12081218
/// Accent color for plan mode (blue).
@@ -1524,7 +1534,7 @@ impl App {
15241534
last_exit_key_warning: None,
15251535
exit_key_sequence_start: None,
15261536
daemon_online: crate::coven_status::daemon_looks_online(),
1527-
daemon_last_checked: 0,
1537+
daemon_last_checked: std::time::Instant::now(),
15281538
familiar_switcher_open: false,
15291539
familiar_switcher_list: Self::default_familiar_switcher_list(),
15301540
familiar_switcher_idx: 0,
@@ -2067,6 +2077,16 @@ impl App {
20672077
None
20682078
}
20692079

2080+
/// Re-read daemon reachability into [`Self::daemon_online`], at most once
2081+
/// per `DAEMON_STATUS_REFRESH` (1 s). The event loop calls this every
2082+
/// iteration, before drawing, whichever renderer draws.
2083+
pub fn refresh_daemon_status(&mut self, now: std::time::Instant) {
2084+
if now.saturating_duration_since(self.daemon_last_checked) >= DAEMON_STATUS_REFRESH {
2085+
self.daemon_last_checked = now;
2086+
self.daemon_online = crate::coven_status::daemon_looks_online();
2087+
}
2088+
}
2089+
20702090
/// Update the familiar pose for this render frame.
20712091
///
20722092
/// Toggles between `Idle { frame }` (blink/sway idle loop) and
@@ -8370,13 +8390,7 @@ impl App {
83708390
loop {
83718391
self.frame_count = self.frame_count.wrapping_add(1);
83728392

8373-
// Re-check daemon reachability ~every 30 seconds (300 frames at
8374-
// 10fps). The probe is cached and non-blocking; it also honors
8375-
// COVEN_HOME, unlike a hardcoded ~/.coven/coven.sock check.
8376-
if self.frame_count.wrapping_sub(self.daemon_last_checked) >= 300 {
8377-
self.daemon_last_checked = self.frame_count;
8378-
self.daemon_online = crate::coven_status::daemon_looks_online();
8379-
}
8393+
self.refresh_daemon_status(std::time::Instant::now());
83808394

83818395
self.poll_session_list();
83828396

@@ -9153,6 +9167,132 @@ mod tests {
91539167
assert!(list.is_empty());
91549168
}
91559169

9170+
/// #513: the refresh the event loop calls each iteration makes
9171+
/// `daemon_online` follow the daemon, and reads it no more often than
9172+
/// `DAEMON_STATUS_REFRESH`.
9173+
#[cfg(unix)]
9174+
#[test]
9175+
fn daemon_status_refresh_follows_the_daemon_socket() {
9176+
use std::io::{Read, Write};
9177+
use std::sync::atomic::{AtomicBool, Ordering};
9178+
use std::time::{Duration, Instant};
9179+
9180+
// Advance the loop's clock one interval per call, as a running loop
9181+
// would, until the reading matches. The probe itself runs on a
9182+
// background thread, so allow real time for it to land.
9183+
fn refresh_until(app: &mut App, now: &mut Instant, online: bool) -> bool {
9184+
let deadline = Instant::now() + Duration::from_secs(30);
9185+
while Instant::now() < deadline {
9186+
*now += DAEMON_STATUS_REFRESH;
9187+
app.refresh_daemon_status(*now);
9188+
if app.daemon_online == online {
9189+
return true;
9190+
}
9191+
std::thread::sleep(Duration::from_millis(20));
9192+
}
9193+
false
9194+
}
9195+
9196+
let temp = tempfile::tempdir().expect("tempdir");
9197+
let home = temp.path().join("home");
9198+
let coven_home = temp.path().join("coven");
9199+
std::fs::create_dir_all(&home).expect("home dir");
9200+
std::fs::create_dir_all(&coven_home).expect("coven home dir");
9201+
let _guard = EnvGuard::set(&home, &coven_home);
9202+
let socket = coven_home.join("coven.sock");
9203+
9204+
// A fake daemon that reads each request, then answers it. Answering
9205+
// before the request arrives could close the stream under the
9206+
// probe's write and read as offline.
9207+
let listener = std::os::unix::net::UnixListener::bind(&socket).expect("bind socket");
9208+
listener
9209+
.set_nonblocking(true)
9210+
.expect("nonblocking listener");
9211+
let stop = Arc::new(AtomicBool::new(false));
9212+
let daemon = {
9213+
let stop = Arc::clone(&stop);
9214+
std::thread::spawn(move || {
9215+
while !stop.load(Ordering::Acquire) {
9216+
let Ok((mut stream, _)) = listener.accept() else {
9217+
std::thread::sleep(Duration::from_millis(5));
9218+
continue;
9219+
};
9220+
// Accepted streams inherit O_NONBLOCK on macOS.
9221+
let _ = stream.set_nonblocking(false);
9222+
let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
9223+
let mut request = Vec::new();
9224+
let mut chunk = [0_u8; 256];
9225+
while !request.windows(4).any(|w| w == b"\r\n\r\n") {
9226+
match stream.read(&mut chunk) {
9227+
Ok(0) | Err(_) => break,
9228+
Ok(n) => request.extend_from_slice(&chunk[..n]),
9229+
}
9230+
}
9231+
let _ = stream.write_all(b"HTTP/1.0 200 OK\r\n\r\n[]");
9232+
}
9233+
// Dropping the listener leaves the socket file in place.
9234+
})
9235+
};
9236+
9237+
crate::coven_status::forget_daemon_probe();
9238+
let mut app = make_app();
9239+
let mut now = app.daemon_last_checked;
9240+
// Until a probe lands, the reading falls back to socket-file presence.
9241+
// Wait for the probe itself to find the daemon alive.
9242+
let deadline = Instant::now() + Duration::from_secs(10);
9243+
while crate::coven_status::cached_daemon_probe().is_none() && Instant::now() < deadline {
9244+
std::thread::sleep(Duration::from_millis(20));
9245+
}
9246+
assert_eq!(
9247+
crate::coven_status::cached_daemon_probe(),
9248+
Some(true),
9249+
"the probe did not find the fake daemon"
9250+
);
9251+
assert!(
9252+
refresh_until(&mut app, &mut now, true),
9253+
"daemon_online never turned on while the daemon answered"
9254+
);
9255+
9256+
// The daemon dies and leaves its socket behind. Only the probe can
9257+
// tell: the socket file still exists, so connecting is refused.
9258+
stop.store(true, Ordering::Release);
9259+
daemon.join().expect("fake daemon thread");
9260+
assert!(socket.exists(), "the stale socket file stays");
9261+
crate::coven_status::forget_daemon_probe();
9262+
let deadline = Instant::now() + Duration::from_secs(10);
9263+
while crate::coven_status::daemon_looks_online() && Instant::now() < deadline {
9264+
std::thread::sleep(Duration::from_millis(20));
9265+
}
9266+
assert!(
9267+
!crate::coven_status::daemon_looks_online(),
9268+
"the probe never saw the daemon go"
9269+
);
9270+
9271+
// The cache now says offline, but inside the interval the last
9272+
// reading stands: the refresh does not read every frame.
9273+
app.refresh_daemon_status(now + DAEMON_STATUS_REFRESH / 2);
9274+
assert!(
9275+
app.daemon_online,
9276+
"refresh read the daemon inside the interval"
9277+
);
9278+
9279+
assert!(
9280+
refresh_until(&mut app, &mut now, false),
9281+
"daemon_online stayed on after the daemon stopped answering"
9282+
);
9283+
9284+
// `coven daemon stop` removes the socket. A guard, not a refresh
9285+
// check (the reading is already off): with no socket file, neither
9286+
// the fallback nor a probe turns it back on.
9287+
std::fs::remove_file(&socket).expect("remove socket");
9288+
crate::coven_status::forget_daemon_probe();
9289+
for _ in 0..5 {
9290+
now += DAEMON_STATUS_REFRESH;
9291+
app.refresh_daemon_status(now);
9292+
assert!(!app.daemon_online, "daemon_online came back with no socket");
9293+
}
9294+
}
9295+
91569296
#[test]
91579297
fn app_does_not_infer_builtin_familiar_without_saved_roster() {
91589298
let temp = tempfile::tempdir().expect("tempdir");

0 commit comments

Comments
 (0)