# Change notification

Nothing in the Worker or in a window looks again on a short timer to find out whether something changed. The code that makes a change says so once, and whoever waits on it wakes. A loop with a deadline sleeps until it. An idle Worker does almost nothing.

1. **signal, watch, run-table commit** The change is announced once
2. **changes** One hub per Worker
3. **Loops wake; windows read again** Nothing looks on a short timer

## The hub

| Part | What it does |
| --- | --- |
| `signal(topic, *keys)` | Called right after a change is written. Keys name what changed: a conversation, a job, a table. Costs nothing when nobody listens |
| `listen`, `wait_for` | A loop waits for its topics, the next time it must act at (`due`), or a long `resync`. What was signalled while it was busy is kept |
| `subscribe` | For a loop that already waits on its own event: a callback on the signalling thread sets it |
| `watch` | Files written by another process (the CLI, a command's supervisor, the update controller, the user editing a skill). One thread takes the operating system's file events through `watchfiles`, which `uvicorn[standard]` already brings: 8 ms of processor time per 30 s idle, a change seen within about 0.7 s |
| `process_exits.watch_process(pid, identity, topic, key)` | A command's supervisor or the update controller: its topic is signalled when it ends, through `kqueue` `NOTE_EXIT` on macOS, a `pidfd` in `epoll` on Linux, the process handle in `WaitForMultipleObjects` on Windows. One thread serves every process; a killed one is seen about 1 ms later on macOS. The process is held before its birth identity is compared, so a reused PID counts as ended at once. Without these, it is looked at every 10 s |
| `publish` | Forwards a topic to the windows as `{"type": "changed", "topic", "keys"}`, changes within 0.2 s in one frame |

Threads and frames start only in the Worker (`start_watching` for file events and process exits, `set_publisher`). In the CLI and in tests a signal only wakes listeners, and a loop that relies on file events looks on its fallback interval (`poll`).

Some topics stay inside the Worker; they wake loops and are not sent to windows.

| Topic | Signalled when |
| --- | --- |
| `turn_ended` | Keyed by session: a turn's cancellation token retires the first time, the server hands back a run slot, or the Worker begins shutting down (no key) |
| `session.records` | A conversation's log makes a durable write; while a live run is watched, also a file event on the session's `main.jsonl` or `agents/`. Keyed by session |
| `memory.checkpoint` | A manual memory edit makes a history checkpoint pending |
| `recordings` | Keyed by recording id: a step is added, typing into a new element begins, or the recording stops. It drives the server-sent stream `/api/recordings/{id}/events` |

`subscribe_idle` (`run_control/idle.py`) gathers what can end a conversation's busy state: `turn_ended`, `runs`, and run-table commits to `executions` or `job_finalizations`. Whatever holds something for a busy conversation waits on it.

## Windows

`useChanged(topics, refresh, keys)` (`apps/web/lib/net/ws/changes.ts`) runs `refresh` when a frame for one of its topics and keys arrives.

- A hidden window keeps the change and reads once when it shows.
- After a reconnect every topic counts as changed: frames sent while the socket was down are lost.
- A cached answer stays fresh until a topic says it changed: React Query answers never age (`staleTime: Infinity`), and `QUERY_TOPICS` invalidates them by topic.
- Elapsed times, countdowns and "5 min ago" share one clock (below).

| Cache | Fresh until |
| --- | --- |
| React Query (`query-client.ts`) | `settings`, `routing`, `agents` or `applications` for the keys read from it; a reconnect invalidates everything |
| Settings reads (`settings-cache.ts`) | `settings`, `routing` or `channels`, or a reconnect; an unchanged answer redraws nothing |
| Activity reads (`activity-reads.ts`) | `op:execution-update`, `op:job-status`, `processes`, or the socket opening again |
| Project lists (`list-projects.ts`) | `project-changed` or `op:browser-connection` |
| Running apps for an @ mention | Read once per new @ being typed |
| Files and the project menu | One read, then again on `onReconnected` |
| Local model services (Ollama and others) | Opening the model picker asks `/api/models/enabled?probe=local`, which probes at once past the 30 s probe cache; opening the providers page or adding a provider reads again. Cached data shows first, an unchanged answer redraws nothing, and nothing probes in the background |

`useNow(cadence, from)` (`apps/web/lib/clock/use-now.ts`) is the one clock. The whole App keeps a single `setTimeout`, set for the earliest moment any shown text reads differently. It stops with no subscribers, pauses while the document is hidden and catches up when it shows.

Some views follow a source other than a topic:

- A terminal view reads from its cursor when the desktop app pushes output (`terminal:data`) or the resource changes.
- A web resource's thumbnail is taken after each Agent operation on its tab, not re-captured on a timer.
- System-access recovery checks when the window shows or gets focus back; a grant made elsewhere closes the wait on the server (`system_access.waits`).
- The recording bar reads a server-sent stream; provider sign-in asks with a request held up to 25 s until the sign-in changes.
- The command page reads on its own `op:execution-update`; the sidebar project list and working-folder chips ask again when the socket opens.

## Decisions

| Decision | Why |
| --- | --- |
| Announce changes; do not look for them | OpenCode works this way: one bus inside the server, file events from the operating system, and a stream of events the client reads instead of polling. Looking every few seconds cost an idle Worker 2.5 s of processor time per 30 s and found nothing |
| Keep a long resync | A lost announcement must not leave work undone. Kubernetes controllers work from events and still list everything again on a long period; here 30 to 60 s for loops that hold a turn or a Job, 300 s elsewhere |
| Wait until a due time | Deadlines (a Job's budget, a durable wait expiring, a scheduled agent, a pending checkpoint, a credential's expiry, the `recheck_in` that channels and routing return) are known in advance; a loop or window sleeps until the earliest one instead of checking whether it has come |
| Operating system file events through `watchfiles` | It is already installed with the server, has wheels for macOS, Linux and Windows, and falls back to polling by itself where events cannot be had (WSL, some network drives) |
| A loop is not woken by its own writes | A pass that writes would otherwise wake itself for ever |
| Folder metadata is not a change | The self-update store chmods its folder on every write lock; counting that would wake the watchdog and the reconciler for nothing. A file made or changed inside a watched folder still counts |
| Liveness comes from the operating system, not from heartbeats | A heartbeat costs a write for a process's whole life and still leaves its death unseen until a staleness deadline passes (15 s for a supervisor, 30 s for the controller). The operating system knows the moment a process ends, as `waitpid` does for a parent; kqueue, pidfd and process handles give that to any process. A process says once who it is (pid and birth identity, in its record, `controller.json` or the `.migrating` marker) and writes nothing more |
| An exit, not a hang | None of the replaced heartbeats detected a hang: each was written by a timer thread of its own, which goes on beating while the work is stuck. A stuck controller or migration is bounded by its phase limits (`MIGRATION_LIMIT_SECONDS`, `VERIFY_LIMIT_SECONDS`), a stuck command by its own Stop |
| Busy waits wait on what ends them | A notice, a queued message or a Goal's next turn held for a busy conversation wakes through `subscribe_idle`, not on an interval |
| A running command and its waiter ring each other | The supervisor and the tool call waiting on it are separate processes, and a quick command must return in milliseconds, so file events (about 0.7 s, and only in the Worker) are too slow. Each supervisor listens on a loopback TCP port with a token in its record: the one local channel Python has on macOS, Linux and Windows alike. `processes.db` stays the record; a ring only says "look now", and its connection closing says the supervisor ended ([command sessions](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/command-sessions.html#wakeups)) |
| Bursts are coalesced | Output streaming into a command's records or nodes written by a live run would wake a loop many times a second; the exit-notice loop looks at most every 2 s and the run tree pushes at most once a second. In windows, a gap only merges a burst of change frames into one read: `READ_GAP_MS` (execution debugger), `GAP_MS` (agent roster), `CHANGE_SETTLE_MS` (provider status) |
| Opening is the event | Local model services announce nothing; the picker or providers page opening is when their state matters, so that is when they are probed, never in the background |
| Probe what announces nothing, only while it matters | The operating system announces no permission grant, so the reconciler checks every 5 s only while a system-access wait is open |

## What each loop waits on

| Loop | Before | Now |
| --- | --- | --- |
| Job dispatcher | Claimed every 0.5 s, taking the self-update lock and a ledger transaction each time | A run-table commit to an admission, a finalization or a resource intent by another thread, or a self-update file; 60 s resync |
| Job reconciler | Every 5 s: every session directory, every self-update record | A run-table commit by another thread, a self-update file, or the next durable wait deadline; while a system-access wait is open it is due every 5 s (`SYSTEM_ACCESS_PROBE_SECONDS`, `waits.next_due`); passes at least 5 s apart; 60 s resync |
| Job budgets | Four times a second | Sleeps until the earliest runtime, idle, stall or hard-stop deadline; also wakes when another thread writes a stop to `commands`, a helper's usage is written (`roster`, spend checks at least 5 s apart), or a Job starts; 60 s resync. With no Job it waits for one to start |
| Event effects | Woken by each commit, and every second | Woken by each commit, or at the next retry of a failed effect; 300 s resync |
| Agent notices and queued messages | Every 2 s | A notice queued (`agent_notices`); while one waits for a busy conversation, that conversation possibly going idle (`subscribe_idle`); a failed delivery retries once after 2 s; 300 s resync |
| Background command exit notices | Every 2 s | A change to `processes.db`; while output keeps arriving, at most every 2 s, cut short when the conversation goes idle or a supervisor ends; 300 s resync. Each look follows every live record's supervisor (`record_changes.follow_supervisors`); one that ends without writing its command's end turns the record `unknown` at once. A quiet running command writes nothing |
| A command's supervisor | Read its stop and stdin rows and the command's liveness every 50 ms | The command's end (`SIGCHLD` through `set_wakeup_fd`; a Windows job's completion port), a writer connecting to its doorbell after inserting a row, a blocked stdin pipe with room again, or a stop's 5 s grace ending |
| A command tool call (`collect`), a stop or input waiting to be applied, a launch | Read the record every 50 ms | The supervisor's ring after each output chunk, status or acknowledgement; its connection closing; a stop fired for the turn (`cancellation.on_cancel`); the launch's `ready` line; the yield time or limit; 10 s resync. The same in the Worker, `--print` and scripts |
| A command's group leader (`group_guard`) | Listed its group every 0.1 s until a background child ended | Each remaining member's exit (kqueue `NOTE_EXIT`, a pidfd), then the group listed once more |
| Run slot for a Goal's next turn (`run_slot.hold_admitted`) | Every 0.5 s | `subscribe_idle`; 30 s resync; a 0.5 s retry only when the session's file lock times out |
| Live run tree (`dag.live_progress`) | Every 0.15 s, backing off to 1.2 s | The run writing a node (`session.records`), coalesced: the first tree after at least 0.1 s, then at least 1 s apart; 60 s resync; a final push at the end |
| Self-update watchdog | Every 10 s | A self-update file, or the exit of the process named in the update's `controller.json`, which is then launched again; after a launch, 30 s for the new controller to say who it is; 300 s resync; every 10 s only where file events are unavailable |
| Programs watcher | A fingerprint of every package and application source every 5 s | File events on the Programs folder, the source and catalog files and each enabled application's tree (`programs.sources`); the fingerprint is still compared, so an event that changes nothing rescans nothing |
| Skills watcher | A walk of the skill folders every 5 s | File events on each skill root (`skills.files`); a plugin's new root is watched when the plugin registers it |
| Stop request | The main thread looked for the file four times a second | A file event on `worker.stop`; a signal still interrupts the wait at once. On Windows, where a wait is not interrupted by Ctrl-C, the main thread wakes each second |
| Web build, thread and memory sample requests | A file read every 2 s each | A file event on `BUILD_ID` or on the request file |
| Channel supervisor | Accounts and heartbeats every 5 s | An account or credentials file, or a start retry coming due; 300 s resync. No heartbeat loop: an adapter thread marks itself running when it starts and signals `channels` when it ends |
| Always-on ticker | Every always-on agent read every 30 s | Sleeps until the earliest scheduled wake; an agent's settings or state changing wakes it (`always_on`). Every 30 s only while a check-in runs or a run has a time limit |
| Scheduled tasks | Every minute | Sleeps until the next cron match, one-time run or command limit; saving a task wakes it (`schedule.entries`). Each wait is at most a minute of wall clock, so a firing missed while the computer slept is seen |
| Idle-session memory watcher | Every 5 minutes | Sleeps until the next known idle deadline or retry, at most 300 s |
| Memory manual checkpoints | Every 15 s | Sleeps until the pending checkpoint is due; `memory.checkpoint` wakes it; 300 s resync |
| Following another application's window (`embedding/follow/`) | The view read the window's state every 1.5 s | OS events from the first view of the window to the last: Accessibility observers and kqueue on macOS, `SetWinEventHook` on Windows, `StructureNotify` and `PropertyChange` on X11; each signals `embedded_windows` |
| Control overlay place report (`desktop/macos/window_watch.py`, `desktop/macos/ax_events.py`) | Every 0.12 s while a step runs | Accessibility observers on the application element of every app with a window on screen (window created, moved, resized, destroyed, minimized, restored; focused window changed; app activated, deactivated, hidden, shown) and a kqueue exit per process; one window-list read per burst; 5 s resync while a step runs; observers only while a window is watched |

The apps to observe come from the window list: NSWorkspace notifications never reach a Worker, which has no main run loop.

### In the windows

| Wait | Before | Now |
| --- | --- | --- |
| A window view's state (`live-window-view.tsx`) | Read every 1.5 s; a lost capture retaken after 1 s | Read once in the animation frame after an `embedded_windows` frame, and a lost capture retaken then |
| A window tab's own layout | Every 120 ms | A `ResizeObserver`, an `IntersectionObserver` for shifts without resize, page resize and zoom, scroll and visibility, coalesced per animation frame |
| The App window moving (macOS window tab) | Every 400 ms | Electron `move` and `resize` on the App window, sent as `embedded-window:host-changed` IPC |
| Elapsed times and "ago" text | A timer in each component (runtime block, task block, attach card, retry status, meeting window, recording bar, chats page, routing overview) | The one shared clock, `useNow` |
| Optimistic actions (`optimistic-action.ts`) | Every 250 ms | Subscribed to the store it reads, with one 10 s deadline |
| An unconfirmed write (`ws-request.ts`) | Reconciled every 250 ms | An `operation.receipts` frame for its idempotency key; asks once on reconnect; one deadline |
| A recorded pane's place (`pane-recorder.ts`) | Every 200 ms | A `ResizeObserver`, a `MutationObserver` on ancestors' `style` and `class`, resize and scroll; each animation frame only while a transition or animation runs |
| A recorded pane closing | Every 500 ms | A `ResizeObserver` and a `MutationObserver` on the body |
| Send queue's run state (`send-queue.ts`) | Every 1.5 s | Asks once after the current microtask for a run slot with no id, then only when a `running_task_clear` does not match, or on reconnect |
| A steer's confirmation (`steer-message.ts`) | A timer | Asks again on that execution's `op:execution-update`, a run-slot change or reconnect; a backoff timer only after a transport failure |
| Stop, then rewind (`rewind-actions.ts`) | Every 400 ms, backing off to 5 s | The session's run-slot change, `op:execution-update`, `op:job-status` or reconnect; one 15 s deadline |

## What windows listen to

| Topic | Signalled when | Read again |
| --- | --- | --- |
| `conversation.resources` | A machine or desktop is attached or let go, a browser page changes, a UI binding is made or released, a run changes status. Keyed by the session and every session above it, so a helper's change reaches the conversation on screen | A conversation's resources list, instead of every 3 s for each conversation on screen |
| `system_access.waits` | A run pauses or resumes for a permission | The waiting-for-permission list, instead of every 2 s while one waits |
| `runs`, `roster` | A Job is written, topics are sorted, a helper's usage or stall is recorded | The Activity lists and the helper roster, instead of every 30 s and every 4 s while sorting |
| `inbox`, `work` | An always-on report is written or seen, a person writes, a scheduled task or its run record changes | The pending inbox and the conversation's open work, instead of every 30 s |
| `programs`, `applications` | Programs are rescanned or disposed; an application loads, unloads or its catalog changes | The Programs page, the new tab page and the sidebar, instead of every 5, 10 and 30 s |
| `mcp` | An MCP server starts, connects, fails, stops or is removed | The MCP page, instead of every 4 s |
| `channels` | An account changes, an adapter starts, stops or retries, or its running mark appears or clears | Channel settings and the channel health dot, instead of every 5 and 30 s |
| `application-state` | An application instance's state document is saved (key: the instance) | That application's window, as its `state` event |
| `application-audio` | A recording the host makes for an instance starts, takes or hands over a chunk, or ends | That application's window, as its `audio` event; Meetings no longer reads every 4 s while recording |
| `documents` | A file a window has open changes on disk. Keyed by a hash of the file's path; the window starts following the file with `/api/documents/stat`, and the Worker watches it | The document window's file metadata |
| `processes` | A write to `processes.db` or its `-wal`, by a command's supervisor | The programs panel of a conversation |
| `routing` | The usage ledger records a provider call or route event, a cold session finishes opening, or a credential changes | The routing overview in provider settings |
| `embedded_windows` | A window another application owns, shown in a tab or preview, moves, resizes, is minimized or restored, is renamed, gains focus or closes, or its process exits. Keyed by window id | That window view's state, instead of every 1.5 s |
| `operation.receipts` | A file operation leaves `in_flight`, or a turn's revert or `reapply_turn` ends. Keyed by idempotency key (`operation_receipts.py`) | The receipt of a write whose answer was lost, instead of every 250 ms |
| `settings` | A file event on `config.json`, written by the Worker or another process | Enabled models, providers, fallbacks and Agents' defaults |
| `agents` | A file event on any saved Agent's `agent.json` (a recursive watch) | The Agents list |

A program's own process writes `session-resources.changed` beside the database, and the Worker watches that file rather than the database, which it writes all the time itself. The Worker writes `processes.db` only when it delivers a notice or a supervisor ends, so that file is watched directly.

## Timers that stay

| Timer | Why |
| --- | --- |
| A launched controller's start window | After the watchdog launches a controller, it waits up to 30 s for `controller.json` before launching again; nothing announces a launch that produced no process |
| The fallback process look | Every 10 s, only for a process the operating system cannot follow here |
| A stop's grace | A stopped command's group has 5 s after SIGTERM before SIGKILL; nothing announces that a process ignores SIGTERM |
| A command group without exit events | Where neither kqueue nor pidfds exist (a Linux kernel before 5.3), `group_guard` lists its group every 0.1 s while a background child runs |
| Loop-stall watch | It asks the event loop to answer four times a second to notice a loop that stopped answering: a hang, which no exit announces. Idle, it costs 8.8 ms of processor time per 20 s. Timing only the loop's work, by wrapping its selector, would cost nothing idle but misses a loop woken yet waiting for the interpreter another thread holds, the case `busy_threads` names; the ping sees it |
| The shared clock | Elapsed times and "2 min ago" redraw from one App-wide timer, set for the next moment any shown text changes; they read nothing |
| System-access probe | The operating system announces no permission grant; the Worker checks every 5 s only while a system-access wait is open |
| Without Accessibility access | Where the Worker cannot start Accessibility observers, a window view reads state and retries a lost picture every 1.5 s while open, and the overlay reads the window list every 0.12 s while a step runs. Taking a window or a step needs that access anyway; ScreenCaptureKit cannot replace it, because a window capture never shows the windows covering it |
| Network checks and channel long-polls | Releases, plugin updates and subscription catalogues are fetched every few hours; a channel adapter's long-poll is how its service delivers messages |
| Daily and ten-minute schedules | Memory sleep, tool output collection and clearing a version's start records after ten minutes of service sleep until their time |
| Request timeouts and backoff | A request that gets no answer gives up after its timeout, and a failed read is asked again with growing gaps |
