Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 27 additions & 15 deletions crates/openlogi-agent-core/src/watchers/capture_session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,18 @@ pub(super) enum CompletionAction {
Remove { unexpected: bool },
}

enum SessionPhase {
Active(oneshot::Sender<()>),
enum SessionPhase<Stop> {
Active(oneshot::Sender<Stop>),
Draining,
}

/// One capture epoch, including its hardware identity, dispatch state and
/// acknowledged teardown phase.
pub(super) struct CaptureSession<Target, Dispatch> {
pub(super) struct CaptureSession<Target, Dispatch, Stop = ()> {
id: HidppSessionId,
target: Target,
dispatch: Dispatch,
phase: SessionPhase,
phase: SessionPhase<Stop>,
}

/// Firmware restoration and restart pacing retained after a capture task has
Expand Down Expand Up @@ -82,13 +82,13 @@ impl<Restore> CaptureRecovery<Restore> {

/// One manager-owned hardware slot. A session remains in `Running` while it
/// drains; only its matching ordered completion moves the slot to recovery.
pub(super) enum CaptureSlot<Target, Dispatch, Restore> {
Running(CaptureSession<Target, Dispatch>),
pub(super) enum CaptureSlot<Target, Dispatch, Restore, Stop = ()> {
Running(CaptureSession<Target, Dispatch, Stop>),
Recovering(CaptureRecovery<Restore>),
}

impl<Target, Dispatch, Restore> CaptureSlot<Target, Dispatch, Restore> {
pub(super) fn running(session: CaptureSession<Target, Dispatch>) -> Self {
impl<Target, Dispatch, Restore, Stop> CaptureSlot<Target, Dispatch, Restore, Stop> {
pub(super) fn running(session: CaptureSession<Target, Dispatch, Stop>) -> Self {
Self::Running(session)
}

Expand All @@ -102,14 +102,14 @@ impl<Target, Dispatch, Restore> CaptureSlot<Target, Dispatch, Restore> {
})
}

pub(super) fn session(&self) -> Option<&CaptureSession<Target, Dispatch>> {
pub(super) fn session(&self) -> Option<&CaptureSession<Target, Dispatch, Stop>> {
let Self::Running(session) = self else {
return None;
};
Some(session)
}

pub(super) fn session_mut(&mut self) -> Option<&mut CaptureSession<Target, Dispatch>> {
pub(super) fn session_mut(&mut self) -> Option<&mut CaptureSession<Target, Dispatch, Stop>> {
let Self::Running(session) = self else {
return None;
};
Expand Down Expand Up @@ -157,13 +157,13 @@ impl<Target, Dispatch, Restore> CaptureSlot<Target, Dispatch, Restore> {
}
}

impl<Target, Dispatch> CaptureSession<Target, Dispatch> {
impl<Target, Dispatch, Stop> CaptureSession<Target, Dispatch, Stop> {
/// Begin tracking an active capture task.
pub(super) fn active(
id: HidppSessionId,
target: Target,
dispatch: Dispatch,
stop: oneshot::Sender<()>,
stop: oneshot::Sender<Stop>,
) -> Self {
Self {
id,
Expand Down Expand Up @@ -219,11 +219,15 @@ impl<Target, Dispatch> CaptureSession<Target, Dispatch> {
}
}

impl<Target: PartialEq, Dispatch: Clone + PartialEq> CaptureSession<Target, Dispatch> {
impl<Target: PartialEq, Dispatch: Clone + PartialEq, Stop> CaptureSession<Target, Dispatch, Stop> {
/// Reconcile against the latest wanted target and dispatch state. A target
/// change begins teardown exactly once; dispatch-only changes hot-refresh
/// the plan while preserving the hardware epoch.
pub(super) fn reconcile(&mut self, wanted: Option<(&Target, &Dispatch)>) -> ReconcileAction {
pub(super) fn reconcile_with(
&mut self,
wanted: Option<(&Target, &Dispatch)>,
stop_for_change: impl FnOnce(&Target, Option<&Target>) -> Stop,
) -> ReconcileAction {
if !self.is_active() {
return ReconcileAction::None;
}
Expand All @@ -236,15 +240,23 @@ impl<Target: PartialEq, Dispatch: Clone + PartialEq> CaptureSession<Target, Disp
self.dispatch.clone_from(dispatch);
return ReconcileAction::DispatchChanged;
}
let stop_command = stop_for_change(&self.target, wanted.map(|(target, _)| target));
let SessionPhase::Active(stop) = std::mem::replace(&mut self.phase, SessionPhase::Draining)
else {
return ReconcileAction::None;
};
let _ = stop.send(());
let _ = stop.send(stop_command);
ReconcileAction::Retiring
}
}

impl<Target: PartialEq, Dispatch: Clone + PartialEq> CaptureSession<Target, Dispatch> {
/// Reconcile a session whose teardown command carries no additional intent.
pub(super) fn reconcile(&mut self, wanted: Option<(&Target, &Dispatch)>) -> ReconcileAction {
self.reconcile_with(wanted, |_, _| ())
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
39 changes: 31 additions & 8 deletions crates/openlogi-agent-core/src/watchers/gesture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ use std::time::Duration;
use openlogi_core::device_order::PhysicalDeviceKey;
use openlogi_core::scroll::ScrollDelta;
use openlogi_hid::{
CaptureChannel, CaptureSessionOutcome, CapturedInput, DeviceIoGate, PendingCaptureRestore,
run_capture_session_with_registry_spec,
CaptureChannel, CaptureSessionOutcome, CaptureSessionStop, CapturedInput, DeviceIoGate,
PendingCaptureRestore, run_capture_session_with_registry_spec,
};
use tokio::sync::{mpsc, oneshot, watch};
use tokio::time::Instant;
Expand Down Expand Up @@ -132,8 +132,8 @@ pub fn spawn(
WatcherHandle::new(shutdown_tx, shutdown_done_rx)
}

type RunningSession = CaptureSession<CaptureTarget, DispatchPlan>;
type GestureSlot = CaptureSlot<CaptureTarget, DispatchPlan, PendingRestore>;
type RunningSession = CaptureSession<CaptureTarget, DispatchPlan, CaptureSessionStop>;
type GestureSlot = CaptureSlot<CaptureTarget, DispatchPlan, PendingRestore, CaptureSessionStop>;

struct CapturedEvent {
physical_key: PhysicalDeviceKey,
Expand Down Expand Up @@ -245,13 +245,26 @@ fn reconcile_session(
wanted: Option<(&CaptureTarget, &DispatchPlan)>,
dispatcher: &mut InputDispatcher,
) {
if session.reconcile(wanted) == ReconcileAction::DispatchChanged {
if session.reconcile_with(wanted, stop_for_target_change) == ReconcileAction::DispatchChanged {
dispatcher.cancel_session(session.id());
let config_key = session.dispatch().config_key.clone();
session.rekey(&config_key);
}
}

fn stop_for_target_change(
current: &CaptureTarget,
wanted: Option<&CaptureTarget>,
) -> CaptureSessionStop {
wanted.map_or(CaptureSessionStop::Shutdown, |next| {
if next.route == current.route {
CaptureSessionStop::Shutdown
} else {
CaptureSessionStop::Handoff(next.route.clone())
}
})
}

/// Reconcile one tracked slot directly against the latest publication. Input
/// calls this before dispatch so an event cannot slip between publishing a hot
/// action update and processing its notification.
Expand Down Expand Up @@ -307,6 +320,7 @@ fn acquire_session_lease(
async fn retry_pending_restores(
slots: &mut HashMap<PhysicalDeviceKey, GestureSlot>,
registry: &openlogi_hid::ChannelRegistry,
wanted: &[DeviceCapturePlan],
now: Instant,
) {
let keys: Vec<_> = slots
Expand All @@ -326,7 +340,16 @@ async fn retry_pending_restores(
slots.insert(key, GestureSlot::Recovering(recovery));
continue;
};
if let CaptureSessionOutcome::RestorePending(token) = pending.token.retry(registry).await {
let outcome = match wanted.iter().find(|plan| plan.target.physical_key == key) {
Some(plan) => {
pending
.token
.retry_via(plan.target.route.clone(), registry)
.await
}
None => pending.token.retry(registry).await,
};
if let CaptureSessionOutcome::RestorePending(token) = outcome {
recovery.pending_restore = Some(PendingRestore {
token,
retry_at: Instant::now() + RETRY_DELAY,
Expand Down Expand Up @@ -442,7 +465,7 @@ impl GestureManagerState {
None
};
if restore_lease.is_some() {
retry_pending_restores(&mut self.slots, &channels.registry, now).await;
retry_pending_restores(&mut self.slots, &channels.registry, wanted, now).await;
}

for plan in wanted {
Expand Down Expand Up @@ -583,7 +606,7 @@ async fn drain_for_shutdown(
std::future::pending::<()>().await;
}
if let Some(_lease) = acquire_session_lease(receiver_access, &mut state.lease) {
retry_pending_restores(&mut state.slots, &channels.registry, Instant::now()).await;
retry_pending_restores(&mut state.slots, &channels.registry, &[], Instant::now()).await;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Shutdown retries obsolete route

If a device moves from route A to B and then back to A or onward to C while the first handoff is still draining, the restore token retains route B because draining sessions ignore later plan changes. This shutdown path passes an empty plan list, so it repeatedly retries obsolete route B instead of the latest reachable route. Confirmed replacement can remain blocked indefinitely, while terminal shutdown can time out and leave the controls diverted.

Knowledge Base Used:

Fix in Codex Fix in Claude Code

}
if state.has_pending_restores() {
tokio::time::sleep(RETRY_DELAY).await;
Expand Down
85 changes: 72 additions & 13 deletions crates/openlogi-agent-core/src/watchers/gesture/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ fn live_session_with_epoch(epoch: u64) -> RunningSession {

fn draining_session_with_epoch(epoch: u64) -> RunningSession {
let mut session = live_session_with_epoch(epoch);
assert_eq!(session.reconcile(None), ReconcileAction::Retiring);
assert_eq!(
session.reconcile_with(None, stop_for_target_change),
ReconcileAction::Retiring
);
session
}

Expand Down Expand Up @@ -297,7 +300,10 @@ async fn exclusive_request_retires_capture_without_rejecting_owned_input() {
assert!(wanted_sessions(*requests.borrow(), &plans).is_empty());

let mut session = live_session_with_epoch(7);
assert_eq!(session.reconcile(None), ReconcileAction::Retiring);
assert_eq!(
session.reconcile_with(None, stop_for_target_change),
ReconcileAction::Retiring
);
assert!(!session.is_active());
assert!(
dispatch_context_for(&session_id(7), Some(&session)).is_some(),
Expand Down Expand Up @@ -331,7 +337,10 @@ fn an_active_session_refreshes_bindings_without_rearming_hardware() {
assert_eq!(session.target(), &new_plan.target);

assert_eq!(
session.reconcile(Some((&new_plan.target, &new_plan.dispatch))),
session.reconcile_with(
Some((&new_plan.target, &new_plan.dispatch)),
stop_for_target_change,
),
ReconcileAction::DispatchChanged,
"a hot plan refresh must cancel input lifecycles admitted under the old action map"
);
Expand Down Expand Up @@ -370,10 +379,13 @@ fn side_gesture_transition_keeps_the_retiring_plan_until_native_restore() {
.clear();
assert_ne!(session.target(), &published_without_hook.target);
assert_eq!(
session.reconcile(Some((
&published_without_hook.target,
&published_without_hook.dispatch,
))),
session.reconcile_with(
Some((
&published_without_hook.target,
&published_without_hook.dispatch,
)),
stop_for_target_change,
),
ReconcileAction::Retiring
);
assert!(!session.is_active());
Expand Down Expand Up @@ -418,6 +430,35 @@ fn capture_target_changes_schedule_the_old_session_for_retirement() {
);
}

#[test]
fn receiver_route_change_requests_a_firmware_handoff() {
let old_plan = plan();
let mut new_plan = old_plan.clone();
let successor_route = DeviceRoute::Bolt {
receiver_uid: "receiver-b".to_owned(),
slot: 2,
};
new_plan.target.route.clone_from(&successor_route);
let (stop, mut stopped) = oneshot::channel();
let mut session =
CaptureSession::active(session_id(7), old_plan.target, old_plan.dispatch, stop);

assert_eq!(
session.reconcile_with(
Some((&new_plan.target, &new_plan.dispatch)),
stop_for_target_change,
),
ReconcileAction::Retiring
);
assert_eq!(
stopped
.try_recv()
.expect("route change should stop the active session"),
CaptureSessionStop::Handoff(successor_route),
"teardown must restore through the receiver the mouse moved to"
);
}

#[test]
fn config_key_adoption_hot_refreshes_the_same_physical_capture_slot() {
let old_plan = plan();
Expand All @@ -435,7 +476,10 @@ fn config_key_adoption_hot_refreshes_the_same_physical_capture_slot() {
.get(&physical_key)
.map(|plan| (&plan.target, &plan.dispatch));

assert_eq!(running.reconcile(desired), ReconcileAction::DispatchChanged);
assert_eq!(
running.reconcile_with(desired, stop_for_target_change),
ReconcileAction::DispatchChanged
);
running.rekey(&wanted[&physical_key].dispatch.config_key);
assert!(running.is_active());
assert_eq!(running.id().device_key(), "unit:00000001");
Expand Down Expand Up @@ -480,7 +524,10 @@ fn active_session_adopts_action_only_plan_changes_without_rearming() {
);
assert_eq!(first.target, rebound.target);
assert_eq!(
session.reconcile(Some((&rebound.target, &rebound.dispatch))),
session.reconcile_with(
Some((&rebound.target, &rebound.dispatch)),
stop_for_target_change,
),
ReconcileAction::DispatchChanged
);
assert_eq!(
Expand Down Expand Up @@ -521,7 +568,10 @@ fn active_session_adopts_gesture_and_per_app_dispatch_changes() {
);
assert_eq!(first.target, gestured.target);
assert_eq!(
session.reconcile(Some((&gestured.target, &gestured.dispatch))),
session.reconcile_with(
Some((&gestured.target, &gestured.dispatch)),
stop_for_target_change,
),
ReconcileAction::DispatchChanged
);
assert_eq!(
Expand Down Expand Up @@ -565,7 +615,10 @@ fn active_session_adopts_gesture_and_per_app_dispatch_changes() {
);
assert_eq!(base.target, per_app.target);
assert_eq!(
session.reconcile(Some((&per_app.target, &per_app.dispatch))),
session.reconcile_with(
Some((&per_app.target, &per_app.dispatch)),
stop_for_target_change,
),
ReconcileAction::DispatchChanged
);
assert_eq!(
Expand Down Expand Up @@ -612,7 +665,10 @@ fn wheel_configuration_changes_refresh_without_rearming_hardware() {
"both custom bindings require the same HID++ diversion"
);
assert_eq!(
session.reconcile(Some((&rebound.target, &rebound.dispatch))),
session.reconcile_with(
Some((&rebound.target, &rebound.dispatch)),
stop_for_target_change,
),
ReconcileAction::DispatchChanged,
"dispatch-only binding changes must not cycle firmware diversion"
);
Expand All @@ -630,7 +686,10 @@ fn wheel_configuration_changes_refresh_without_rearming_hardware() {
);
assert_eq!(rebound.target, rescaled.target);
assert_eq!(
session.reconcile(Some((&rescaled.target, &rescaled.dispatch))),
session.reconcile_with(
Some((&rescaled.target, &rescaled.dispatch)),
stop_for_target_change,
),
ReconcileAction::DispatchChanged,
"an already-diverted wheel needs a state reset, not a hardware restart"
);
Expand Down
5 changes: 3 additions & 2 deletions crates/openlogi-device/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,9 @@ pub use pairing::{
PasskeyMethod, ReceiverFamily, ReceiverSelector, list_pairing_receivers, run_pairing, unpair,
};
pub use session::gesture::{
CaptureChannel, CaptureSessionFailure, CaptureSessionOutcome, CapturedInput, GestureError,
PendingCaptureRestore, run_capture_session, run_capture_session_with_registry_spec,
CaptureChannel, CaptureSessionFailure, CaptureSessionOutcome, CaptureSessionStop,
CapturedInput, GestureError, PendingCaptureRestore, run_capture_session,
run_capture_session_with_registry_spec,
};
pub use session::host_switch::{
HostSwitchError, HostSwitchRestoreOutcome, HostSwitchSessionFailure, HostSwitchSessionOutcome,
Expand Down
Loading
Loading