flexitracker 0.4.1__tar.gz → 0.5.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. {flexitracker-0.4.1 → flexitracker-0.5.1}/.gitignore +4 -0
  2. {flexitracker-0.4.1 → flexitracker-0.5.1}/PKG-INFO +2 -2
  3. {flexitracker-0.4.1 → flexitracker-0.5.1}/src/flexitracker/cli.py +24 -2
  4. flexitracker-0.5.1/src/flexitracker/idle.py +209 -0
  5. {flexitracker-0.4.1 → flexitracker-0.5.1}/src/flexitracker/state_machine.py +93 -8
  6. flexitracker-0.5.1/tests/test_idle.py +46 -0
  7. flexitracker-0.5.1/tests/vectors/25-heartbeat-does-not-clamp-idle-backdate.json +14 -0
  8. flexitracker-0.4.1/src/flexitracker/idle.py +0 -97
  9. flexitracker-0.4.1/tests/test_idle.py +0 -9
  10. {flexitracker-0.4.1 → flexitracker-0.5.1}/LICENSE +0 -0
  11. {flexitracker-0.4.1 → flexitracker-0.5.1}/README.md +0 -0
  12. {flexitracker-0.4.1 → flexitracker-0.5.1}/install/README.md +0 -0
  13. {flexitracker-0.4.1 → flexitracker-0.5.1}/install/flexitracker.service +0 -0
  14. {flexitracker-0.4.1 → flexitracker-0.5.1}/pyinstaller_entry.py +0 -0
  15. {flexitracker-0.4.1 → flexitracker-0.5.1}/pyproject.toml +0 -0
  16. {flexitracker-0.4.1 → flexitracker-0.5.1}/src/flexitracker/__init__.py +0 -0
  17. {flexitracker-0.4.1 → flexitracker-0.5.1}/src/flexitracker/__main__.py +0 -0
  18. {flexitracker-0.4.1 → flexitracker-0.5.1}/src/flexitracker/_backend.py +0 -0
  19. {flexitracker-0.4.1 → flexitracker-0.5.1}/src/flexitracker/config.py +0 -0
  20. {flexitracker-0.4.1 → flexitracker-0.5.1}/src/flexitracker/core.py +0 -0
  21. {flexitracker-0.4.1 → flexitracker-0.5.1}/src/flexitracker/logging_setup.py +0 -0
  22. {flexitracker-0.4.1 → flexitracker-0.5.1}/src/flexitracker/login.py +0 -0
  23. {flexitracker-0.4.1 → flexitracker-0.5.1}/src/flexitracker/outbox.py +0 -0
  24. {flexitracker-0.4.1 → flexitracker-0.5.1}/src/flexitracker/sender.py +0 -0
  25. {flexitracker-0.4.1 → flexitracker-0.5.1}/src/flexitracker/version.py +0 -0
  26. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/test_cli.py +0 -0
  27. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/test_config.py +0 -0
  28. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/test_conformance.py +0 -0
  29. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/test_logging_setup.py +0 -0
  30. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/test_login.py +0 -0
  31. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/test_outbox.py +0 -0
  32. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/test_sender_body.py +0 -0
  33. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/01-activation-debounced-backdated.json +0 -0
  34. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/02-idle-backdated-to-last-input.json +0 -0
  35. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/03-short-break-absorbed.json +0 -0
  36. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/04-brief-activity-debounced.json +0 -0
  37. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/05-sustained-return-backdated.json +0 -0
  38. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/06-heartbeats-while-active.json +0 -0
  39. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/07-recover-after-sudden-shutdown.json +0 -0
  40. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/08-locked-session-goes-idle.json +0 -0
  41. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/09-recover-anchors-later-evidence.json +0 -0
  42. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/10-suspend-longer-closes-span.json +0 -0
  43. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/11-suspend-with-immediate-wake.json +0 -0
  44. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/12-suspend-shorter-absorbed.json +0 -0
  45. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/13-backwards-clock-watermark.json +0 -0
  46. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/14-small-forward-clock-absorbed.json +0 -0
  47. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/15-recover-from-active-matches-loop.json +0 -0
  48. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/16-explicit-close-no-double-close.json +0 -0
  49. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/17-freshness-independent-of-poll.json +0 -0
  50. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/18-short-reading-pause.json +0 -0
  51. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/19-presence-must-be-sustained.json +0 -0
  52. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/20-gap-kills-pending-return.json +0 -0
  53. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/21-idle-backdating-exact.json +0 -0
  54. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/22-min-inactivity-exact-boundary.json +0 -0
  55. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/23-large-timestamps.json +0 -0
  56. {flexitracker-0.4.1 → flexitracker-0.5.1}/tests/vectors/24-all-kinds-lowercase.json +0 -0
  57. {flexitracker-0.4.1 → flexitracker-0.5.1}/uv.lock +0 -0
@@ -21,3 +21,7 @@ daemon-py/build/
21
21
 
22
22
  # Personal activity export (migrated into PROD, not for the repo)
23
23
  /events.txt
24
+
25
+ # Downloaded daemon logs/config from a real machine (contains a live access
26
+ # key) -- used to diagnose an incident, never for the repo.
27
+ /logs/
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: flexitracker
3
- Version: 0.4.1
3
+ Version: 0.5.1
4
4
  Summary: FlexiTracker activity daemon — pure-Python.
5
5
  Project-URL: Homepage, https://github.com/jvuori/flexitracker
6
6
  Project-URL: Source, https://github.com/jvuori/flexitracker
@@ -282,6 +282,28 @@ def run(argv: list) -> int:
282
282
  return 1
283
283
 
284
284
 
285
+ # platform_source() can transiently fail right after login/resume-from-suspend,
286
+ # before the display server has finished (re)initializing. Observed on this
287
+ # machine's own systemd unit: "cannot open X display" firing right at session
288
+ # start, needing 1-2 of systemd's own 10s-spaced restarts to clear. Retrying
289
+ # in-process avoids relying on that external restart at all, and avoids
290
+ # burning through systemd's default restart-burst limit on a bad day.
291
+ IDLE_SOURCE_MAX_WAIT_S = 30.0
292
+ IDLE_SOURCE_RETRY_S = 2.0
293
+
294
+
295
+ def _acquire_idle_source(max_wait_s: float = IDLE_SOURCE_MAX_WAIT_S, retry_s: float = IDLE_SOURCE_RETRY_S):
296
+ deadline = time.monotonic() + max_wait_s
297
+ while True:
298
+ try:
299
+ return platform_source()
300
+ except OSError as e:
301
+ if time.monotonic() >= deadline:
302
+ raise
303
+ logger.warning("idle source not ready yet (%s); retrying in %.0fs", e, retry_s)
304
+ time.sleep(retry_s)
305
+
306
+
285
307
  def _run_daemon(args: Args, cfg: Config, config_path: Path, machine: dict) -> int:
286
308
  # Refresh thresholds; fall back to cached/defaults offline.
287
309
  try:
@@ -312,7 +334,7 @@ def _run_daemon(args: Args, cfg: Config, config_path: Path, machine: dict) -> in
312
334
  flush(cfg, ob)
313
335
 
314
336
  try:
315
- source = platform_source()
337
+ source = _acquire_idle_source()
316
338
  except OSError as e:
317
339
  logger.error("idle source: %s", e)
318
340
  return 1
@@ -320,7 +342,7 @@ def _run_daemon(args: Args, cfg: Config, config_path: Path, machine: dict) -> in
320
342
  last_mono: Optional[float] = None
321
343
  while True:
322
344
  s: Sample = source.sample()
323
- logger.debug("sample idle_ms=%s locked=%s", s.idle_ms, s.locked)
345
+ logger.debug("sample now=%d idle_ms=%s locked=%s", now_ms(), s.idle_ms, s.locked)
324
346
  mono_now = time.monotonic()
325
347
  mono_elapsed_ms = None if last_mono is None else int((mono_now - last_mono) * 1000)
326
348
  last_mono = mono_now
@@ -0,0 +1,209 @@
1
+ """Idle-time and session-lock detection — mirror of `idle.rs`, via ctypes.
2
+
3
+ No input content is ever captured — only "how long since any input" and whether
4
+ the session is locked. Platform sources are selected at runtime; a simulated
5
+ source drives scripted runs and tests. Using ctypes (stdlib) means no compiled
6
+ extension and so no C toolchain at install time.
7
+
8
+ Lock detection matters independently of idle_ms: a locked session is an
9
+ authoritative "the user is not present" signal that OS idle-time counters can
10
+ get wrong around suspend/resume (observed: a corporate laptop's idle-time API
11
+ underreporting elapsed time across a sleep/wake cycle kept `idle_ms` looking
12
+ fresh for hours). It is best-effort — any failure to query it (missing
13
+ `loginctl`/logind on Linux, an unexpected WTS response on Windows) falls back
14
+ to `locked=False`, i.e. today's idle_ms-only behavior, rather than crashing the
15
+ daemon; a wrong-but-safe default beats an unhandled exception in the poll loop.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import ctypes
21
+ import os
22
+ import subprocess
23
+ import sys
24
+ from dataclasses import dataclass
25
+ from typing import Optional
26
+
27
+
28
+ @dataclass
29
+ class Sample:
30
+ idle_ms: int
31
+ locked: bool
32
+
33
+
34
+ class SimulatedIdle:
35
+ """Replays a scripted sequence of samples (scripted runs / tests)."""
36
+
37
+ def __init__(self, samples: list) -> None:
38
+ self._samples = samples
39
+ self._i = 0
40
+
41
+ def sample(self) -> Sample:
42
+ if self._i < len(self._samples):
43
+ s = self._samples[self._i]
44
+ else:
45
+ s = Sample(idle_ms=2**63 - 1, locked=False) # exhausted -> very idle
46
+ self._i += 1
47
+ return s
48
+
49
+
50
+ # XScreenSaverInfo: idle (unsigned long) is at byte offset 24 on LP64
51
+ # (window u64, state i32, kind i32, since u64, idle u64, ...).
52
+ _IDLE_OFFSET = 24
53
+
54
+
55
+ def _parse_locked_hint(returncode: int, stdout: str) -> Optional[bool]:
56
+ """Interpret `loginctl show-session <id> -p LockedHint --value` output.
57
+ None means "couldn't tell" (missing binary, no session id, non-systemd
58
+ session, ...) — the caller must treat that as "assume not locked" rather
59
+ than erroring, since this is a best-effort signal on top of idle_ms."""
60
+ if returncode != 0:
61
+ return None
62
+ value = stdout.strip()
63
+ if value not in ("yes", "no"):
64
+ return None
65
+ return value == "yes"
66
+
67
+
68
+ def linux_session_locked() -> Optional[bool]:
69
+ """logind's `LockedHint` — set the moment a lock screen (gnome-screensaver,
70
+ light-locker, systemd-triggered lid lock, ...) engages, unlike the X11 idle
71
+ timer which some lockers/compositors can keep nudging. Requires
72
+ `$XDG_SESSION_ID` (present on any systemd-logind desktop session) and the
73
+ `loginctl` binary (part of systemd, not a new dependency to install)."""
74
+ session_id = os.environ.get("XDG_SESSION_ID")
75
+ if not session_id:
76
+ return None
77
+ try:
78
+ proc = subprocess.run(
79
+ ["loginctl", "show-session", session_id, "-p", "LockedHint", "--value"],
80
+ capture_output=True, text=True, timeout=2,
81
+ )
82
+ except (OSError, subprocess.TimeoutExpired):
83
+ return None
84
+ return _parse_locked_hint(proc.returncode, proc.stdout)
85
+
86
+
87
+ class LinuxIdle:
88
+ def __init__(self) -> None:
89
+ try:
90
+ x11 = ctypes.CDLL("libX11.so.6")
91
+ xss = ctypes.CDLL("libXss.so.1")
92
+ except OSError as e:
93
+ raise OSError(f"cannot load X libraries ({e}); set them up or use --simulate") from e
94
+
95
+ x11.XOpenDisplay.restype = ctypes.c_void_p
96
+ x11.XOpenDisplay.argtypes = [ctypes.c_char_p]
97
+ x11.XDefaultRootWindow.restype = ctypes.c_ulong
98
+ x11.XDefaultRootWindow.argtypes = [ctypes.c_void_p]
99
+ xss.XScreenSaverAllocInfo.restype = ctypes.c_void_p
100
+ xss.XScreenSaverQueryInfo.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p]
101
+ xss.XScreenSaverQueryInfo.restype = ctypes.c_int
102
+
103
+ self._display = x11.XOpenDisplay(None)
104
+ if not self._display:
105
+ raise OSError("cannot open X display (set DISPLAY, or use --simulate)")
106
+ self._root = x11.XDefaultRootWindow(self._display)
107
+ self._info = xss.XScreenSaverAllocInfo()
108
+ self._query = xss.XScreenSaverQueryInfo
109
+
110
+ def sample(self) -> Sample:
111
+ self._query(self._display, self._root, self._info)
112
+ idle_ptr = ctypes.cast(self._info + _IDLE_OFFSET, ctypes.POINTER(ctypes.c_ulong))
113
+ locked = linux_session_locked()
114
+ return Sample(idle_ms=int(idle_ptr.contents.value), locked=bool(locked))
115
+
116
+
117
+ class _LASTINPUTINFO(ctypes.Structure):
118
+ _fields_ = [("cbSize", ctypes.c_uint), ("dwTime", ctypes.c_uint)]
119
+
120
+
121
+ # WTSQuerySessionInformationW(..., WTSSessionInfoEx, ...) fills a WTSINFOEXW:
122
+ # DWORD Level; // offset 0 — union variant selector (1 == Level1)
123
+ # union { WTSINFOEX_LEVEL1_W L1; // offset 4 (DWORD-aligned)
124
+ # ULONG SessionId; // +0
125
+ # WTS_CONNECTSTATE_CLASS State; // +4 (C enum, 4 bytes)
126
+ # LONG SessionFlags; // +8 (WTS_SESSIONSTATE_LOCK=0 / _UNLOCK=1 / _UNKNOWN=-1)
127
+ # ... (session addresses, latency — unused, and version-sensitive) ...
128
+ # }
129
+ # Reading just these two ints by fixed offset (rather than modeling the full,
130
+ # larger union) mirrors the same trick already used for X11's
131
+ # XScreenSaverInfo above — the ABI for this struct has been stable since Vista.
132
+ _WTS_LEVEL_OFFSET = 0
133
+ _WTS_SESSION_FLAGS_OFFSET = 12
134
+ WTS_SESSIONSTATE_LOCK = 0
135
+ WTS_CURRENT_SERVER_HANDLE = 0
136
+ WTS_CURRENT_SESSION = -1 # cast to DWORD below; WTS_CURRENT_SESSION is (DWORD)-1
137
+ _WTS_SESSION_INFO_EX = 25 # WTS_INFO_CLASS.WTSSessionInfoEx
138
+
139
+
140
+ def _locked_from_session_flags(level: int, session_flags: int) -> Optional[bool]:
141
+ """Pure interpretation of a WTSINFOEXW's Level/SessionFlags, split out from
142
+ the ctypes plumbing so it's unit-testable without a real Windows session."""
143
+ if level != 1:
144
+ return None # unrecognized variant — don't guess
145
+ if session_flags not in (0, 1):
146
+ return None # WTS_SESSIONSTATE_UNKNOWN (-1) or an unexpected value
147
+ return session_flags == WTS_SESSIONSTATE_LOCK
148
+
149
+
150
+ def windows_session_locked(wtsapi32) -> Optional[bool]:
151
+ buf = ctypes.c_void_p()
152
+ length = ctypes.c_uint()
153
+ ok = wtsapi32.WTSQuerySessionInformationW(
154
+ WTS_CURRENT_SERVER_HANDLE,
155
+ ctypes.c_uint(WTS_CURRENT_SESSION & 0xFFFFFFFF),
156
+ _WTS_SESSION_INFO_EX,
157
+ ctypes.byref(buf),
158
+ ctypes.byref(length),
159
+ )
160
+ if not ok or not buf.value:
161
+ return None
162
+ try:
163
+ level = ctypes.cast(buf.value + _WTS_LEVEL_OFFSET, ctypes.POINTER(ctypes.c_uint32)).contents.value
164
+ flags = ctypes.cast(
165
+ buf.value + _WTS_SESSION_FLAGS_OFFSET, ctypes.POINTER(ctypes.c_int32)
166
+ ).contents.value
167
+ finally:
168
+ wtsapi32.WTSFreeMemory(buf)
169
+ return _locked_from_session_flags(level, flags)
170
+
171
+
172
+ class WindowsIdle:
173
+ def __init__(self) -> None:
174
+ self._user32 = ctypes.windll.user32 # type: ignore[attr-defined]
175
+ self._kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
176
+ # windows_session_locked() (WTSQuerySessionInformationW/WTSSessionInfoEx,
177
+ # below) is DISABLED — see CLAUDE.md. Its struct-offset read was never
178
+ # verified on real Windows hardware and, in production, it returned
179
+ # "locked" on the very first poll and never once returned "unlocked"
180
+ # again across 6 days / 20,000+ polls — not imprecise, structurally
181
+ # incapable of ever confirming activity again, since input_fresh()
182
+ # requires `not locked`. Hardcoded to None (idle_ms-only, the
183
+ # known-safe pre-v0.5.0 behavior) until this is fixed AND actually
184
+ # verified against real hardware, not just reasoned about.
185
+ self._wtsapi32 = None
186
+
187
+ def sample(self) -> Sample:
188
+ info = _LASTINPUTINFO()
189
+ info.cbSize = ctypes.sizeof(_LASTINPUTINFO)
190
+ if self._user32.GetLastInputInfo(ctypes.byref(info)) == 0:
191
+ raise OSError("GetLastInputInfo failed")
192
+ tick = self._kernel32.GetTickCount() & 0xFFFFFFFF
193
+ idle_ms = (tick - info.dwTime) & 0xFFFFFFFF # wrapping_sub, as u32
194
+ locked = False
195
+ if self._wtsapi32 is not None:
196
+ try:
197
+ locked = bool(windows_session_locked(self._wtsapi32))
198
+ except OSError:
199
+ locked = False
200
+ return Sample(idle_ms=idle_ms, locked=locked)
201
+
202
+
203
+ def platform_source():
204
+ """Construct the real platform idle source, or fail fast with a clear message."""
205
+ if sys.platform.startswith("linux"):
206
+ return LinuxIdle()
207
+ if sys.platform == "win32":
208
+ return WindowsIdle()
209
+ raise OSError(f"no idle source for platform {sys.platform!r}; use --simulate")
@@ -9,16 +9,25 @@ Any change here MUST land as a change to the behavioural vectors in
9
9
  - downtime (reboot/suspend/clock-step) is reconciled via monotonic-vs-wall
10
10
  divergence and startup recover().
11
11
 
12
- Pure: `step` takes an observation and returns events, with no I/O. All arithmetic
13
- is integer milliseconds.
12
+ Pure with respect to its return value: `step` takes an observation and
13
+ returns events computed from no other input. All arithmetic is integer
14
+ milliseconds. It does emit DEBUG-level log records of every decision (fresh
15
+ input, idle/heartbeat/reconcile branches taken, anchors chosen) — that is
16
+ observability only, never consulted by the tests or by any other code, so it
17
+ does not compromise the vectors in `tests/vectors/` as the oracle for this
18
+ logic.
14
19
  """
15
20
 
16
21
  from __future__ import annotations
17
22
 
23
+ import logging
18
24
  from dataclasses import dataclass
19
25
  from typing import Optional
20
26
 
21
27
  from .core import EventKind, event
28
+ from .logging_setup import LOGGER_NAME
29
+
30
+ logger = logging.getLogger(LOGGER_NAME)
22
31
 
23
32
  # Input newer than this counts as "fresh" on a tick. Deliberately NOT poll_ms:
24
33
  # freshness is "how recent must input be to mean the user is here", independent
@@ -74,14 +83,34 @@ class StateMachine:
74
83
  self.p = persisted
75
84
 
76
85
  def emit(self, ts: int, kind: str) -> dict:
77
- """Emit an event, holding the monotonic-timestamp watermark. Clamping
78
- here means no path can emit out of order."""
86
+ """Emit a span-boundary event (active/idle), holding the monotonic
87
+ watermark so no path can emit one out of order relative to the last.
88
+ Heartbeats go through `emit_heartbeat` instead, deliberately NOT
89
+ through here: the backend pairs spans from active/idle ts alone
90
+ (`pairSpans` in worktime.ts) and never requires an idle ts to be at or
91
+ after some prior heartbeat's ts — a heartbeat is a wall-clock liveness
92
+ ping, not a span boundary. Letting a heartbeat raise this watermark
93
+ used to force a legitimately earlier, correctly back-dated idle close
94
+ forward to the last heartbeat's ts — which happened on essentially
95
+ every idle transition at default settings, since heartbeat_ms (5 min)
96
+ is shorter than min_inactivity_ms (10 min), so a heartbeat has always
97
+ fired since the real last input by the time idle_long confirms.
98
+ Observed in production: an active span's real last input was 14:01:33,
99
+ confirmed idle at 14:11:42, and got reported as ending 14:07:11 (the
100
+ last heartbeat) instead — see CLAUDE.md."""
79
101
  prev = self.p.last_emitted_ts
80
102
  if prev is not None and ts < prev:
81
103
  ts = prev
82
104
  self.p.last_emitted_ts = ts
83
105
  return event(ts, kind)
84
106
 
107
+ def emit_heartbeat(self, ts: int) -> dict:
108
+ """A wall-clock liveness ping, not a span boundary — see `emit`. `ts`
109
+ is always `tick.now` (never back-dated), so it never needs the
110
+ backwards-clock clamp for itself, and must not raise the watermark
111
+ that clamps a later active/idle back-date."""
112
+ return event(ts, EventKind.HEARTBEAT)
113
+
85
114
  def input_fresh(self, tick: Tick) -> bool:
86
115
  return (not tick.locked) and tick.idle_ms < FRESH_INPUT_MS
87
116
 
@@ -100,10 +129,20 @@ class StateMachine:
100
129
  last local evidence. Shared by recover() and in-loop detection so they
101
130
  cannot drift apart."""
102
131
  if self.p.reported_state != ACTIVE or gap_ms < self.t.min_inactivity_ms:
132
+ logger.debug(
133
+ "reconcile_gap: gap_ms=%d state=%s min_inactivity_ms=%d -> absorbed, no reconcile",
134
+ gap_ms, self.p.reported_state, self.t.min_inactivity_ms,
135
+ )
103
136
  return []
104
137
  anchor = self.last_evidence()
105
138
  if anchor is None:
139
+ logger.debug("reconcile_gap: gap_ms=%d but no last evidence recorded -> nothing to anchor to", gap_ms)
106
140
  return []
141
+ logger.debug(
142
+ "reconcile_gap: gap_ms=%d >= min_inactivity_ms=%d -> closing span at anchor=%d "
143
+ "(last_heartbeat=%s last_active_time=%s)",
144
+ gap_ms, self.t.min_inactivity_ms, anchor, self.p.last_heartbeat, self.p.last_active_time,
145
+ )
107
146
  self.p.reported_state = IDLE
108
147
  self.p.pending_active_since = None
109
148
  return [self.emit(anchor, EventKind.IDLE)]
@@ -113,8 +152,11 @@ class StateMachine:
113
152
  is measured from the last local evidence to now."""
114
153
  a = self.last_evidence()
115
154
  if a is None:
155
+ logger.debug("recover: now=%d no last evidence recorded -> nothing to reconcile", now)
116
156
  return []
117
- return self.reconcile_gap(now - a)
157
+ gap = now - a
158
+ logger.debug("recover: now=%d last_evidence=%d gap_ms=%d", now, a, gap)
159
+ return self.reconcile_gap(gap)
118
160
 
119
161
  def due_heartbeat(self, now: int) -> bool:
120
162
  hb = self.p.last_heartbeat
@@ -124,6 +166,10 @@ class StateMachine:
124
166
 
125
167
  def step(self, tick: Tick) -> list:
126
168
  out: list = []
169
+ logger.debug(
170
+ "tick: now=%d idle_ms=%d locked=%s mono_elapsed_ms=%s state=%s",
171
+ tick.now, tick.idle_ms, tick.locked, tick.mono_elapsed_ms, self.p.reported_state,
172
+ )
127
173
 
128
174
  # Downtime the daemon slept through: wall advances across a suspend while
129
175
  # the monotonic clock does not, so the difference isolates the frozen
@@ -131,17 +177,35 @@ class StateMachine:
131
177
  # absorb the suspend). Backwards divergence is a clock correction, ignored.
132
178
  if tick.mono_elapsed_ms is not None:
133
179
  seen = self.p.last_seen_wall if self.p.last_seen_wall is not None else tick.now
134
- divergence = (tick.now - seen) - tick.mono_elapsed_ms
180
+ wall_gap = tick.now - seen
181
+ divergence = wall_gap - tick.mono_elapsed_ms
135
182
  if divergence > 0:
183
+ logger.debug(
184
+ "suspend divergence: wall_gap=%d mono_elapsed_ms=%d divergence=%d -> reconciling",
185
+ wall_gap, tick.mono_elapsed_ms, divergence,
186
+ )
136
187
  out.extend(self.reconcile_gap(divergence))
188
+ elif divergence < 0:
189
+ logger.debug(
190
+ "backwards clock divergence ignored: wall_gap=%d mono_elapsed_ms=%d divergence=%d",
191
+ wall_gap, tick.mono_elapsed_ms, divergence,
192
+ )
137
193
  self.p.last_seen_wall = tick.now
138
194
 
139
195
  fresh = self.input_fresh(tick)
196
+ logger.debug(
197
+ "input_fresh=%s (locked=%s idle_ms=%d fresh_threshold_ms=%d)",
198
+ fresh, tick.locked, tick.idle_ms, FRESH_INPUT_MS,
199
+ )
140
200
  if fresh:
141
201
  self.p.last_active_time = tick.now
142
202
 
143
203
  if self.p.reported_state == ACTIVE:
144
204
  idle_long = tick.locked or tick.idle_ms >= self.t.min_inactivity_ms
205
+ logger.debug(
206
+ "active-branch: idle_long=%s (locked=%s idle_ms=%d min_inactivity_ms=%d)",
207
+ idle_long, tick.locked, tick.idle_ms, self.t.min_inactivity_ms,
208
+ )
145
209
  if idle_long:
146
210
  # Back-date idle to when input actually stopped. On the LOCK path
147
211
  # keep the last-input anchor (reported idle at lock reflects the
@@ -149,27 +213,48 @@ class StateMachine:
149
213
  # the exact stop moment.
150
214
  if tick.locked:
151
215
  ts = self.p.last_active_time if self.p.last_active_time is not None else tick.now
216
+ path = "locked"
152
217
  else:
153
218
  ts = tick.now - tick.idle_ms
219
+ path = "idle_ms"
220
+ logger.debug("-> closing active span: kind=idle ts=%d (path=%s)", ts, path)
154
221
  out.append(self.emit(ts, EventKind.IDLE))
155
222
  self.p.reported_state = IDLE
156
223
  self.p.pending_active_since = None
157
224
  elif self.due_heartbeat(tick.now):
158
- out.append(self.emit(tick.now, EventKind.HEARTBEAT))
225
+ logger.debug(
226
+ "-> heartbeat due (last_heartbeat=%s heartbeat_ms=%d)",
227
+ self.p.last_heartbeat, self.t.heartbeat_ms,
228
+ )
229
+ out.append(self.emit_heartbeat(tick.now))
159
230
  self.p.last_heartbeat = tick.now
160
231
  else: # IDLE
161
232
  # "Activity persisted for min_activity" must tolerate short pauses.
162
233
  # The claim dies only when idle reaches min_activity itself; below
163
234
  # that the accumulator keeps running.
164
235
  if tick.locked or tick.idle_ms >= self.t.min_activity_ms:
236
+ if self.p.pending_active_since is not None:
237
+ logger.debug(
238
+ "idle-branch: pending activation dropped (locked=%s idle_ms=%d min_activity_ms=%d)",
239
+ tick.locked, tick.idle_ms, self.t.min_activity_ms,
240
+ )
165
241
  self.p.pending_active_since = None
166
242
  else:
167
243
  # Start only on genuinely fresh input; once started, short pauses
168
244
  # no longer reset it. Anchor to the real resume moment.
169
245
  if fresh and self.p.pending_active_since is None:
170
246
  self.p.pending_active_since = tick.now - tick.idle_ms
247
+ logger.debug("idle-branch: pending activation started, anchor=%d", self.p.pending_active_since)
171
248
  if self.p.pending_active_since is not None:
172
- if tick.now - self.p.pending_active_since >= self.t.min_activity_ms:
249
+ sustained_ms = tick.now - self.p.pending_active_since
250
+ logger.debug(
251
+ "idle-branch: pending activation sustained_ms=%d min_activity_ms=%d",
252
+ sustained_ms, self.t.min_activity_ms,
253
+ )
254
+ if sustained_ms >= self.t.min_activity_ms:
255
+ logger.debug(
256
+ "-> confirming active: kind=active ts=%d", self.p.pending_active_since
257
+ )
173
258
  out.append(self.emit(self.p.pending_active_since, EventKind.ACTIVE))
174
259
  self.p.reported_state = ACTIVE
175
260
  self.p.pending_active_since = None
@@ -0,0 +1,46 @@
1
+ from flexitracker.idle import (
2
+ Sample,
3
+ SimulatedIdle,
4
+ _locked_from_session_flags,
5
+ _parse_locked_hint,
6
+ )
7
+
8
+
9
+ def test_simulated_replays_then_reports_idle():
10
+ s = SimulatedIdle([Sample(0, False), Sample(5000, False)])
11
+ assert s.sample().idle_ms == 0
12
+ assert s.sample().idle_ms == 5000
13
+ # Exhausted -> very idle (matches the Rust i64::MAX sentinel).
14
+ assert s.sample().idle_ms == 2**63 - 1
15
+
16
+
17
+ def test_parse_locked_hint_yes():
18
+ assert _parse_locked_hint(0, "yes\n") is True
19
+
20
+
21
+ def test_parse_locked_hint_no():
22
+ assert _parse_locked_hint(0, "no\n") is False
23
+
24
+
25
+ def test_parse_locked_hint_nonzero_exit_is_unknown():
26
+ assert _parse_locked_hint(1, "") is None
27
+
28
+
29
+ def test_parse_locked_hint_unexpected_value_is_unknown():
30
+ assert _parse_locked_hint(0, "maybe") is None
31
+
32
+
33
+ def test_locked_from_session_flags_lock():
34
+ assert _locked_from_session_flags(level=1, session_flags=0) is True
35
+
36
+
37
+ def test_locked_from_session_flags_unlock():
38
+ assert _locked_from_session_flags(level=1, session_flags=1) is False
39
+
40
+
41
+ def test_locked_from_session_flags_unknown_flag_value():
42
+ assert _locked_from_session_flags(level=1, session_flags=-1) is None
43
+
44
+
45
+ def test_locked_from_session_flags_unrecognized_level():
46
+ assert _locked_from_session_flags(level=0, session_flags=0) is None
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "heartbeat_does_not_clamp_a_later_idle_backdate",
3
+ "description": "A heartbeat between the real last input and the confirmed idle close must not force the idle close's back-dated ts forward to the heartbeat's ts. Reproduces a production incident: real last input 14:01:33, confirmed idle 14:11:42, incorrectly reported as ending 14:07:11 (the last heartbeat) instead of 14:01:33.",
4
+ "initial": { "reported_state": "Active", "last_active_time": 0, "last_emitted_ts": 0 },
5
+ "steps": [
6
+ { "op": "tick", "now": 300000, "idle_ms": 300000 },
7
+ { "op": "tick", "now": 600000, "idle_ms": 600000 }
8
+ ],
9
+ "expected": [
10
+ { "kind": "heartbeat", "ts": 300000 },
11
+ { "kind": "idle", "ts": 0 }
12
+ ],
13
+ "expected_final": { "reported_state": "Idle" }
14
+ }
@@ -1,97 +0,0 @@
1
- """Idle-time and session-lock detection — mirror of `idle.rs`, via ctypes.
2
-
3
- No input content is ever captured — only "how long since any input" and whether
4
- the session is locked. Platform sources are selected at runtime; a simulated
5
- source drives scripted runs and tests. Using ctypes (stdlib) means no compiled
6
- extension and so no C toolchain at install time.
7
- """
8
-
9
- from __future__ import annotations
10
-
11
- import ctypes
12
- import sys
13
- from dataclasses import dataclass
14
-
15
-
16
- @dataclass
17
- class Sample:
18
- idle_ms: int
19
- locked: bool
20
-
21
-
22
- class SimulatedIdle:
23
- """Replays a scripted sequence of samples (scripted runs / tests)."""
24
-
25
- def __init__(self, samples: list) -> None:
26
- self._samples = samples
27
- self._i = 0
28
-
29
- def sample(self) -> Sample:
30
- if self._i < len(self._samples):
31
- s = self._samples[self._i]
32
- else:
33
- s = Sample(idle_ms=2**63 - 1, locked=False) # exhausted -> very idle
34
- self._i += 1
35
- return s
36
-
37
-
38
- # XScreenSaverInfo: idle (unsigned long) is at byte offset 24 on LP64
39
- # (window u64, state i32, kind i32, since u64, idle u64, ...).
40
- _IDLE_OFFSET = 24
41
-
42
-
43
- class LinuxIdle:
44
- def __init__(self) -> None:
45
- try:
46
- x11 = ctypes.CDLL("libX11.so.6")
47
- xss = ctypes.CDLL("libXss.so.1")
48
- except OSError as e:
49
- raise OSError(f"cannot load X libraries ({e}); set them up or use --simulate") from e
50
-
51
- x11.XOpenDisplay.restype = ctypes.c_void_p
52
- x11.XOpenDisplay.argtypes = [ctypes.c_char_p]
53
- x11.XDefaultRootWindow.restype = ctypes.c_ulong
54
- x11.XDefaultRootWindow.argtypes = [ctypes.c_void_p]
55
- xss.XScreenSaverAllocInfo.restype = ctypes.c_void_p
56
- xss.XScreenSaverQueryInfo.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p]
57
- xss.XScreenSaverQueryInfo.restype = ctypes.c_int
58
-
59
- self._display = x11.XOpenDisplay(None)
60
- if not self._display:
61
- raise OSError("cannot open X display (set DISPLAY, or use --simulate)")
62
- self._root = x11.XDefaultRootWindow(self._display)
63
- self._info = xss.XScreenSaverAllocInfo()
64
- self._query = xss.XScreenSaverQueryInfo
65
-
66
- def sample(self) -> Sample:
67
- self._query(self._display, self._root, self._info)
68
- idle_ptr = ctypes.cast(self._info + _IDLE_OFFSET, ctypes.POINTER(ctypes.c_ulong))
69
- return Sample(idle_ms=int(idle_ptr.contents.value), locked=False)
70
-
71
-
72
- class _LASTINPUTINFO(ctypes.Structure):
73
- _fields_ = [("cbSize", ctypes.c_uint), ("dwTime", ctypes.c_uint)]
74
-
75
-
76
- class WindowsIdle:
77
- def __init__(self) -> None:
78
- self._user32 = ctypes.windll.user32 # type: ignore[attr-defined]
79
- self._kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
80
-
81
- def sample(self) -> Sample:
82
- info = _LASTINPUTINFO()
83
- info.cbSize = ctypes.sizeof(_LASTINPUTINFO)
84
- if self._user32.GetLastInputInfo(ctypes.byref(info)) == 0:
85
- raise OSError("GetLastInputInfo failed")
86
- tick = self._kernel32.GetTickCount() & 0xFFFFFFFF
87
- idle_ms = (tick - info.dwTime) & 0xFFFFFFFF # wrapping_sub, as u32
88
- return Sample(idle_ms=idle_ms, locked=False)
89
-
90
-
91
- def platform_source():
92
- """Construct the real platform idle source, or fail fast with a clear message."""
93
- if sys.platform.startswith("linux"):
94
- return LinuxIdle()
95
- if sys.platform == "win32":
96
- return WindowsIdle()
97
- raise OSError(f"no idle source for platform {sys.platform!r}; use --simulate")
@@ -1,9 +0,0 @@
1
- from flexitracker.idle import Sample, SimulatedIdle
2
-
3
-
4
- def test_simulated_replays_then_reports_idle():
5
- s = SimulatedIdle([Sample(0, False), Sample(5000, False)])
6
- assert s.sample().idle_ms == 0
7
- assert s.sample().idle_ms == 5000
8
- # Exhausted -> very idle (matches the Rust i64::MAX sentinel).
9
- assert s.sample().idle_ms == 2**63 - 1
File without changes
File without changes
File without changes