A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
fix(desktop): recover a refused panel and harden the daemon pid file
Alan Buscaglia6932a1bf3904
diff --git a/apps/desktop/src-tauri/src/daemon.rs b/apps/desktop/src-tauri/src/daemon.rsindex fbcc0c7..5e7a287 100644--- a/apps/desktop/src-tauri/src/daemon.rs+++ b/apps/desktop/src-tauri/src/daemon.rs@@ -84,21 +84,58 @@ pub fn process_started(_pid: u32) -> Option<u64> {None}-/// Records the daemon just spawned as `pid` (private, 0600).+/// Records the daemon just spawned as `pid` (private, 0600). A new file in the same folder renamed+/// over the pid file: never written through a symlink there, and never seen half written.pub fn record_launch(data_dir: &Path, pid: u32) -> io::Result<()> {let started = process_started(pid).ok_or_else(|| io::Error::other("the assistant is not running"))?;- let mut file = OpenOptions::new().create(true).write(true).truncate(true).mode(0o600).open(data_dir.join(PID_FILE))?;- file.set_permissions(fs::Permissions::from_mode(0o600))?;- use std::io::Write;- writeln!(file, "{pid} {started}")+ let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());+ let temp = data_dir.join(format!(".{PID_FILE}.{}.{nanos}", std::process::id()));+ let written = OpenOptions::new()+ .write(true)+ .create_new(true)+ .mode(0o600)+ .custom_flags(libc::O_NOFOLLOW)+ .open(&temp)+ .and_then(|mut file| {+ file.set_permissions(fs::Permissions::from_mode(0o600))?;+ use std::io::Write;+ writeln!(file, "{pid} {started}")+ })+ .and_then(|()| fs::rename(&temp, data_dir.join(PID_FILE)));+ if written.is_err() {+ let _ = fs::remove_file(&temp);+ }+ written+}++/// A pid file holds `<pid> <start time>`, far below this.+const PID_FILE_MAX: u64 = 64;++/// Whether a pid read from the pid file may name a daemon to signal: never this app, its parent,+/// init, or the kernel.+fn may_be_daemon(pid: u32) -> bool {+ // SAFETY: getppid(2) has no preconditions.+ let parent = u32::try_from(unsafe { libc::getppid() }).ok();+ pid > 1 && pid != std::process::id() && Some(pid) != parent}-/// The daemon the pid file names, if it holds a launch.+/// The daemon the pid file names, if it holds a launch. Only a small regular file is read: a+/// symlink, a FIFO, or anything else there is ignored (opened without following or blocking).pub fn recorded_launch(data_dir: &Path) -> Option<Launched> {- let text = fs::read_to_string(data_dir.join(PID_FILE)).ok()?;+ let file = OpenOptions::new()+ .read(true)+ .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)+ .open(data_dir.join(PID_FILE))+ .ok()?;+ let meta = file.metadata().ok()?;+ if !meta.file_type().is_file() || meta.len() > PID_FILE_MAX {+ return None;+ }+ let mut text = String::new();+ io::Read::read_to_string(&mut io::Read::take(file, PID_FILE_MAX), &mut text).ok()?;let mut parts = text.split_whitespace();let launched = Launched { pid: parts.next()?.parse().ok()?, started: parts.next()?.parse().ok()? };- (parts.next().is_none() && launched.pid > 1).then_some(launched)+ (parts.next().is_none() && may_be_daemon(launched.pid)).then_some(launched)}/// The recorded daemon, while that same process still runs (a reused pid has another start time).@@ -119,6 +156,9 @@ fn stop_orphan(launch: Launched, grace: Duration) {let Ok(pid) = libc::pid_t::try_from(launch.pid) else {return;};+ if !may_be_daemon(launch.pid) {+ return;+ }let same = || process_started(launch.pid) == Some(launch.started);for (signal, wait) in [(libc::SIGTERM, grace), (libc::SIGKILL, Duration::from_secs(2))] {if !same() {@@ -346,6 +386,8 @@ pub struct Daemon {handler: Option<Arc<dyn Handler>>,/// Why the last start neither started nor attached ([`foreign_daemon_message`]).refused: Mutex<Option<String>>,+ /// Told each time a start leaves a daemon the app may use answering.+ ready: Option<Arc<dyn Fn() + Send + Sync>>,/// Replaces [`launch_spec`] (tests).launch: Option<LaunchSpec>,/// Replaces the `/health` probe (tests).@@ -363,6 +405,7 @@ impl Daemon {channel: Mutex::new(None),handler: None,refused: Mutex::new(None),+ ready: None,launch: None,#[cfg(test)]health: None,@@ -375,6 +418,13 @@ impl Daemon {self}+ /// `ready` runs each time a start (at launch or from Restart assistant) leaves a daemon the app+ /// may use answering, so a window that was refused can connect without a reopen.+ pub fn on_ready(mut self, ready: Arc<dyn Fn() + Send + Sync>) -> Self {+ self.ready = Some(ready);+ self+ }+#[cfg(test)]fn with_launch(mut self, spec: LaunchSpec) -> Self {self.launch = Some(spec);@@ -441,8 +491,16 @@ impl Daemon {}/// Spawns the daemon, or waits for the one this app spawned; see [`start_plan`] for a daemon- /// already on the port. Blocking: call off the main thread.+ /// already on the port. Tells [`Daemon::on_ready`] once it answers. Blocking: call off the main thread.pub fn ensure_running(&self, timeout: Duration) -> Result<(), String> {+ self.start(timeout)?;+ if let Some(ready) = &self.ready {+ ready();+ }+ Ok(())+ }++ fn start(&self, timeout: Duration) -> Result<(), String> {let wants_channel = self.handler.is_some();let owns_child = self.owns_running();let orphan = if wants_channel && !owns_child { live_orphan(&self.data_dir) } else { None };@@ -852,14 +910,143 @@ done"#;child.kill().unwrap();child.wait().unwrap();assert_eq!(live_orphan(&dir), None);- // Another live process under that number (here this test's own) is never taken for it.- let me = std::process::id();- fs::write(dir.join(PID_FILE), format!("{me} {}\n", process_started(me).unwrap() + 1)).unwrap();+ // Another live process under that number (a later start time) is never taken for it.+ let mut other = Command::new("/bin/sleep").arg("30").spawn().unwrap();+ let started = process_started(other.id()).unwrap();+ fs::write(dir.join(PID_FILE), format!("{} {}\n", other.id(), started + 1)).unwrap();assert_eq!(live_orphan(&dir), None);+ other.kill().unwrap();+ other.wait().unwrap();fs::write(dir.join(PID_FILE), "not a launch\n").unwrap();assert_eq!(recorded_launch(&dir), None);}+ /// A pid file naming `pid` with its real start time, as `record_launch` would write it.+ fn launch_line(pid: u32) -> String {+ format!("{pid} {}\n", process_started(pid).expect("a live process"))+ }++ #[test]+ fn the_pid_file_never_names_the_app_its_parent_or_the_system() {+ let dir = scratch_dir("pid-self");+ fs::create_dir_all(&dir).unwrap();+ let me = std::process::id();+ // SAFETY: getppid(2) has no preconditions.+ let parent = u32::try_from(unsafe { libc::getppid() }).unwrap();+ for pid in [me, parent] {+ fs::write(dir.join(PID_FILE), launch_line(pid)).unwrap();+ assert_eq!(recorded_launch(&dir), None, "pid {pid}");+ assert_eq!(live_orphan(&dir), None, "pid {pid}");+ }+ for pid in [0, 1] {+ fs::write(dir.join(PID_FILE), format!("{pid} 1\n")).unwrap();+ assert_eq!(recorded_launch(&dir), None, "pid {pid}");+ }+ }++ #[test]+ fn a_pid_file_that_is_a_symlink_is_not_read_and_its_target_is_untouched() {+ let dir = scratch_dir("pid-symlink-read");+ fs::create_dir_all(&dir).unwrap();+ let mut child = Command::new("/bin/sleep").arg("30").spawn().unwrap();+ let target = dir.join("elsewhere");+ let line = launch_line(child.id());+ fs::write(&target, &line).unwrap();+ std::os::unix::fs::symlink(&target, dir.join(PID_FILE)).unwrap();+ assert_eq!(recorded_launch(&dir), None);+ assert_eq!(live_orphan(&dir), None);+ assert_eq!(fs::read_to_string(&target).unwrap(), line);+ child.kill().unwrap();+ child.wait().unwrap();+ }++ #[test]+ fn recording_a_launch_never_writes_through_a_symlink() {+ let dir = scratch_dir("pid-symlink-write");+ fs::create_dir_all(&dir).unwrap();+ let target = dir.join("elsewhere");+ fs::write(&target, "keep me\n").unwrap();+ std::os::unix::fs::symlink(&target, dir.join(PID_FILE)).unwrap();+ let mut child = Command::new("/bin/sleep").arg("30").spawn().unwrap();+ record_launch(&dir, child.id()).unwrap();+ assert_eq!(fs::read_to_string(&target).unwrap(), "keep me\n");+ let file = fs::symlink_metadata(dir.join(PID_FILE)).unwrap();+ assert!(file.file_type().is_file(), "{:?}", file.file_type());+ assert_eq!(file.permissions().mode() & 0o777, 0o600);+ assert_eq!(recorded_launch(&dir).map(|launch| launch.pid), Some(child.id()));+ child.kill().unwrap();+ child.wait().unwrap();+ }++ #[test]+ fn recording_a_launch_replaces_the_pid_file_whole() {+ use std::os::unix::fs::MetadataExt;+ let dir = scratch_dir("pid-atomic");+ fs::create_dir_all(&dir).unwrap();+ let mut first = Command::new("/bin/sleep").arg("30").spawn().unwrap();+ let mut second = Command::new("/bin/sleep").arg("30").spawn().unwrap();+ record_launch(&dir, first.id()).unwrap();+ let before = fs::metadata(dir.join(PID_FILE)).unwrap().ino();+ record_launch(&dir, second.id()).unwrap();+ // A new file renamed over the old one: a reader sees one launch or the other, never half.+ assert_ne!(fs::metadata(dir.join(PID_FILE)).unwrap().ino(), before);+ assert_eq!(fs::read_to_string(dir.join(PID_FILE)).unwrap(), launch_line(second.id()));+ // Nothing else is left in the folder.+ assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);+ for child in [&mut first, &mut second] {+ child.kill().unwrap();+ child.wait().unwrap();+ }+ }++ #[test]+ fn a_pid_file_that_is_not_a_small_regular_file_is_not_read() {+ let dir = scratch_dir("pid-odd");+ fs::create_dir_all(&dir).unwrap();+ let mut child = Command::new("/bin/sleep").arg("30").spawn().unwrap();+ // A real launch followed by padding past any launch's size.+ fs::write(dir.join(PID_FILE), format!("{}{}", launch_line(child.id()), " ".repeat(4096))).unwrap();+ assert_eq!(live_orphan(&dir), None);+ fs::remove_file(dir.join(PID_FILE)).unwrap();+ // A FIFO would block a plain open; it is refused at once.+ let fifo = std::ffi::CString::new(dir.join(PID_FILE).as_os_str().as_encoded_bytes()).unwrap();+ // SAFETY: mkfifo(2) on a path we own, from a valid C string.+ assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o600) }, 0);+ assert_eq!(live_orphan(&dir), None);+ child.kill().unwrap();+ child.wait().unwrap();+ }++ #[test]+ fn a_refused_app_announces_its_assistant_once_a_restart_starts_it() {+ let dir = scratch_dir("ready-after-restart");+ // Another daemon answers on the port until the user stops it; then only this app's own does.+ let foreign = Arc::new(std::sync::atomic::AtomicBool::new(true));+ let health = {+ let (dir, foreign) = (dir.clone(), foreign.clone());+ Arc::new(move || foreign.load(std::sync::atomic::Ordering::SeqCst) || live_orphan(&dir).is_some())+ };+ let ready = Arc::new(Mutex::new(0usize));+ let daemon = {+ let ready = ready.clone();+ Daemon::new(1, dir.clone(), None)+ .with_channel(Arc::new(Opened::default()))+ .with_launch(sh_spec(ECHO))+ .with_health(health)+ .on_ready(Arc::new(move || *ready.lock().unwrap() += 1))+ };+ assert_eq!(daemon.ensure_running(Duration::from_secs(5)), Err(foreign_daemon_message(1)));+ assert_eq!(*ready.lock().unwrap(), 0);+ // The user follows the refusal's exit: stops the other one, then "Restart assistant".+ foreign.store(false, std::sync::atomic::Ordering::SeqCst);+ assert_eq!(daemon.restart(Duration::from_secs(5)), RestartOutcome::Restarted);+ assert_eq!(*ready.lock().unwrap(), 1);+ // What the panel asks next now succeeds instead of repeating the refusal.+ assert_eq!(daemon.wait_ready(Duration::from_millis(300)), Ok(()));+ assert!(daemon.channel().is_some());+ daemon.stop();+ }+#[test]fn a_relaunched_app_after_a_crashed_one_gets_a_channel() {let dir = scratch_dir("relaunch");diff --git a/apps/desktop/src-tauri/src/shell.rs b/apps/desktop/src-tauri/src/shell.rsindex 153d98c..d868975 100644--- a/apps/desktop/src-tauri/src/shell.rs+++ b/apps/desktop/src-tauri/src/shell.rs@@ -47,6 +47,10 @@ const EDGE_MARGIN: i32 = 12;const PANEL_GAP: i32 = 8;const DRAG_SETTLE: Duration = Duration::from_millis(300);const DAEMON_START_TIMEOUT: Duration = Duration::from_secs(20);+/// Sent to the Dot and the panel each time the assistant this app may use starts answering (at+/// launch or after Restart assistant): a window that was refused, or whose `connection_info` gave up+/// first, asks again and connects without a reopen (S35.2).+const ASSISTANT_READY: &str = "dot://assistant-ready";struct Shell {config: DesktopConfig,@@ -170,6 +174,8 @@ async fn connector_command(app: AppHandle, client_id: String, message: serde_jso/// Waits until the daemon this app launched answers `/health`, then returns its URLs and token./// A daemon it did not launch is never used (S35.2): the answer is then the reason and its exit.+/// Replacing an earlier app's daemon can take longer than this waits (up to 17 s before the spawn);+/// the windows then connect on [`ASSISTANT_READY`].#[tauri::command]async fn connection_info(app: AppHandle) -> CommandResult<ConnectionInfo> {let shell = app.state::<Shell>();@@ -783,8 +789,15 @@ pub fn run() {};app.manage(computer);let runtime_dir = daemon::runtime_dir(|key| std::env::var(key).ok(), app.path().resource_dir().ok());+ let announcer = handle.clone();let daemon = Arc::new(- Daemon::new(config.port, config.data_dir.clone(), runtime_dir).with_channel(Arc::new(service)),+ Daemon::new(config.port, config.data_dir.clone(), runtime_dir)+ .with_channel(Arc::new(service))+ .on_ready(Arc::new(move || {+ if let Err(error) = announcer.emit(ASSISTANT_READY, ()) {+ eprintln!("gentle-dot: cannot tell the windows the assistant is ready: {error}");+ }+ })),);let (starter, notifier) = (daemon.clone(), handle.clone());thread::spawn(move || {@@ -913,6 +926,15 @@ mod tests {}}+ #[test]+ fn the_windows_listen_for_the_assistant_ready_event() {+ let desktop = include_str!("../../../../packages/ui/src/desktop.ts");+ let app = include_str!("../../../../packages/ui/src/App.tsx");+ let quoted = format!("\"{ASSISTANT_READY}\"");+ assert!(desktop.contains("ed), "desktop.ts does not accept {quoted}");+ assert!(app.contains(&format!("onDesktopEvent({quoted}")), "App.tsx does not listen for {quoted}");+ }+#[test]fn conversations_flag_reads_like_the_daemon() {assert!(conversations_on(Some("1")));diff --git a/docs/design.md b/docs/design.mdindex cdef8f5..d5bad80 100644--- a/docs/design.md+++ b/docs/design.md@@ -362,7 +362,7 @@ The app is single-instance (`tauri-plugin-single-instance`; D-Bus on Linux). A s### Daemon lifecycle-On launch, the app checks `GET /health`. If the daemon does not answer, the app spawns it: `<node> <repo>/packages/daemon/src/cli.ts`, with the `PATH` captured at build time (apps launched from Finder get a minimal `PATH`, and the daemon needs `gentle-shell`). `build.rs` records the absolute `node` path, the daemon script path, and `PATH`; `GENTLE_DOT_NODE` and `GENTLE_DOT_DAEMON_SCRIPT` override them at runtime. A daemon spawned by the app gets the app channel on fd 3 (§4) and stops by itself when that channel closes, so it never outlives the app, even after a crash or a kill (S35.2, #22). Each spawn records `<dataDir>/daemon.pid` (0600: the pid and the process start time, from `proc_pidinfo` on macOS and `/proc/<pid>/stat` on Linux); Quit stops the daemon, closes the channel, and removes the file. The app never attaches to a daemon it did not launch, which would have no channel and keep connectors locked. When a daemon answers at launch: if the pid file names a process that is still the same one (same start time), the app stops it (SIGTERM, SIGKILL after 10 s), waits for the port, and starts its own; otherwise (`pnpm dev`, or a daemon left by an app older than this rule) it starts nothing and shows a dialog naming the way out: stop the other one (Ctrl+C where `pnpm dev` runs, or the process on the port), then Restart assistant. The panel then gets that message from `connection_info` instead of a connection. A pid file names a process the app may signal, so a same-user process that rewrites it could make the app stop that process at the next launch, only while a daemon answers on the port; that user can already do so directly. Restart assistant restarts the daemon this app spawned, and shows the same dialog when another one holds the port. The UI connects only after the daemon this app spawned answers `/health`.+On launch, the app checks `GET /health`. If the daemon does not answer, the app spawns it: `<node> <repo>/packages/daemon/src/cli.ts`, with the `PATH` captured at build time (apps launched from Finder get a minimal `PATH`, and the daemon needs `gentle-shell`). `build.rs` records the absolute `node` path, the daemon script path, and `PATH`; `GENTLE_DOT_NODE` and `GENTLE_DOT_DAEMON_SCRIPT` override them at runtime. A daemon spawned by the app gets the app channel on fd 3 (§4) and stops by itself when that channel closes, so it never outlives the app, even after a crash or a kill (S35.2, #22). Each spawn records `<dataDir>/daemon.pid` (0600: the pid and the process start time, from `proc_pidinfo` on macOS and `/proc/<pid>/stat` on Linux), written to a new file in the same folder and renamed over the old one, so it is never written through a symlink and never read half written; it is read only as a small regular file, opened without following a symlink or blocking on a FIFO, and a record naming the app itself, its parent, init, or pid 0 is ignored. The start time is checked again before each signal. Quit stops the daemon, closes the channel, and removes the file. The app never attaches to a daemon it did not launch, which would have no channel and keep connectors locked. When a daemon answers at launch: if the pid file names a process that is still the same one (same start time), the app stops it (SIGTERM, SIGKILL after 10 s), waits for the port, and starts its own; otherwise (`pnpm dev`, or a daemon left by an app older than this rule) it starts nothing and shows a dialog naming the way out: stop the other one (Ctrl+C where `pnpm dev` runs, or the process on the port), then Restart assistant. The panel then gets that message from `connection_info` instead of a connection. A pid file names a process the app may signal, so a same-user process that rewrites it could make the app stop that process at the next launch, only while a daemon answers on the port; that user can already do so directly. Restart assistant restarts the daemon this app spawned, and shows the same dialog when another one holds the port. The UI connects only after the daemon this app spawned answers `/health`. Each time a start leaves that daemon answering (at launch or after Restart assistant), the app sends `dot://assistant-ready` to its windows, and a Dot or panel that was refused or gave up asks `connection_info` again and connects without a reopen. That also covers a slow replacement: `connection_info` waits 20 s, while stopping an earlier app's daemon can take up to 17 s (10 s grace, 2 s after SIGKILL, 5 s for the port) before the new one is spawned and given its own 20 s.## 10. Configurationdiff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsxindex 2880138..5f83c17 100644--- a/packages/ui/src/App.tsx+++ b/packages/ui/src/App.tsx@@ -105,12 +105,33 @@ function Assistant({ surface }: { surface: Surface }) {useEffect(() => {if (inDesktop()) {- connectionInfo().then(setInfo, (error: unknown) => {- const reason = typeof error === "string" ? error : error instanceof Error ? error.message : "";- if (reason) setUnreachable(reason);- else setMissingToken(true);- });- return;+ let live = true;+ const connect = () =>+ connectionInfo().then(+ (next) => {+ if (!live) return;+ // The same assistant keeps its connection; only a new one replaces it.+ setInfo((current) =>+ current?.url === next.url && current.token === next.token ? current : next,+ );+ setUnreachable(undefined);+ setMissingToken(false);+ },+ (error: unknown) => {+ if (!live) return;+ const reason = typeof error === "string" ? error : error instanceof Error ? error.message : "";+ if (reason) setUnreachable(reason);+ else setMissingToken(true);+ },+ );+ // A refused or timed-out window recovers without a reopen: the app reports its assistant+ // ready after Restart assistant, or after a start slower than `connection_info` waits (S35.2).+ const ready = onDesktopEvent("dot://assistant-ready", () => void connect());+ void connect();+ return () => {+ live = false;+ void ready.then((unlisten) => unlisten());+ };}const found = browserConnection();if (found) setInfo(found);diff --git a/packages/ui/src/desktop.ts b/packages/ui/src/desktop.tsindex ba67203..82c530a 100644--- a/packages/ui/src/desktop.ts+++ b/packages/ui/src/desktop.ts@@ -44,8 +44,12 @@ export async function startDragging(): Promise<void> {await getCurrentWindow().startDragging();}+/**+ * `dot://assistant-ready`: the app's assistant just started answering (at launch or after Restart+ * assistant), so a window it refused can ask `connection_info` again (S35.2).+ */export async function onDesktopEvent(- name: "dot://new-conversation" | "dot://panel-shown",+ name: "dot://new-conversation" | "dot://panel-shown" | "dot://assistant-ready",handler: () => void,) {if (!inDesktop()) return () => {};diff --git a/packages/ui/test/reconnect.test.tsx b/packages/ui/test/reconnect.test.tsxnew file mode 100644index 0000000..80c8819--- /dev/null+++ b/packages/ui/test/reconnect.test.tsx@@ -0,0 +1,108 @@+import { act, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ConnectionInfo } from "../src/client.ts";+import { type DotState, initialState } from "../src/store.ts";++/**+ * A window the app refused recovers without a reopen (S35.2): once the app reports its assistant+ * ready (`dot://assistant-ready`, after Restart assistant or a slow start), the panel and the Dot+ * ask again and connect. Through the mocked Tauri commands and desktop events.+ */+const h = vi.hoisted(() => ({+ connection: undefined as unknown as () => Promise<unknown>,+ invoke: vi.fn(),+ listeners: new Map<string, () => void>(),+ infos: [] as (ConnectionInfo | undefined)[],+ state: undefined as unknown as DotState,+}));++vi.mock("@tauri-apps/api/core", () => ({+ isTauri: () => true,+ invoke: (command: string, args?: unknown) => h.invoke(command, args),+}));++vi.mock("@tauri-apps/api/event", () => ({+ listen: async () => () => {},+}));++vi.mock("../src/desktop.ts", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../src/desktop.ts")>()),+ onDesktopEvent: async (name: string, handler: () => void) => {+ h.listeners.set(name, handler);+ return () => h.listeners.delete(name);+ },+}));++vi.mock("../src/useDot.ts", () => ({+ useDot: (info: ConnectionInfo | undefined) => {+ h.infos.push(info);+ return { state: h.state, send: () => {}, dismiss: () => {}, dispatch: () => {} };+ },+}));++const REFUSAL =+ "Another Gentle Dot assistant is already running on port 4317. Stop it, then choose Restart assistant.";+const INFO: ConnectionInfo = { url: "ws://127.0.0.1:4317/ws", token: "abc" };++async function renderApp(search: string) {+ window.history.replaceState(null, "", `/${search}`);+ const { App } = await import("../src/App.tsx");+ return render(<App />);+}++const READY = "dot://assistant-ready";++async function reportReady() {+ await waitFor(() => expect(h.listeners.has(READY)).toBe(true));+ await act(async () => h.listeners.get(READY)?.());+}++beforeEach(() => {+ h.listeners.clear();+ h.infos = [];+ h.state = { ...initialState, connection: "closed", agentState: "idle" };+ h.connection = async () => {+ throw REFUSAL;+ };+ h.invoke = vi.fn(async (command: string) => {+ if (command === "connection_info") return h.connection();+ if (command === "computer_status") return { active: false };+ return null;+ });+});++afterEach(() => {+ vi.restoreAllMocks();+ window.history.replaceState(null, "", "/");+});++describe("after the app refused its assistant (S35.2)", () => {+ it("the panel connects once the app reports the assistant ready", async () => {+ await renderApp("?surface=panel");+ expect(await screen.findByText(REFUSAL)).toHaveAttribute("role", "status");+ h.connection = async () => INFO;+ await reportReady();+ await waitFor(() => expect(h.infos.at(-1)).toEqual(INFO));+ expect(screen.queryByText(REFUSAL)).toBeNull();+ expect(screen.getByRole("textbox")).toBeInTheDocument();+ });++ it("the Dot connects once the app reports the assistant ready", async () => {+ await renderApp("?surface=dot");+ await waitFor(() => expect(h.invoke.mock.calls.some(([c]) => c === "connection_info")).toBe(true));+ expect(h.infos.at(-1)).toBeUndefined();+ h.connection = async () => INFO;+ await reportReady();+ await waitFor(() => expect(h.infos.at(-1)).toEqual(INFO));+ });++ it("a panel already connected keeps its connection when the app reports ready again", async () => {+ h.connection = async () => ({ ...INFO });+ await renderApp("?surface=panel");+ await waitFor(() => expect(h.infos.at(-1)).toEqual(INFO));+ const first = h.infos.at(-1);+ await reportReady();+ await waitFor(() => expect(h.invoke.mock.calls.filter(([c]) => c === "connection_info")).toHaveLength(2));+ expect(h.infos.at(-1)).toBe(first);+ });+});