Background agent service
The background agent is OpenLogi's long-lived owner of device access and input control. Its executable starts a headless runtime that keeps device-facing capabilities active, turns device and operating-system events into configured actions, coordinates cross-device handoff, and exposes safe local control to the desktop application and overlay. It belongs to the wider application composition model, while interprocess communication defines the client boundary. The desktop application and command-line interface use this boundary instead of owning live device access.
Service responsibility
The agent keeps work that must continue without the desktop window inside one process. It owns input capture, device access, background settings, pairing, host switching, lighting, transient device indicators, notices, and the local RPC service. Other processes request state or commands through IPC instead of opening a device themselves.
The production executable is paired with a hardware-free mock executable for GUI development. Both use the local service shape, but only the production executable claims the agent role and owns live device work.
The agent-core runtime provides the shared state and action path. It coordinates device facts, configuration, input sources, action dispatch, light observation, pointer precision state, transient overlay state, and orderly shutdown. Cloneable handles let watchers and IPC submit work without taking ownership of the runtime workers.
| Service area | Purpose |
|---|---|
| Device view | Find devices, track routes and health, and publish current inventory. |
| Input control | Capture supported device and OS input and resolve it to configured actions. |
| Device control | Read and write settings such as DPI, pointer speed, wheel mode, SmartShift, Fn-lock, Disable Keys, report rate, backlight, and lighting. |
| Exclusive workflows | Run pairing, unpairing, and host changes without conflicting with capture. |
| Light observation | Track standalone light state and changes made on the light itself. |
| Overlay state | Publish notices and short-lived lock-key and backlight indicators. |
| Cross-device Flow | Move configured devices between trusted computers when the cursor crosses a configured display edge. |
| Local clients | Serve the desktop application, overlay, and other local clients through the agent IPC contract. |
References: crates/…/orchestrator.rs• L126-206 crates/…/orchestrator.rs• L564-667 crates/…/server.rs• L51-68
Runtime coordination
The runtime combines configuration, device inventory, current application context, pointer context, permission state, and light state into shared projections. Watchers report changes to the orchestrator. The orchestrator then publishes capture plans, action maps, device routes, watched lights, pointer-speed targets, cross-device flow inputs, and client-visible state so device facts and configured actions stay aligned.
Capture publications separate a physical device's hardware target from the actions that run for it. App changes, pointer changes, and binding changes can refresh dispatch data without restarting an unchanged hardware session. Route changes, reconnect re-arms, and system resume remain hardware changes and retire only the affected session, except that a system resume can request all online sessions to re-arm.
Device identity is kept separate from its current route. This lets the agent preserve settings and pending recovery for the same physical device when inventory enriches its identity or the device moves to another receiver path. A true replacement does not inherit the old device's pending work.
The shared hardware context is the common boundary for device access, route channels, inventory, receiver ownership, light control, and host activity. Each request waits for the current transport turn before it resolves the authoritative channel, so queued work cannot pin a retired connection. Requests for the same physical transport take one shared turn, so receiver slots do not send competing HID transactions. This prevents a stale route or a second connection from taking control of the same device.
The runtime also gives competing writes a clear order. Newer user choices can replace older pending choices. Whole-state changes run in request order when each change depends on the state written by the previous change. Reconnect and wake paths re-apply volatile settings with bounded confirmation. A reconnect uses a short confirmation run, while a first sighting or system wake gets a longer run for devices that may still be starting.
The following diagram shows how state changes become device work and client-visible state.
flowchart LR
C[Config and client commands] --> O[Agent orchestrator]
I[Inventory and OS watchers] --> O
L[Light watchers] --> O
O --> P[Capture plans and dispatch maps]
O --> S[Observable snapshots]
P --> W[Capture managers]
W --> D[Device events and actions]
O --> H[Shared hardware context]
H --> D
O --> F[Cross-device Flow]
F --> N[Trusted peer handoff]
S --> R[Local IPC clients]
R --> C
References: crates/…/orchestrator.rs• L512-600 crates/…/orchestrator.rs• L1070-1108 crates/…/orchestrator.rs• L1361-1509 crates/…/hardware.rs• L234-349 crates/…/runtime.rs• L703-903
Device inventory
Inventory is the agent's current view of receiver devices, directly attached devices, and standalone raw-HID devices. Hotplug and device lifecycle events trigger settled updates. Scheduled repair and recovery scans restore the view when a host or firmware event is missing. A completed empty scan means “checked, no devices.” An enumeration failure keeps the last good view.
The inventory watcher owns the persistent enumeration path and publishes its channels to the agent's shared registry. It uses event-first reconciliation with bounded repair, a separate delayed confirmation path for volatile settings, and a lower-frequency authority scan for missed events and device features without broadcasts. Standalone device omissions receive a short grace period so a brief enumeration gap does not look like a real removal.
A device-wake event reaches the orchestrator before the snapshot that publishes a replacement channel. The orchestrator can then re-apply volatile settings even when the device stayed online in the published view. System wake requests the broader capture re-arm, while a device wake affects the settings and route that need recovery.
The orchestrator turns inventory into stable device identities and active runtime projections. A device can keep its saved settings when its route changes. Reconnect and wake events can re-apply settings that live in device memory. The service also preserves enough state to distinguish an unknown inventory from a known empty inventory and from an unavailable inventory source.
Inventory also carries device-originated backlight and lock-key updates. The first becomes a short-lived client indicator. The second becomes a short-lived lock-key indicator when the platform supports it. Reconnection intent causes a later refresh to restore volatile settings even when no offline state was observed.
References: crates/…/inventory.rs• L46-93 crates/…/inventory.rs• L180-239 crates/…/inventory.rs• L541-612 crates/…/schedule.rs• L118-205 crates/…/orchestrator.rs• L1390-1509
Input capture
Input capture has separate device and operating-system sources that share one action path. The agent-core action runtime owns the button lifecycles and action execution, while cloneable dispatch handles let each source submit input without owning worker shutdown. HID sessions handle device controls and keyboard keys. The operating-system hook handles remappable OS input when its permission and health allow it. Pointer context selects the target for pointer-scoped actions.
Capture plans describe each online enabled device and the one bound keyboard session, when a keyboard has keys to remap. A plan keeps hardware ownership tied to the physical device while its dispatch maps can refresh for a new application, pointer target, or configuration. The capture managers run sessions for all published device plans, not only the selected device. Disabled devices stay native, and an unavailable hook path fails open instead of swallowing physical input.
The operating-system hook may not identify which mouse produced an event. The selected device's physical route is therefore part of the hook state. When that route already owns a diverted control, unattributed hook edges pass through so another mouse keeps its native behavior instead of receiving the selected device's action.
Each capture session has a physical-device identity and an incarnation number. A changed route or capture target retires the old session and keeps its dispatch plan authoritative until teardown and firmware restoration complete. Only then can a successor take the slot. Events from an old session are ignored. An unexpected end enters delayed recovery, while a planned retirement can admit its successor as soon as ordered teardown finishes. Accepted input is forwarded before completion is reported, so the final device event cannot race the ownership change.
The device capture path resolves gestures, button presses, thumb-wheel movement, held-wheel output, and main-wheel output against the plan of the device that produced them. It uses the common action runtime for press lifecycles and sends diverted scrolling through the scroll path. A direct diverted control can also appear as an operating-system event on some hosts. The capture session records that ownership before forwarding its press, and the OS hook suppresses the matching press and release instead of dispatching it a second time.
The button runtime turns input into press, trigger, and end events. It tracks long-press deadlines and cancels active presses when a source ends, the pointer context changes, the action generation changes, or the worker shuts down. Each accepted press has one terminal event. Before a due long press fires, the worker settles queued state changes so deadline actions do not run against stale input state.
Pointer-scoped actions keep the target captured at press time and validate it again before dispatch. Any move to a different or unsupported target drops the action, including actions that do not need focus. Keyboard-like effects on a binding that differs from the focused profile also require the same identified window to remain focused; shared bindings use the focused-action route without that extra focus check.
Browser navigation keeps the target captured at press time. The service uses the captured application path or the platform keyboard path and suppresses duplicate events from the two input sources for each direction.
The scroll runtime applies smoothing and sensitivity without blocking input callbacks. Diverted wheel reports distinguish ratchet motion, free spin, and a finger stop, so natural spin-down does not become extra scrolling and a new push is not swallowed as settling. If a diverted device event cannot enter the worker, it returns a direct-output path so consumed physical input is not lost. A source-specific cancellation removes only that session's pending output.
References: crates/…/orchestrator.rs• L856-904 crates/…/orchestrator.rs• L1311-1363 crates/…/runtime.rs• L364-487 crates/…/runtime.rs• L703-903 crates/…/hook.rs• L220-341 crates/…/hook.rs• L394-479 crates/…/pointer.rs• L95-201 crates/…/free_spin.rs• L112-133 crates/…/free_spin.rs• L197-269 crates/…/gesture.rs• L194-260 crates/…/gesture.rs• L555-623 crates/…/dispatch.rs• L147-323 crates/…/keyboard.rs• L35-59 crates/…/keyboard.rs• L217-243
Secure input state
Secure Event Input is a macOS host state that hides key presses from the operating-system hook. The agent samples it in the background and publishes a settled status so clients can explain why OS key bindings do not fire. A brief “on” sample does not create a notice, while an “off” change or a change of the active app is reported at once.
References: crates/…/secure_input.rs• L1-27 crates/…/secure_input.rs• L81-111 crates/…/lifecycle.rs• L448-474
Virtual keyboard
The virtual keyboard is the macOS output path for synthesized keys. The agent reports whether it is active, unavailable, or unsupported, watches for its loss, and removes it only after action workers stop so held output can end cleanly.
References: crates/…/virtual_keyboard.rs• L27-70 crates/…/lifecycle.rs• L232-247 crates/…/lifecycle.rs• L358-364 crates/…/shutdown.rs• L153-175
Permission and host state
Permission watchers keep the service's view of macOS Accessibility and Input Monitoring current. Accessibility controls whether the operating-system hook runs. Input Monitoring controls whether the agent can open HID nodes. Other platforms publish fixed permission facts where no changing privacy grant exists.
Host activity also controls proactive device I/O. The shared gate stays closed during startup uncertainty, sleep, DarkWake, and inactive console sessions. Inventory stops reconciliation while the gate is closed. Capture sessions keep their passive ownership and do not retire or retry firmware work until the host reports a usable session. They then resume recovery and reconciliation.
References: crates/…/lifecycle.rs• L629-667 crates/…/lifecycle.rs• L842-869 crates/…/gesture.rs• L470-553 crates/…/keyboard.rs• L280-363
Background workflows
The agent runs workflows that need device ownership but have different lifetimes. Each workflow uses the shared receiver rules and publishes only the state or command surface that another process needs.
Pairing and unpairing
Receiver pairing runs in the agent because it must open and control the receiver. The desktop application starts, drives, and cancels the session through IPC. The agent admits one session, waits for an exclusive receiver lease after capture releases it, and publishes discovery, pairing, passkey, and terminal phases. The lease remains until the terminal event has been translated, so capture cannot resume before receiver cleanup is complete.
Unpairing uses the same exclusive boundary. After the receiver removes a device, the agent requests a fresh inventory pass so the freed slot leaves client-visible state.
References: crates/…/pairing.rs• L41-73 crates/…/pairing.rs• L76-218 crates/…/session.rs• L23-70 crates/…/session.rs• L125-210 crates/…/hardware.rs• L234-349
Flow peer pairing
Flow peer pairing is a separate, temporary network ceremony that creates trust for later cross-device handoff. While the user has pairing open, the agent advertises a pairing endpoint and discovers other computers that are also waiting. The endpoint accepts no trusted peer yet, so an unknown computer can complete only the pairing ceremony and cannot enter the normal Flow runtime.
One pairing attempt connects two computers, verifies their shared code, and saves the peer only after both users confirm it. The agent then reloads configuration so the saved key reaches the trusted Flow runtime. It publishes the current phase through the observable state and closes the temporary connection after the peer key is stored or the attempt ends.
The following diagram shows how a temporary pairing connection becomes a trusted Flow peer.
sequenceDiagram
participant G as GUI
participant A as Agent pairing
participant P as Peer computer
participant C as Saved configuration
participant F as Flow runtime
G->>A: Open pairing
A-->>P: Advertise and discover
G->>A: Select peer or address
A->>P: Pairing ceremony
A-->>G: Shared confirmation code
G->>A: Confirm code
A->>C: Save peer key
C-->>F: Reload trusted peer
A-->>G: Paired result
References: crates/…/pairing.rs• L1-20 crates/…/pairing.rs• L80-126 crates/…/pairing.rs• L527-625 crates/…/pairing.rs• L754-803 crates/…/stage.rs• L14-53 crates/…/stage.rs• L109-183
Host switching
Host switching keeps configured keyboard-to-device links active in the background. When a linked keyboard or one of its pointing devices requests a change, the service pauses related receiver work, performs the transition for the whole link, and waits for the expected device state before normal tracking resumes.
The manager keeps only the newest queued linked transition. It drains the old session and restores keyboard state before starting the next transition. A departing keyboard keeps its session slot until inventory no longer publishes the link or a bounded departure wait ends. A failed or interrupted restore stays pending and retries when the device and receiver become usable.
References: crates/…/orchestrator.rs• L117-146 crates/…/orchestrator.rs• L691-715 crates/…/host_switch.rs• L20-83 crates/…/host_switch.rs• L391-465 crates/…/host_switch.rs• L770-823
Cross-device Flow
Cross-device Flow lets trusted computers share configured mice, keyboards, and other supported devices. The agent watches cursor motion near a configured display edge. When the cursor crosses that edge, Flow coordinates a network handoff so a peer can take control of the devices and place the cursor at the matching edge.
The Flow controller receives configuration and inventory from the orchestrator. It stays dormant until the agent arms it and Flow has at least one configured peer. A running Flow generation owns peer links, peer status, the pointer edge detector, and the handoff session. A configuration change replaces that generation.
The handoff keeps device identity separate from the current connection. The receiving computer accepts only configured devices that are not already online there. The sending computer starts each host switch within the receiver's time window. The receiver reports whether all, some, or none of the requested devices arrived. It places the cursor when the first pointing device arrives.
The following diagram shows how local cursor motion becomes a peer handoff and a new local device state.
sequenceDiagram
participant P as Pointer and display edges
participant A as Agent Flow runtime
participant S as Sending computer
participant R as Receiving computer
participant I as Device inventory
P->>A: Edge crossing
A->>S: Start handoff request
S->>R: Trusted peer request
R->>R: Arm arrival window
R-->>S: Accept and entry point
S->>I: Switch configured devices
I-->>R: Devices become online
R->>P: Place cursor at entry edge
R-->>S: Handoff result
Flow uses a persistent machine identity for peer trust. Discovery can find peers automatically, while configured addresses remain a direct path. A pointer motion only wakes the current generation. This keeps the input hook non-blocking and prevents a stale generation from acting after a configuration change.
References: crates/…/controller.rs• L58-162 crates/…/runtime.rs• L75-85 crates/…/runtime.rs• L176-314 crates/…/devices.rs• L16-145 crates/…/handoff.rs• L130-215 crates/…/pointer.rs• L84-100
Camera-linked lighting
Camera activity becomes one service-wide fact. The orchestrator applies that fact to online lights configured for camera automation. Saved light settings stay separate from temporary effective power. A manual power choice acts as a temporary override until the next camera-use transition.
References: crates/…/orchestrator.rs• L1833-1865 crates/…/orchestrator.rs• L1867-1883
Standalone lighting
Standalone lights can change outside the application. The light watcher keeps one observation task for each online light that supports the service's light protocol, then sends initial state and later changes to the orchestrator. A light that is reachable only through a raw report is not treated as watchable.
The orchestrator exposes the latest read state to clients and remembers controls changed on the light until the user saves them. A failed application write restores the remembered change. A successful write or a matching saved value removes it. This keeps reconnects and config reloads from silently undoing a user's physical change.
References: crates/…/light.rs• L22-63 crates/…/light.rs• L91-155 crates/…/lights.rs• L55-109 crates/…/lights.rs• L112-228
Pointer precision
Pointer precision is an agent-owned temporary mode for mice whose speed OpenLogi controls. A precision action moves the mouse to its slowest supported speed and can show that mode on the DPI LED. A later toggle, a matching settings change, or a DPI preset returns the mouse to its saved value or device default.
The mode stays with the agent across device reconnects but not across agent restarts. The runtime orders precision, settings, preset, and reconnect writes together. This prevents an older background restore from overwriting a newer user choice and re-applies a needed restore until one write reaches the device.
References: crates/…/pointer_speed.rs• L1-38 crates/…/pointer_speed.rs• L238-429 crates/…/orchestrator.rs• L307-343 crates/…/runtime.rs• L203-279
Device settings
Device settings are agent-owned because a change can affect device state outside the life of an IPC request. For an online device, the agent writes and confirms the value before saving it. For an offline device, it saves the requested policy and applies it when the device returns. The agent then reloads the saved configuration through one path so the runtime, menu-bar controls, and background policies use the same value.
Backlight changes run in request order and keep the hardware attempt alive even if the requesting client goes away. Settings such as Fn-lock and report rate let a newer request replace an older pending request. Disable Keys uses a separate accepted-policy path: a manual request keeps ownership through the complete native write, while a timeout or cancellation leaves recovery work for a later inventory confirmation.
These policies prevent a late reconnect write from undoing a newer user choice. Each device operation resolves the current authoritative channel after receiver and transport admission, and a device identity check rejects a replacement device on the same route. Reads also wait for admitted writes on the same keyboard, so a client does not observe a state from before an earlier write has finished.
References: crates/…/settings.rs• L28-58 crates/…/settings.rs• L105-214 crates/…/disable_keys.rs• L74-130 crates/…/write_order.rs• L1-10 crates/…/orchestrator.rs• L342-365 crates/…/settings.rs• L12-31
Actions Ring
The Actions Ring is an agent-owned interaction session shown by a separate overlay process. The agent snapshots its layout and actions when the ring opens. The overlay receives presentation data and sends hover or activation commands back to the agent, which validates and runs them.
Haptic feedback is best effort. One worker sends at most one waveform at a time and keeps only the newest pending request. It limits the time spent on one interaction and pauses after repeated transport failures so feedback does not delay normal device writes.
The worker also tracks when a ring session had to enable a device-wide haptic engine. It hands that setting back when the session closes or the agent leaves. If the device cannot be reached, the restore remains pending and is retried later. A newer session on the same device replaces the older proof so a late close cannot disable haptics that the newer session still uses.
References: crates/…/lifecycle.rs• L586-625 crates/…/server.rs• L555-635 crates/…/server.rs• L637-1151
Overlay notices
Overlay notices are agent-owned short-lived state. The notice board publishes low-battery notices and removes them when their display time ends, so a late or reconnected overlay sees only notices that are still current. Low battery is announced once per discharge and becomes eligible again after the device charges.
Lock-key changes use a separate short-lived indicator. The agent filters them by user setting and platform support, replaces an older shown change with a newer one, and keeps the language with the displayed state. Both indicators use generation-based observation so the overlay can wait for a change without polling.
References: crates/…/notices.rs• L21-127 crates/…/notices.rs• L135-209 crates/…/lock_keys.rs• L14-89 crates/…/orchestrator.rs• L1573-1615
Process boundary
The agent exposes the Agent service over local IPC. The desktop application, overlay, and command-line tools are clients. They request status, snapshots, settings, pairing, light control, Flow status, notices, backlight and lock-key indicators, and ring actions while the agent remains the only process that owns live device access. The server maps these requests to shared runtime handles or to the orchestrator, so client requests use the same device access rules as background watchers.
The agent binds IPC during bootstrap before it starts permission prompts, device opens, or device-facing watchers. This lets a dormant macOS process hear a client demand without starting device work too early. A client declaration can request arming, while other client kinds can use IPC without requesting device-facing work.
The service publishes complete observable snapshots with generation numbers. A client supplies the last generation it received. The agent returns the next changed snapshot or the unchanged state after a hold period. Related facts publish together so a reconnecting client does not need to rebuild state from event gaps. Flow peer status and Flow pairing phase are part of the shared snapshot. Transient keyboard backlight, lock-key, and notice state use the same generation-based observation shape but have their own display lifetimes.
The server checks the protocol version before normal RPC use, and a mock agent can provide the same service shape without hardware. Flow status is part of the observable state, so local clients can follow peer reachability without owning the peer connection.
References: crates/…/startup.rs• L31-100 crates/…/startup.rs• L103-126 crates/…/server.rs• L51-104 crates/…/server.rs• L178-211 crates/…/server.rs• L494-563 crates/…/observable.rs• L36-149 crates/…/observable.rs• L205-227 crates/…/pairing.rs• L623-653
Menu-bar control
On macOS, the agent hosts the menu-bar control surface because the desktop application is on-demand. The status item opens the GUI through openlogi:// commands. Config reloads can update its icon, visibility, and language without restarting the agent. Quit first asks the GUI and overlay to leave, then sends shutdown to the lifecycle that owns device cleanup.
The menu model is built from the latest agent snapshot and configuration. It presents device state, connection type, battery or light readings, current-app profile context, Flow peers, permissions, and actions that route back through the agent. Building the model reads held state only; it does not open devices or perform writes. Device setting commands use the same agent setting path as other clients.
The menu-bar loop stays on the process main thread, while the agent core runs on a separate async thread. Both observe host activity. This keeps AppKit work on its required thread while device work remains under the core lifecycle.
References: crates/…/tray_model.rs• L1-7 crates/…/tray_model.rs• L36-71 crates/…/tray_model.rs• L93-130 crates/…/status_item.rs• L23-41 crates/…/tray.rs• L79-134 crates/…/tray.rs• L228-317 crates/…/settings.rs• L18-31
Service lifecycle
The executable follows a fixed lifecycle: bootstrap, demand gate, arming, running, and exit. Bootstrap claims the agent role, builds shared state, starts non-device action workers, and binds IPC. Arming starts permissions, inventory, capture, light observation, secure-input observation, virtual-keyboard support, Flow, and other device-facing watchers. The running loop then folds watcher events and agent-owned action requests into the orchestrator.
The startup construction keeps safe work separate from arming. Input action workers can start before device access because they do not open devices until an action needs one. State watchers and HID sessions start only after the lifecycle has decided that device work is wanted. Low-frequency watcher events merge into the lifecycle loop, while the high-rate input path goes directly from the hook or capture source to the action runtime.
On macOS, a login-started process can remain dormant when login start is disabled. It waits for GUI demand for a fixed period and exits without opening devices if no GUI asks it to arm. Linux and Windows start directly in the wanted state.
Permissions can require a replacement process. On macOS, a newly granted Input Monitoring permission takes effect after relaunch. A binary update also stops the device-facing watcher fleet before the replacement starts. Unix systems replace the image in place when possible. macOS starts a successor after the old process exits, while Windows leaves through cleanup so its normal launcher can start the new image.
Shutdown owns replacement and cleanup. Flow stops before the service releases receiver and device-I/O leases. The agent then finishes ring haptics and drains the HID++ watcher fleet before it releases the OS hook, action workers, and virtual keyboard. A normal shutdown returns lighting control to firmware; a handover keeps that control for the successor. A deliberate tray shutdown also asks the overlay to leave so a successor does not inherit a stale helper.
The startup and steady-state flow is:
flowchart TD
A[Process starts] --> B[Claim agent role]
B --> C[Build runtime and bind IPC]
C --> D{Device work wanted?}
D -->|No on macOS| E[Serve demand briefly and exit]
D -->|Yes| F[Arm permissions and helpers]
F --> G[Start inventory capture light and host watchers]
G --> H[Reconcile events and device state]
H --> M[Run configured Flow peers]
M --> I[Serve local clients and device commands]
I --> J{Exit or update?}
J -->|No| H
J -->|Yes| K[Stop Flow and finish ring haptics]
K --> L[Drain device watchers]
L --> N[Release hook action workers and keyboard]
References: crates/…/main.rs• L56-100 crates/…/main.rs• L111-174 crates/…/startup.rs• L50-126 crates/…/startup.rs• L129-179 crates/…/startup.rs• L205-241 crates/…/lifecycle.rs• L60-88 crates/…/lifecycle.rs• L90-129 crates/…/lifecycle.rs• L132-198 crates/…/lifecycle.rs• L208-265 crates/…/lifecycle.rs• L303-369 crates/…/lifecycle.rs• L696-830
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the agent as the only owner of device opens. New client features must use the IPC service.
- Keep inventory, capture, pairing, lighting, light observation, pointer precision, and device writes on one hardware context and one host I/O policy.
- When a new input source is added, connect it to the common action runtime and define its receiver ownership.
- When button or scroll workers change, preserve non-blocking input, source-scoped cancellation, press cancellation, direct fallback, deadline handling, and shutdown cleanup.
- When button diversion crosses the OS hook, publish ownership before the session's press, suppress both echoed edges, and release ownership only after the session input queue drains.
- When selected-device hook behavior changes, keep the selected physical route aligned with capture ownership so unattributed events from other mice remain native.
- When browser navigation changes, keep press-time target selection and per-direction duplicate suppression aligned across OS-hook and HID++ paths.
- When capture sessions change, keep physical-session identity, stale-event rejection, ordered completion, firmware restoration, and successor admission aligned.
- When a capture plan changes, separate hardware-target changes from dispatch-only changes. Refresh actions in place and retire hardware only when its target changes.
- When pointer-scoped dispatch changes, keep press-time target capture, exact current-target validation, shared-versus-distinct binding rules, focus checks, and stale-press cancellation aligned.
- When a setting has both user and reconnect writers, assign it one ordering policy so an older value cannot overwrite a newer choice. This includes pointer precision restores and Disable Keys policy recovery.
- When a capture target changes, keep session retirement, firmware restoration, dispatch ownership, and stale-event handling aligned.
- When a new observable fact is added, update snapshot generation with the fact so clients receive coherent state. Keep transient indicators, notices, and lock-key changes on their own observation lifetime when they are not part of the durable snapshot.
- When Flow pairing changes, keep the temporary pairing endpoint separate from the trusted Flow endpoint, require mutual confirmation before saving a peer, and reload the saved trust into Flow.
- When notices or lock-key indicators change, keep user settings, platform filtering, generation changes, expiry, and overlay observation aligned.
- When Secure Event Input reporting changes, keep macOS polling, settled transitions, client state, and lost-watcher fallback aligned.
- When standalone light observation changes, keep watched-light publication, route checks, external-change retention, and write-failure rollback aligned.
- When backlight or Disable Keys writes change, keep request admission, per-keyboard ordering, native completion, client cancellation, and settings-change publication aligned.
- When Actions Ring haptics change, keep session ownership, latest-wins playback, restore proof, retry timing, and shutdown handoff aligned.
- When virtual keyboard support changes, keep status publication, loss detection, action-worker order, and final release aligned.
- When startup, replacement, or shutdown changes, review the demand gate, watcher fleet, overlay ownership, virtual keyboard, device cleanup, haptic restore, and RGB control release together.
- When Input Monitoring or executable replacement changes, preserve the platform-specific successor handoff and ensure the old fleet is settled before the new one starts.
- When a device setting can be lost on reconnect or wake, include it in the ordered re-apply path and confirmation behavior.
- When inventory scheduling changes, preserve the distinction between a completed empty scan, a failed scan, bounded repair, delayed settings confirmation, and low-frequency recovery.
- When Flow changes, keep configuration, inventory identity, peer trust, edge detection, handoff timing, device switching, cursor placement, and observable peer status aligned.
- When Flow starts or stops, keep its receiver access and device-I/O leases ordered with capture, pairing, host switching, and shutdown.
- When receiver pairing changes, keep session admission, exclusive receiver ownership, session-tagged events, terminal cleanup, and published phases aligned.
- When device writes change, resolve the current channel after the per-transport turn and keep the response timeout separate from queue wait.
- When free-spin detection changes, preserve the distinction between natural coasting, a hand-stopped wheel, settling reports, and a new push.
- When the menu model changes, keep its snapshot-only decisions separate from device reads and route its setting actions through the agent server.
- When linked host switching changes, keep session stop, firmware restore, newest-request handling, departure waiting, and successor admission aligned.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A second agent starts while another owns the service | Processes could compete for IPC, input capture, or device routes | The executable claims the agent role before runtime work begins. |
| macOS starts the agent without GUI demand | An unwanted login start could open devices | The demand gate binds IPC first and exits without arming after its deadline. |
| Bootstrap starts a device watcher before demand is accepted | A dormant login agent could prompt or open hardware | Startup separates safe construction from arming and keeps device-facing watchers out of bootstrap. |
| The agent starts during sleep or DarkWake | Device access could run before the host is ready | The activity gate starts closed and opens only for a usable host session. |
| Inventory fails after a good scan | Clients could see false device removal | The watcher keeps the last good inventory and reports an empty result only after a completed scan. |
| Repair or settings confirmation fails repeatedly | Volatile settings could remain unapplied, or a confirmation request could be lost | Fast retries are bounded, while the request remains pending for the low-frequency recovery scan. |
| A receiver slot is reused by another physical device | Pending writes or confirmation work could affect the replacement | Stable device identity scopes lifecycle state and starts a fresh re-apply run for a replacement. |
| Pairing overlaps with capture | Receiver replies or firmware control could conflict | Pairing uses exclusive receiver access and capture retires without rejecting already-owned input. |
| A pairing terminal event arrives twice or belongs to an older session | A replacement session could be ended or its result could be replaced | Session identities accept terminal events only for the live session and consume the session once. |
| Pairing cancellation returns before receiver cleanup | Capture could resume while the pairing watcher still owns the receiver | Cancellation waits for the session completion signal after the receiver lease is released. |
| A Flow pairing attempt saves one side before mutual confirmation | A peer could enter trusted Flow without a completed user check | The agent persists the peer only after both sides confirm the shared code. |
| A Flow pairing response arrives after its attempt ended | Stale network work could change the current pairing result | Attempt events carry an attempt identity and ended stages refuse later transitions. |
| A capture task ends unexpectedly | A device could stay native or remain unavailable | Ordered completion reports the end, retains any firmware restore, and retries re-arm after a delay. |
| A stale capture event arrives after replacement | An old action could run under a new device plan | Session epochs accept only the current or still-draining owner. |
| A directly diverted button also reaches the OS hook | One physical press could run its action twice | Session-scoped diversion ownership makes the hook suppress the echoed press and release. |
| An unattributed OS-hook event comes from a different mouse while the selected mouse diverts that control | The other mouse could run the selected mouse's binding | The hook compares the selected physical route with capture ownership and passes the event through when the source is not the selected route. |
| A capture plan changes during a held action | A held action could use stale bindings or a new physical owner | Dispatch-only changes cancel affected lifecycles in place. Target changes freeze the old plan until ordered teardown completes. |
| A browser navigation action arrives through both input paths | One press could navigate twice | The action runtime captures the target at press time and debounces each direction across sources. |
| A reconnect write races a newer user choice | The device could keep an old report rate, pointer speed, Fn-lock, or Disable Keys value | Per-setting write order lets a newer request supersede older pending work or schedule accepted-policy recovery. |
| A device write waits behind another slot on the same transport | Its channel could be retired before the write starts, or its response budget could expire in the queue | The request takes the transport turn before resolving the channel and starts its bounded I/O timeout after the wait. |
| A delayed setting reaches a replacement device on the same route | The wrong device could receive a saved choice | Bound operations confirm the current unit identity before writing. |
| A Disable Keys requester cancels after native I/O starts | A successor could write while the first report is still in flight | The worker retains the setting and transport turns through native completion, then schedules recovery when ownership was not confirmed. |
| A button or scroll queue is full | Input could block or consumed device input could disappear | Producers submit without waiting. Button state invalidates on overflow, and diverted scroll returns direct output. |
| A button worker stops with active presses | The foreground application could receive incomplete press state | Shutdown and source cancellation emit end events for active presses. |
| A long-press deadline is handled after stale queued input | An action could fire for an invalid press | The worker settles queued state and checks generation before firing due presses. |
| A pointer-scoped action runs after the pointer moves | An old binding could affect a new window or surface | The action worker requires the exact captured target to remain current, then applies the shared-versus-distinct focus rule for actions that need focus. |
| A capture target changes while firmware controls remain diverted | Native device behavior could remain diverted or stale input could run | Teardown keeps the old session authoritative until restoration completes. |
| Secure Event Input starts for one sample | Clients could show a false or distracting warning | The watcher waits for a second consecutive “on” sample before reporting it. |
| A light write fails after an external change was hidden for the write | A reconnect or reload could lose the user's physical setting | The orchestrator restores the claimed change unless a newer change or saved value replaced it. |
| Haptic requests saturate the receiver | Feedback retries could delay normal device writes | The haptic worker uses latest-wins queuing, bounded attempts, and a failure cooldown. |
| A virtual keyboard is removed before action workers stop | Held synthesized keys could remain logically pressed or fail to release | Shutdown stops input workers before the virtual keyboard releases its device. |
| A client and agent use different IPC contracts | Requests or snapshots cannot be exchanged safely | The client checks the protocol version before normal RPC use. |
| Flow is enabled without a usable peer or machine identity | The agent cannot start a handoff generation | The controller publishes dormant peer state and retries a failed start after a delay. |
| A cursor crossing arrives while Flow changes generations | A crossing could use stale peer or display state | The hook wakes only the current generation, and the next motion wakes its replacement. |
| A handoff names an unknown or already local device | The receiver could switch the wrong device or disrupt a local device | The receiver matches configured physical identities and rejects invalid requests. |
| A handoff window expires during device switching | The peer could report that only part of the transfer completed | The sender starts writes before the deadline and the receiver reports arrived, partial, or timeout outcomes. |
| Flow stops while it holds receiver access | Capture or pairing could compete with a live peer transfer | Shutdown stops Flow before releasing the agent's device and receiver resources. |
| A linked host switch is requested while its session or restore is active | A successor could arm over old firmware state or an older host request could win | The manager drains sessions, waits for restore, keeps the newest request, and checks link publication before transition. |
| A keyboard is leaving while a host-switch restore is pending | The restore could target a departing device or block a new session | The manager waits for link departure or a bounded timeout, then retries only against the current route. |
| A replacement is started before old device work settles | Both processes could touch the same device or lock | The lifecycle waits for watcher teardown and uses a platform-specific handoff before exit. |
Key files
| File | Why to read it |
|---|---|
| crates/…/main.rs | Shows the single-instance claim, platform split, and process entry path. |
| crates/…/Cargo.toml | Shows the production executable and the hardware-free mock service boundary. |
| crates/…/startup.rs | Shows how the executable builds the core, starts IPC, and arms watcher fleets. |
| crates/…/lifecycle.rs | Shows bootstrap, demand gating, arming, event coordination, replacement, and exit boundaries. |
| crates/…/relaunch.rs | Shows how updated binaries and late Input Monitoring grants hand off to a successor on each platform. |
| crates/…/server.rs | Shows the local RPC service, client demand, Actions Ring haptics, and boundary between client requests and agent-owned device work. |
| crates/…/settings.rs | Shows how menu-bar and agent clients use the common setting reload path. |
| crates/…/pairing.rs | Shows receiver pairing admission, exclusive receiver ownership, IPC updates, and cleanup. |
| crates/…/session.rs | Shows the receiver-pairing state model and terminal resource release. |
| crates/…/status_item.rs | Shows the macOS menu-bar status-item boundary. |
| crates/…/tray.rs | Shows the macOS menu-bar loop, live menu updates, and graceful quit handoff. |
| crates/…/tray_model.rs | Shows the snapshot-driven menu model and the product state exposed by the menu-bar surface. |
| crates/…/orchestrator.rs | Shows how configuration, inventory, context, device settings, capture plans, pointer speed, notices, and light state become shared runtime state. |
| crates/…/settings.rs | Shows the agent-owned setting flow from device confirmation through config save and reload. |
| crates/…/runtime.rs | Shows the shared action path, action execution, press-time target handling, agent-owned requests, and shutdown behavior. |
| crates/…/hook.rs | Shows OS-hook admission, selected-route filtering, gesture and key handling, and fail-open event policy. |
| crates/…/pointer.rs | Shows pointer-target capture, stale-target rejection, and the focus rules for pointer-selected actions. |
| crates/…/free_spin.rs | Shows the high-level wheel phase model for ratchet motion, free spin, and hand stops. |
| crates/…/flow.rs | Shows the Flow boundary between orchestration and cross-device handoff. |
| crates/…/controller.rs | Shows when Flow starts, replaces a generation, publishes dormant peer state, and stops. |
| crates/…/pairing.rs | Shows the temporary Flow pairing endpoint, mutual confirmation, peer persistence, and observable pairing phase. |
| crates/…/stage.rs | Shows the bounded pairing-attempt stages and their allowed transitions. |
| crates/…/runtime.rs | Shows peer sessions, discovery, the pointer thread, and generation shutdown. |
| crates/…/devices.rs | Shows how configured physical devices are matched to inventory and described to peers. |
| crates/…/handoff.rs | Shows receiver acceptance, sender timing, cancellation, replay, and partial-transfer outcomes. |
| crates/…/edge.rs | Shows how display edges become Flow crossing inputs. |
| crates/…/pointer.rs | Shows how cursor motion wakes edge detection and how a received handoff places the cursor. |
| crates/…/identity.rs | Shows the persistent machine identity used to trust peer connections. |
| crates/…/host_switch.rs | Shows linked keyboard and pointing-device sessions, transition ordering, restore recovery, and departure handling. |
| crates/…/devices.rs | Shows stable device identity, route changes, host links, and bounded settings confirmation plans. |
| crates/…/hardware.rs | Shows the authoritative device channel, transport request turns, host-I/O gate, and ordered background writes. |
| crates/…/disable_keys.rs | Shows native completion ownership and recovery for Disable Keys writes. |
| crates/…/write_order.rs | Shows how user requests, saved policies, retries, and per-route write order share intent state. |
| crates/…/context.rs | Shows the shared backend identity and device-I/O boundary used by inventory, writes, pairing, and lights. |
| crates/…/observable.rs | Shows the coherent snapshot and generation-based client observation model. |
| crates/…/capture_plan.rs | Shows the separation between per-device hardware ownership and hot-refreshable action dispatch. |
| crates/…/capture_session.rs | Shows capture ownership, teardown, ordered completion, and firmware recovery. |
| crates/…/gesture.rs | Shows one capture session per published device plan, session recovery, and diversion handoff. |
| crates/…/dispatch.rs | Shows how captured device input becomes actions or scroll output under a session plan. |
| crates/…/keyboard.rs | Shows the bound-key capture session, in-place per-app key diversion, and its shared action path. |
| crates/…/diverted.rs | Shows how direct-device OS-hook echoes are tied to capture-session ownership. |
| crates/…/button.rs | Shows the source-independent press lifecycle and cancellation contract. |
| crates/…/worker.rs | Shows deadline handling, generation invalidation, and balanced terminal events. |
| crates/…/worker.rs | Shows non-blocking scroll admission, smoothing, direct fallback, and source cancellation. |
| crates/…/pointer_speed.rs | Shows the agent-owned precision mode and ordering of pointer-speed writes. |
| crates/…/inventory.rs | Shows event-first inventory reconciliation, recovery scans, wake handling, channel replacement, and indicator event forwarding. |
| crates/…/schedule.rs | Shows the bounded repair, delayed confirmation, and low-frequency recovery schedule. |
| crates/…/secure_input.rs | Shows macOS Secure Event Input sampling and settled status changes. |
| crates/…/light.rs | Shows how the agent watches standalone lights and handles link loss or replacement. |
| crates/…/lights.rs | Shows how external light changes remain effective across writes, reloads, and reconnects. |