flexitracker 0.5.1__tar.gz → 0.5.3__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 (62) hide show
  1. {flexitracker-0.5.1 → flexitracker-0.5.3}/PKG-INFO +1 -1
  2. {flexitracker-0.5.1 → flexitracker-0.5.3}/src/flexitracker/config.py +2 -2
  3. {flexitracker-0.5.1 → flexitracker-0.5.3}/src/flexitracker/idle.py +30 -16
  4. {flexitracker-0.5.1 → flexitracker-0.5.3}/src/flexitracker/sender.py +20 -8
  5. {flexitracker-0.5.1 → flexitracker-0.5.3}/src/flexitracker/state_machine.py +55 -46
  6. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/test_config.py +2 -2
  7. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/test_conformance.py +2 -2
  8. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/test_sender_body.py +18 -0
  9. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/01-activation-debounced-backdated.json +1 -0
  10. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/02-idle-backdated-to-last-input.json +1 -0
  11. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/03-short-break-absorbed.json +1 -0
  12. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/04-brief-activity-debounced.json +1 -0
  13. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/05-sustained-return-backdated.json +1 -0
  14. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/06-heartbeats-while-active.json +1 -0
  15. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/07-recover-after-sudden-shutdown.json +1 -0
  16. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/08-locked-session-goes-idle.json +1 -0
  17. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/09-recover-anchors-later-evidence.json +1 -0
  18. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/10-suspend-longer-closes-span.json +1 -0
  19. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/11-suspend-with-immediate-wake.json +1 -0
  20. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/12-suspend-shorter-absorbed.json +1 -0
  21. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/13-backwards-clock-watermark.json +1 -0
  22. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/14-small-forward-clock-absorbed.json +1 -0
  23. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/15-recover-from-active-matches-loop.json +1 -0
  24. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/16-explicit-close-no-double-close.json +1 -0
  25. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/18-short-reading-pause.json +1 -0
  26. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/19-presence-must-be-sustained.json +1 -0
  27. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/20-gap-kills-pending-return.json +1 -0
  28. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/21-idle-backdating-exact.json +1 -0
  29. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/22-min-inactivity-exact-boundary.json +1 -0
  30. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/23-large-timestamps.json +1 -0
  31. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/24-all-kinds-lowercase.json +1 -0
  32. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/25-heartbeat-does-not-clamp-idle-backdate.json +1 -0
  33. flexitracker-0.5.3/tests/vectors/26-suspend-with-running-monotonic-clock.json +14 -0
  34. flexitracker-0.5.3/tests/vectors/27-long-downtime-drops-pending-return.json +14 -0
  35. flexitracker-0.5.3/tests/vectors/28-return-tolerates-poll-interval.json +14 -0
  36. flexitracker-0.5.3/tests/vectors/29-single-touch-never-confirms.json +13 -0
  37. flexitracker-0.5.3/tests/vectors/30-default-idle-threshold-is-15-min.json +16 -0
  38. flexitracker-0.5.3/tests/vectors/31-idle-ending-between-polls.json +16 -0
  39. flexitracker-0.5.3/tools/wts_lock_diagnostic.py +127 -0
  40. {flexitracker-0.5.1 → flexitracker-0.5.3}/.gitignore +0 -0
  41. {flexitracker-0.5.1 → flexitracker-0.5.3}/LICENSE +0 -0
  42. {flexitracker-0.5.1 → flexitracker-0.5.3}/README.md +0 -0
  43. {flexitracker-0.5.1 → flexitracker-0.5.3}/install/README.md +0 -0
  44. {flexitracker-0.5.1 → flexitracker-0.5.3}/install/flexitracker.service +0 -0
  45. {flexitracker-0.5.1 → flexitracker-0.5.3}/pyinstaller_entry.py +0 -0
  46. {flexitracker-0.5.1 → flexitracker-0.5.3}/pyproject.toml +0 -0
  47. {flexitracker-0.5.1 → flexitracker-0.5.3}/src/flexitracker/__init__.py +0 -0
  48. {flexitracker-0.5.1 → flexitracker-0.5.3}/src/flexitracker/__main__.py +0 -0
  49. {flexitracker-0.5.1 → flexitracker-0.5.3}/src/flexitracker/_backend.py +0 -0
  50. {flexitracker-0.5.1 → flexitracker-0.5.3}/src/flexitracker/cli.py +0 -0
  51. {flexitracker-0.5.1 → flexitracker-0.5.3}/src/flexitracker/core.py +0 -0
  52. {flexitracker-0.5.1 → flexitracker-0.5.3}/src/flexitracker/logging_setup.py +0 -0
  53. {flexitracker-0.5.1 → flexitracker-0.5.3}/src/flexitracker/login.py +0 -0
  54. {flexitracker-0.5.1 → flexitracker-0.5.3}/src/flexitracker/outbox.py +0 -0
  55. {flexitracker-0.5.1 → flexitracker-0.5.3}/src/flexitracker/version.py +0 -0
  56. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/test_cli.py +0 -0
  57. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/test_idle.py +0 -0
  58. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/test_logging_setup.py +0 -0
  59. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/test_login.py +0 -0
  60. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/test_outbox.py +0 -0
  61. {flexitracker-0.5.1 → flexitracker-0.5.3}/tests/vectors/17-freshness-independent-of-poll.json +0 -0
  62. {flexitracker-0.5.1 → flexitracker-0.5.3}/uv.lock +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: flexitracker
3
- Version: 0.5.1
3
+ Version: 0.5.3
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
@@ -22,7 +22,7 @@ from .state_machine import Thresholds
22
22
  @dataclass
23
23
  class ThresholdCfg:
24
24
  poll_sec: int = 15
25
- min_inactivity_sec: int = 600
25
+ min_inactivity_sec: int = 900
26
26
  min_activity_sec: int = 30
27
27
  heartbeat_sec: int = 300
28
28
 
@@ -63,7 +63,7 @@ class Config:
63
63
  machine_id=data.get("machine_id"),
64
64
  thresholds=ThresholdCfg(
65
65
  poll_sec=th.get("poll_sec", 15),
66
- min_inactivity_sec=th.get("min_inactivity_sec", 600),
66
+ min_inactivity_sec=th.get("min_inactivity_sec", 900),
67
67
  min_activity_sec=th.get("min_activity_sec", 30),
68
68
  heartbeat_sec=th.get("heartbeat_sec", 300),
69
69
  ),
@@ -120,17 +120,31 @@ class _LASTINPUTINFO(ctypes.Structure):
120
120
 
121
121
  # WTSQuerySessionInformationW(..., WTSSessionInfoEx, ...) fills a WTSINFOEXW:
122
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)
123
+ # <4 bytes padding> // offset 4 — see below
124
+ # union { WTSINFOEX_LEVEL1_W L1; // offset 8
125
+ # ULONG SessionId; // +0 (offset 8)
126
+ # WTS_CONNECTSTATE_CLASS State; // +4 (offset 12; C enum, 4 bytes)
127
+ # LONG SessionFlags; // +8 (offset 16; WTS_SESSIONSTATE_LOCK=0 / _UNLOCK=1 / _UNKNOWN=-1)
127
128
  # ... (session addresses, latency — unused, and version-sensitive) ...
128
129
  # }
130
+ # The padding is NOT in Microsoft's field list (which just shows Level then
131
+ # the union) — it exists because WTSINFOEX_LEVEL1_W contains several 8-byte
132
+ # LARGE_INTEGER fields further down (LogonTime etc.), which gives the whole
133
+ # struct — and the union wrapping it — 8-byte alignment on a 64-bit process,
134
+ # pushing the union from offset 4 to offset 8. A first version of this code
135
+ # used offset 12 for SessionFlags, reasoned from the field list without
136
+ # accounting for this, and it landed on SessionState instead (0 = WTSActive
137
+ # for a normal local console session — which numerically collides with
138
+ # WTS_SESSIONSTATE_LOCK, so it read "locked" 100% of the time in production;
139
+ # see CLAUDE.md). Offset 16 was confirmed empirically — not just reasoned —
140
+ # via `tools/wts_lock_diagnostic.py`: [8] exactly matched an independently
141
+ # fetched WTSGetActiveConsoleSessionId() (proving SessionId's real offset),
142
+ # and [16] was the one that actually flipped 1↔0 on real lock/unlock.
129
143
  # Reading just these two ints by fixed offset (rather than modeling the full,
130
144
  # larger union) mirrors the same trick already used for X11's
131
- # XScreenSaverInfo above — the ABI for this struct has been stable since Vista.
145
+ # XScreenSaverInfo above.
132
146
  _WTS_LEVEL_OFFSET = 0
133
- _WTS_SESSION_FLAGS_OFFSET = 12
147
+ _WTS_SESSION_FLAGS_OFFSET = 16
134
148
  WTS_SESSIONSTATE_LOCK = 0
135
149
  WTS_CURRENT_SERVER_HANDLE = 0
136
150
  WTS_CURRENT_SESSION = -1 # cast to DWORD below; WTS_CURRENT_SESSION is (DWORD)-1
@@ -173,16 +187,16 @@ class WindowsIdle:
173
187
  def __init__(self) -> None:
174
188
  self._user32 = ctypes.windll.user32 # type: ignore[attr-defined]
175
189
  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
190
+ # windows_session_locked() (WTSQuerySessionInformationW/WTSSessionInfoEx)
191
+ # was disabled in v0.5.1 after shipping an unverified struct offset
192
+ # that read "locked" permanently in production (see CLAUDE.md). The
193
+ # corrected offset (16, not 12) is now confirmed by direct
194
+ # measurement on real hardware, not just reasoning — see the offset
195
+ # comment above and `tools/wts_lock_diagnostic.py`. Re-enabled.
196
+ try:
197
+ self._wtsapi32 = ctypes.windll.wtsapi32 # type: ignore[attr-defined]
198
+ except OSError:
199
+ self._wtsapi32 = None # lock detection unavailable; idle_ms-only, as before
186
200
 
187
201
  def sample(self) -> Sample:
188
202
  info = _LASTINPUTINFO()
@@ -7,6 +7,7 @@ in `docs/wire-schema.md`; the black-box harness proves it matches the reference.
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
+ import http.client
10
11
  import json
11
12
  import urllib.error
12
13
  import urllib.request
@@ -24,6 +25,11 @@ from .version import get_version
24
25
  USER_AGENT = f"flexitracker-daemon/{get_version()}"
25
26
 
26
27
 
28
+ # The poll loop sends inline, so a request that never returns would stop all
29
+ # tracking; the daemon would then read the stall as absence.
30
+ REQUEST_TIMEOUT_S = 20
31
+
32
+
27
33
  class SenderError(Exception):
28
34
  pass
29
35
 
@@ -37,7 +43,7 @@ def _request(url: str, key: Optional[str], method: str, body: Optional[dict]) ->
37
43
  data = json.dumps(body).encode("utf-8")
38
44
  headers["content-type"] = "application/json"
39
45
  req = urllib.request.Request(url, data=data, headers=headers, method=method)
40
- with urllib.request.urlopen(req) as resp: # noqa: S310 (fixed backend URL)
46
+ with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT_S) as resp: # noqa: S310 (fixed backend URL)
41
47
  raw = resp.read()
42
48
  return json.loads(raw) if raw else {}
43
49
 
@@ -60,8 +66,10 @@ def post_batch(base: str, key: str, batch: dict) -> None:
60
66
  _request(_ingest_url(base), key, "POST", body)
61
67
  except urllib.error.HTTPError as e:
62
68
  raise SenderError(f"server returned {e.code}") from e
63
- except urllib.error.URLError as e:
64
- raise SenderError(str(e.reason)) from e
69
+ except (OSError, http.client.HTTPException) as e:
70
+ # URLError, but also a timeout or dropped connection mid-response, which
71
+ # urllib raises unwrapped.
72
+ raise SenderError(str(getattr(e, "reason", e))) from e
65
73
 
66
74
 
67
75
  @dataclass
@@ -81,8 +89,10 @@ def whoami(base: str, key: str) -> WhoAmI:
81
89
  if e.code == 401:
82
90
  raise SenderError("key rejected (401)") from e
83
91
  raise SenderError(f"server returned {e.code}") from e
84
- except urllib.error.URLError as e:
85
- raise SenderError(str(e.reason)) from e
92
+ except (OSError, http.client.HTTPException) as e:
93
+ # URLError, but also a timeout or dropped connection mid-response, which
94
+ # urllib raises unwrapped.
95
+ raise SenderError(str(getattr(e, "reason", e))) from e
86
96
  return WhoAmI(
87
97
  email=data["email"],
88
98
  machine_label=data.get("machineLabel"),
@@ -101,8 +111,10 @@ def device_token(base: str, code: str) -> dict:
101
111
  return _request(url, None, "POST", {"code": code})
102
112
  except urllib.error.HTTPError as e:
103
113
  raise SenderError(f"server returned {e.code}") from e
104
- except urllib.error.URLError as e:
105
- raise SenderError(str(e.reason)) from e
114
+ except (OSError, http.client.HTTPException) as e:
115
+ # URLError, but also a timeout or dropped connection mid-response, which
116
+ # urllib raises unwrapped.
117
+ raise SenderError(str(getattr(e, "reason", e))) from e
106
118
 
107
119
 
108
120
  def fetch_thresholds(base: str, key: str, poll_sec: int) -> ThresholdCfg:
@@ -110,7 +122,7 @@ def fetch_thresholds(base: str, key: str, poll_sec: int) -> ThresholdCfg:
110
122
  url = f"{base.rstrip('/')}/config"
111
123
  try:
112
124
  data = _request(url, key, "GET", None)
113
- except (urllib.error.HTTPError, urllib.error.URLError) as e:
125
+ except (OSError, http.client.HTTPException) as e:
114
126
  reason = getattr(e, "code", None) or getattr(e, "reason", e)
115
127
  raise SenderError(str(reason)) from e
116
128
  return ThresholdCfg(
@@ -6,8 +6,8 @@ Any change here MUST land as a change to the behavioural vectors in
6
6
  last real input,
7
7
  - return-to-active is confirmed only after `min_activity` of sustained input,
8
8
  - periodic heartbeats bound crash/sleep damage,
9
- - downtime (reboot/suspend/clock-step) is reconciled via monotonic-vs-wall
10
- divergence and startup recover().
9
+ - downtime (reboot/suspend/clock-step) is reconciled via the wall-clock
10
+ gap and startup recover().
11
11
 
12
12
  Pure with respect to its return value: `step` takes an observation and
13
13
  returns events computed from no other input. All arithmetic is integer
@@ -34,6 +34,11 @@ logger = logging.getLogger(LOGGER_NAME)
34
34
  # of how often we poll. See the Rust comment for the bug this prevents.
35
35
  FRESH_INPUT_MS = 20_000
36
36
 
37
+ # While confirming a return to work, the longest pause between inputs that does
38
+ # not restart the clock. A floor under min_activity: at a 15 s poll, requiring
39
+ # every sample to fall within e.g. 5 s of an input drops genuine returns.
40
+ RETURN_GAP_MS = 30_000
41
+
37
42
  ACTIVE = "Active"
38
43
  IDLE = "Idle"
39
44
 
@@ -41,7 +46,7 @@ IDLE = "Idle"
41
46
  @dataclass
42
47
  class Thresholds:
43
48
  poll_ms: int = 15_000
44
- min_inactivity_ms: int = 10 * 60_000
49
+ min_inactivity_ms: int = 15 * 60_000
45
50
  min_activity_ms: int = 30_000
46
51
  heartbeat_ms: int = 5 * 60_000
47
52
 
@@ -61,7 +66,7 @@ class Persisted:
61
66
  # Timestamp of the most recently emitted event; a backwards clock must never
62
67
  # emit below it (spans are paired in ts order).
63
68
  last_emitted_ts: Optional[int] = None
64
- # Wall clock at the previous tick, differenced against monotonic elapsed time
69
+ # Wall clock at the previous tick, compared with the current one
65
70
  # to detect a suspend. Only meaningful within a single process run.
66
71
  last_seen_wall: Optional[int] = None
67
72
 
@@ -93,7 +98,7 @@ class StateMachine:
93
98
  used to force a legitimately earlier, correctly back-dated idle close
94
99
  forward to the last heartbeat's ts — which happened on essentially
95
100
  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
101
+ is shorter than min_inactivity_ms, so a heartbeat has always
97
102
  fired since the real last input by the time idle_long confirms.
98
103
  Observed in production: an active span's real last input was 14:01:33,
99
104
  confirmed idle at 14:11:42, and got reported as ending 14:07:11 (the
@@ -115,36 +120,39 @@ class StateMachine:
115
120
  return (not tick.locked) and tick.idle_ms < FRESH_INPUT_MS
116
121
 
117
122
  def last_evidence(self) -> Optional[int]:
118
- """The most recent local evidence the user was here: the later of
119
- heartbeat and last-active-time (last_active is written every poll)."""
120
- h = self.p.last_heartbeat
121
- a = self.p.last_active_time
122
- if h is not None and a is not None:
123
- return max(h, a)
124
- return h if h is not None else a
123
+ """The most recent local evidence the user was here. `last_active_time`
124
+ is written on every poll that saw input; a heartbeat only proves the
125
+ daemon was running (they continue through up to min_inactivity of no
126
+ input), so it is a fallback for when no input time was recorded."""
127
+ if self.p.last_active_time is not None:
128
+ return self.p.last_active_time
129
+ return self.p.last_heartbeat
125
130
 
126
- def reconcile_gap(self, gap_ms: int) -> list:
131
+ def reconcile_gap(self, gap_ms: int, last_input: Optional[int] = None) -> list:
127
132
  """Reconcile an unobserved interval (reboot/crash/suspend). Gaps below
128
133
  min_inactivity are absorbed; longer ones close the span back-dated to the
129
- last local evidence. Shared by recover() and in-loop detection so they
130
- cannot drift apart."""
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
- )
134
+ last local evidence, and drop any unconfirmed return: presence on one side
135
+ of an unobserved gap says nothing about the gap. `last_input` is the OS's
136
+ own last-input time, used when it is earlier than that evidence. Shared by
137
+ recover() and in-loop detection so they cannot drift apart."""
138
+ if gap_ms < self.t.min_inactivity_ms:
139
+ return []
140
+ self.p.pending_active_since = None
141
+ if self.p.reported_state != ACTIVE:
142
+ logger.debug("reconcile_gap: gap_ms=%d while idle -> pending return dropped", gap_ms)
136
143
  return []
137
144
  anchor = self.last_evidence()
138
145
  if anchor is None:
139
146
  logger.debug("reconcile_gap: gap_ms=%d but no last evidence recorded -> nothing to anchor to", gap_ms)
140
147
  return []
148
+ if last_input is not None:
149
+ anchor = min(anchor, last_input)
141
150
  logger.debug(
142
151
  "reconcile_gap: gap_ms=%d >= min_inactivity_ms=%d -> closing span at anchor=%d "
143
152
  "(last_heartbeat=%s last_active_time=%s)",
144
153
  gap_ms, self.t.min_inactivity_ms, anchor, self.p.last_heartbeat, self.p.last_active_time,
145
154
  )
146
155
  self.p.reported_state = IDLE
147
- self.p.pending_active_since = None
148
156
  return [self.emit(anchor, EventKind.IDLE)]
149
157
 
150
158
  def recover(self, now: int) -> list:
@@ -171,25 +179,24 @@ class StateMachine:
171
179
  tick.now, tick.idle_ms, tick.locked, tick.mono_elapsed_ms, self.p.reported_state,
172
180
  )
173
181
 
174
- # Downtime the daemon slept through: wall advances across a suspend while
175
- # the monotonic clock does not, so the difference isolates the frozen
176
- # interval. Runs BEFORE state handling (fresh input on wake must not
177
- # absorb the suspend). Backwards divergence is a clock correction, ignored.
178
- if tick.mono_elapsed_ms is not None:
179
- seen = self.p.last_seen_wall if self.p.last_seen_wall is not None else tick.now
180
- wall_gap = tick.now - seen
181
- divergence = wall_gap - tick.mono_elapsed_ms
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
- )
187
- out.extend(self.reconcile_gap(divergence))
188
- elif divergence < 0:
182
+ # Downtime the daemon slept through, measured in wall-clock time since the
183
+ # previous poll and since the last recorded input (which also catches an
184
+ # idle period whose end fell between two polls). Deliberately not wall-minus-monotonic: Windows'
185
+ # monotonic clock keeps running across a suspend, so that never fired
186
+ # there. Runs BEFORE state handling (fresh input on wake must not absorb
187
+ # the suspend). A backwards gap is a clock correction, ignored. The first
188
+ # tick of a process (mono None) was already reconciled by recover().
189
+ if tick.mono_elapsed_ms is not None and self.p.last_seen_wall is not None:
190
+ wall_gap = tick.now - self.p.last_seen_wall
191
+ gap = wall_gap
192
+ if wall_gap >= 0 and self.p.last_active_time is not None:
193
+ gap = max(gap, tick.now - self.p.last_active_time)
194
+ if gap >= self.t.min_inactivity_ms:
189
195
  logger.debug(
190
- "backwards clock divergence ignored: wall_gap=%d mono_elapsed_ms=%d divergence=%d",
191
- wall_gap, tick.mono_elapsed_ms, divergence,
196
+ "unobserved gap: gap=%d wall_gap=%d mono_elapsed_ms=%d -> reconciling",
197
+ gap, wall_gap, tick.mono_elapsed_ms,
192
198
  )
199
+ out.extend(self.reconcile_gap(gap, tick.now - tick.idle_ms))
193
200
  self.p.last_seen_wall = tick.now
194
201
 
195
202
  fresh = self.input_fresh(tick)
@@ -229,24 +236,26 @@ class StateMachine:
229
236
  out.append(self.emit_heartbeat(tick.now))
230
237
  self.p.last_heartbeat = tick.now
231
238
  else: # IDLE
232
- # "Activity persisted for min_activity" must tolerate short pauses.
233
- # The claim dies only when idle reaches min_activity itself; below
234
- # that the accumulator keeps running.
235
- if tick.locked or tick.idle_ms >= self.t.min_activity_ms:
239
+ # "Activity persisted for min_activity" must tolerate short pauses and
240
+ # the poll interval. Sustained means input at both ends of the period,
241
+ # so a single touch can never confirm by merely growing old.
242
+ return_gap_ms = max(self.t.min_activity_ms, RETURN_GAP_MS)
243
+ if tick.locked or tick.idle_ms >= return_gap_ms:
236
244
  if self.p.pending_active_since is not None:
237
245
  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,
246
+ "idle-branch: pending activation dropped (locked=%s idle_ms=%d return_gap_ms=%d)",
247
+ tick.locked, tick.idle_ms, return_gap_ms,
240
248
  )
241
249
  self.p.pending_active_since = None
242
250
  else:
251
+ last_input = tick.now - tick.idle_ms
243
252
  # Start only on genuinely fresh input; once started, short pauses
244
253
  # no longer reset it. Anchor to the real resume moment.
245
254
  if fresh and self.p.pending_active_since is None:
246
- self.p.pending_active_since = tick.now - tick.idle_ms
255
+ self.p.pending_active_since = last_input
247
256
  logger.debug("idle-branch: pending activation started, anchor=%d", self.p.pending_active_since)
248
257
  if self.p.pending_active_since is not None:
249
- sustained_ms = tick.now - self.p.pending_active_since
258
+ sustained_ms = last_input - self.p.pending_active_since
250
259
  logger.debug(
251
260
  "idle-branch: pending activation sustained_ms=%d min_activity_ms=%d",
252
261
  sustained_ms, self.t.min_activity_ms,
@@ -14,7 +14,7 @@ def test_round_trip_and_defaults(tmp_path):
14
14
  assert back.account_id == "acc-1"
15
15
  assert back.machine_id is None
16
16
  assert back.thresholds.poll_sec == 15
17
- assert back.thresholds.min_inactivity_sec == 600
17
+ assert back.thresholds.min_inactivity_sec == 900
18
18
 
19
19
 
20
20
  def test_absent_optionals_are_omitted(tmp_path):
@@ -38,6 +38,6 @@ def test_permissions_restricted_on_posix(tmp_path):
38
38
  def test_thresholds_to_ms():
39
39
  t = ThresholdCfg().to_thresholds()
40
40
  assert t.poll_ms == 15_000
41
- assert t.min_inactivity_ms == 600_000
41
+ assert t.min_inactivity_ms == 900_000
42
42
  assert t.min_activity_ms == 30_000
43
43
  assert t.heartbeat_ms == 300_000
@@ -1,4 +1,4 @@
1
- """Behavioural regression tests: the 24 hand-verified vectors, run through the
1
+ """Behavioural regression tests: the hand-verified vectors, run through the
2
2
  real state machine.
3
3
 
4
4
  These began as the language-neutral conformance vectors that validated the
@@ -79,4 +79,4 @@ def test_vector(path: pathlib.Path):
79
79
 
80
80
 
81
81
  def test_vectors_present():
82
- assert len(VECTORS) >= 24, "expected the full seed vector set"
82
+ assert len(VECTORS) >= 31, "expected the full seed vector set"
@@ -1,3 +1,5 @@
1
+ import pytest
2
+
1
3
  import flexitracker.sender as sender
2
4
 
3
5
 
@@ -48,3 +50,19 @@ def test_whoami_maps_camelcase(monkeypatch):
48
50
  assert w.email == "a@b.c"
49
51
  assert w.machine_label == "Work laptop"
50
52
  assert w.active is True
53
+
54
+
55
+ def test_request_has_a_timeout(monkeypatch):
56
+ seen = {}
57
+
58
+ def fake_urlopen(req, timeout=None):
59
+ seen["timeout"] = timeout
60
+ raise TimeoutError("timed out")
61
+
62
+ monkeypatch.setattr(sender.urllib.request, "urlopen", fake_urlopen)
63
+ batch = {"batch_seq": 1, "events": [], "machine": None}
64
+ with pytest.raises(sender.SenderError, match="timed out"):
65
+ sender.post_batch("https://x.example", "KEY", batch)
66
+ with pytest.raises(sender.SenderError):
67
+ sender.fetch_thresholds("https://x.example", "KEY", 15)
68
+ assert seen["timeout"] == sender.REQUEST_TIMEOUT_S
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "activation_is_debounced_then_backdated",
3
3
  "description": "Active is confirmed only after min_activity and back-dated to when input started.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 1000, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 41000, "idle_ms": 0 }
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "idle_is_backdated_to_last_input",
3
3
  "description": "Confirmed idle is back-dated to the last input, not the observation time.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 0, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 60000, "idle_ms": 0 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "short_break_is_absorbed",
3
3
  "description": "Inactivity below min_inactivity keeps the active span continuous with no event.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 0, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 40000, "idle_ms": 0 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "brief_activity_during_idle_is_debounced",
3
3
  "description": "A sub-min_activity blip while idle must not report active.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 100000, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 110000, "idle_ms": 60000 }
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "sustained_return_reports_active_backdated",
3
3
  "description": "A sustained return from idle reports active back-dated to when input resumed.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "initial": { "reported_state": "Idle" },
5
6
  "steps": [
6
7
  { "op": "tick", "now": 100000, "idle_ms": 0 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "heartbeats_emitted_while_active",
3
3
  "description": "A heartbeat is emitted once one heartbeat interval has elapsed while active.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 0, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 40000, "idle_ms": 0 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "recover_after_sudden_shutdown",
3
3
  "description": "Startup recovery of a long downtime closes the span back-dated to the last heartbeat.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "initial": { "reported_state": "Active", "last_heartbeat": 57600000 },
5
6
  "steps": [
6
7
  { "op": "recover", "now": 115200000 }
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "locked_session_goes_idle",
3
3
  "description": "A locked session goes idle, back-dated to the last real input, not the lock moment.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 0, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 40000, "idle_ms": 0 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "recover_anchors_to_the_later_evidence_not_the_heartbeat",
3
3
  "description": "Recovery anchors to the later of last heartbeat and last active time.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "initial": { "reported_state": "Active", "last_heartbeat": 57600000, "last_active_time": 57840000 },
5
6
  "steps": [
6
7
  { "op": "recover", "now": 115200000 }
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "suspend_longer_than_min_inactivity_closes_the_span",
3
3
  "description": "A suspend longer than min_inactivity (wall vs monotonic divergence) closes the span at the last local evidence.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 0, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 40000, "idle_ms": 0 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "suspend_is_reconciled_even_when_user_types_immediately_on_wake",
3
3
  "description": "Fresh input on wake (idle_ms small) must not absorb the suspend as working time.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 0, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 40000, "idle_ms": 0 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "suspend_shorter_than_min_inactivity_is_absorbed",
3
3
  "description": "A suspend shorter than min_inactivity is absorbed, as a brief reboot is.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 0, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 40000, "idle_ms": 0 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "backwards_clock_step_closes_nothing_and_never_emits_below_the_watermark",
3
3
  "description": "A backwards clock is a correction, not downtime; a later idle is clamped to the emit watermark.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 600000, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 640000, "idle_ms": 0 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "small_forward_clock_step_is_absorbed",
3
3
  "description": "A small forward clock step (NTP correction) below min_inactivity is absorbed.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 0, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 40000, "idle_ms": 0 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "startup_recover_and_in_loop_reconciliation_agree",
3
3
  "description": "Startup recover from an active span closes it identically to in-loop reconciliation (compare with vector 10).",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 0, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 40000, "idle_ms": 0 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "reconciliation_after_an_explicit_close_does_not_double_close",
3
3
  "description": "An explicit idle close followed by a later suspend must not produce a second idle.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 0, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 40000, "idle_ms": 0 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "a_short_reading_pause_does_not_restart_the_return_to_work_clock",
3
3
  "description": "Short pauses while returning to work must not restart the min_activity accumulator.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "initial": { "reported_state": "Idle" },
5
6
  "steps": [
6
7
  { "op": "tick", "now": 15000, "idle_ms": 10000 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "presence_must_still_be_sustained_to_confirm",
3
3
  "description": "A single touch must not confirm a return to work.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "initial": { "reported_state": "Idle" },
5
6
  "steps": [
6
7
  { "op": "tick", "now": 15000, "idle_ms": 15000 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "a_gap_of_min_activity_kills_the_pending_return",
3
3
  "description": "A gap of min_activity clears the pending return; a fresh poll then starts a new clock.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "initial": { "reported_state": "Idle" },
5
6
  "steps": [
6
7
  { "op": "tick", "now": 15000, "idle_ms": 5000 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "idle_backdating_is_exact_not_poll_quantised",
3
3
  "description": "Idle is back-dated to the true stop time (now - idle_ms), not the last fresh poll.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 0, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 40000, "idle_ms": 0 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "min_inactivity_exact_boundary_closes",
3
3
  "description": "idle_ms exactly equal to min_inactivity closes the span (>= boundary).",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 0, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 40000, "idle_ms": 0 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "large_timestamps_within_i64",
3
3
  "description": "Timestamps near the i64 range must pass through identically (Python bigint vs Rust i64).",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "initial": { "reported_state": "Active", "last_heartbeat": 9000000000000000000 },
5
6
  "steps": [
6
7
  { "op": "recover", "now": 9000000000000600000 }
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "all_emitted_kinds_serialize_lowercase",
3
3
  "description": "The three emitted kinds (active, idle, heartbeat) must serialize lowercase and identically across implementations.",
4
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "steps": [
5
6
  { "op": "tick", "now": 0, "idle_ms": 0 },
6
7
  { "op": "tick", "now": 40000, "idle_ms": 0 },
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "heartbeat_does_not_clamp_a_later_idle_backdate",
3
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
+ "thresholds": { "min_inactivity_ms": 600000 },
4
5
  "initial": { "reported_state": "Active", "last_active_time": 0, "last_emitted_ts": 0 },
5
6
  "steps": [
6
7
  { "op": "tick", "now": 300000, "idle_ms": 300000 },
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "suspend_is_detected_when_the_monotonic_clock_keeps_running",
3
+ "description": "Windows: the monotonic clock advances across suspend, so wall and monotonic agree. Fresh input on wake must still not absorb it.",
4
+ "steps": [
5
+ {"op": "tick", "now": 0, "idle_ms": 0},
6
+ {"op": "tick", "now": 40000, "idle_ms": 0, "mono_elapsed_ms": 40000},
7
+ {"op": "tick", "now": 10800000, "idle_ms": 0, "mono_elapsed_ms": 10760000}
8
+ ],
9
+ "expected": [
10
+ {"kind": "active", "ts": 0},
11
+ {"kind": "idle", "ts": 40000}
12
+ ],
13
+ "expected_final": {"reported_state": "Idle", "pending_active_since": 10800000}
14
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "long_downtime_drops_the_pending_return",
3
+ "description": "A return still unconfirmed when the machine went down must not be confirmed from before the downtime (Friday touch, Monday start).",
4
+ "initial": {"reported_state": "Idle", "last_active_time": 1000000, "last_seen_wall": 1000000, "pending_active_since": 1000000},
5
+ "steps": [
6
+ {"op": "recover", "now": 200000000},
7
+ {"op": "tick", "now": 200000000, "idle_ms": 0},
8
+ {"op": "tick", "now": 200040000, "idle_ms": 0, "mono_elapsed_ms": 40000}
9
+ ],
10
+ "expected": [
11
+ {"kind": "active", "ts": 200000000}
12
+ ],
13
+ "expected_final": {"reported_state": "Active"}
14
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "return_to_work_tolerates_the_poll_interval",
3
+ "description": "With min_activity below the poll interval, inputs at two separate moments confirm the return even though no two samples fall within min_activity of an input.",
4
+ "thresholds": {"min_activity_ms": 5000},
5
+ "initial": {"reported_state": "Idle"},
6
+ "steps": [
7
+ {"op": "tick", "now": 100000, "idle_ms": 0},
8
+ {"op": "tick", "now": 115000, "idle_ms": 5500, "mono_elapsed_ms": 15000}
9
+ ],
10
+ "expected": [
11
+ {"kind": "active", "ts": 100000}
12
+ ],
13
+ "expected_final": {"reported_state": "Active"}
14
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "a_single_touch_never_confirms_by_growing_old",
3
+ "description": "One input seen on two consecutive polls is still one input.",
4
+ "thresholds": {"min_activity_ms": 5000},
5
+ "initial": {"reported_state": "Idle"},
6
+ "steps": [
7
+ {"op": "tick", "now": 100000, "idle_ms": 0},
8
+ {"op": "tick", "now": 115000, "idle_ms": 15000, "mono_elapsed_ms": 15000},
9
+ {"op": "tick", "now": 130000, "idle_ms": 30000, "mono_elapsed_ms": 15000}
10
+ ],
11
+ "expected": [],
12
+ "expected_final": {"reported_state": "Idle", "pending_active_since": null}
13
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "default_idle_threshold_is_15_minutes",
3
+ "description": "Default thresholds: 14 minutes without input stays active; 15 closes, back-dated past heartbeats.",
4
+ "steps": [
5
+ {"op": "tick", "now": 0, "idle_ms": 0},
6
+ {"op": "tick", "now": 40000, "idle_ms": 0, "mono_elapsed_ms": 40000},
7
+ {"op": "tick", "now": 880000, "idle_ms": 840000, "mono_elapsed_ms": 15000},
8
+ {"op": "tick", "now": 940000, "idle_ms": 900000, "mono_elapsed_ms": 15000}
9
+ ],
10
+ "expected": [
11
+ {"kind": "active", "ts": 0},
12
+ {"kind": "heartbeat", "ts": 880000},
13
+ {"kind": "idle", "ts": 40000}
14
+ ],
15
+ "expected_final": {"reported_state": "Idle"}
16
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "idle_period_ending_between_polls_closes",
3
+ "description": "Input resumes just after the threshold, between two polls, so no sample ever shows it: the time since the last recorded input does.",
4
+ "steps": [
5
+ {"op": "tick", "now": 0, "idle_ms": 0},
6
+ {"op": "tick", "now": 40000, "idle_ms": 0, "mono_elapsed_ms": 40000},
7
+ {"op": "tick", "now": 930000, "idle_ms": 890000, "mono_elapsed_ms": 15000},
8
+ {"op": "tick", "now": 945000, "idle_ms": 1000, "mono_elapsed_ms": 15000}
9
+ ],
10
+ "expected": [
11
+ {"kind": "active", "ts": 0},
12
+ {"kind": "heartbeat", "ts": 930000},
13
+ {"kind": "idle", "ts": 40000}
14
+ ],
15
+ "expected_final": {"reported_state": "Idle", "pending_active_since": 944000}
16
+ }
@@ -0,0 +1,127 @@
1
+ """Diagnostic that found the TRUE byte offset of SessionFlags (lock state)
2
+ inside the WTSINFOEXW buffer returned by WTSQuerySessionInformationW. Windows
3
+ only. Standalone -- does not import `flexitracker`, deliberately, so it
4
+ can't share whatever bug it's used to find.
5
+
6
+ RESOLVED (2026-09-29): offset 16, not the originally-shipped 12. Confirmed
7
+ by real output from this tool, two ways at once: [8] exactly matched an
8
+ independently fetched WTSGetActiveConsoleSessionId() every sample (pinning
9
+ SessionId's real offset), and [16] was the one that actually flipped 1<->0
10
+ in lockstep with real Win+L lock/unlock, matching the documented
11
+ WTS_SESSIONSTATE_UNLOCK=1 / _LOCK=0. [12] (the original offset) sat at a
12
+ constant 0 throughout -- SessionState (WTSActive), not SessionFlags. Fixed
13
+ in `idle.py`; kept here for the next time this class of bug needs
14
+ re-verifying, on a different Windows build or architecture.
15
+
16
+ The first run of this script also needed a fix of its own:
17
+ WTSGetActiveConsoleSessionId is exported by Kernel32.dll, not Wtsapi32.dll,
18
+ despite the WTS-prefixed name -- calling it on the wtsapi32 handle raised
19
+ `AttributeError: function 'WTSGetActiveConsoleSessionId' not found`. That
20
+ bug was confirmed NOT present in the production code (`idle.py` only calls
21
+ WTSQuerySessionInformationW/WTSFreeMemory on wtsapi32, both genuinely
22
+ exported there, and GetLastInputInfo/GetTickCount on the correct
23
+ user32/kernel32) -- it only existed here, in this script, and is fixed
24
+ below.
25
+
26
+ Why this exists: `windows_session_locked()` in `flexitracker/idle.py` used
27
+ offset 12 (reasoned from the documented struct field order, assuming no
28
+ padding). In production it always read "locked" -- see CLAUDE.md. The
29
+ explanation, worked out from Microsoft's own struct definitions and then
30
+ confirmed by this script's actual output: WTSINFOEX_LEVEL1_W contains
31
+ several 8-byte LARGE_INTEGER fields, which gives the whole struct (and the
32
+ union wrapping it) 8-byte alignment, pushing the union 4 bytes later than
33
+ offset 12 assumed -- landing on SessionState (usually 0 = WTSActive)
34
+ instead of SessionFlags, and 0 also happens to mean WTS_SESSIONSTATE_LOCK.
35
+ Reasoning alone wasn't trusted a second time after the first offset guess
36
+ shipped wrong -- this script measured it instead.
37
+
38
+ Usage (from daemon-py/):
39
+ uv run tools/wts_lock_diagnostic.py [poll_seconds] [total_seconds]
40
+
41
+ Run it, then deliberately lock (Win+L) and unlock the screen a few times
42
+ while it's running (default: every 2s for 3 minutes -- plenty of time for a
43
+ few lock/unlock cycles). Send back the full output.
44
+
45
+ How to read it:
46
+ - `console_session_id` is fetched independently (WTSGetActiveConsoleSessionId)
47
+ and is NOT the value we're trying to find -- it's a known-correct anchor.
48
+ Whichever [offset]=value in the dump EXACTLY MATCHES it is the real
49
+ SessionId field. SessionState is 4 bytes after that, SessionFlags 4
50
+ bytes after that -- this pins down the whole layout without having to
51
+ trust anyone's reasoning about padding, including the note above.
52
+ - Independently, whichever offset's value changes exactly when you lock
53
+ vs. unlock is SessionFlags by direct observation, regardless of the
54
+ SessionId cross-check. The two should agree; if they don't, trust the
55
+ lock/unlock toggle -- it's the more direct measurement.
56
+ """
57
+
58
+ from __future__ import annotations
59
+
60
+ import sys
61
+ import time
62
+
63
+ WTS_CURRENT_SERVER_HANDLE = 0
64
+ WTS_CURRENT_SESSION = 0xFFFFFFFF
65
+ WTS_SESSION_INFO_EX = 25
66
+
67
+
68
+ def dump_once(wtsapi32, kernel32, ctypes) -> None:
69
+ buf = ctypes.c_void_p()
70
+ length = ctypes.c_uint()
71
+ ok = wtsapi32.WTSQuerySessionInformationW(
72
+ WTS_CURRENT_SERVER_HANDLE,
73
+ ctypes.c_uint(WTS_CURRENT_SESSION),
74
+ WTS_SESSION_INFO_EX,
75
+ ctypes.byref(buf),
76
+ ctypes.byref(length),
77
+ )
78
+ ts = time.strftime("%Y-%m-%d %H:%M:%S")
79
+ if not ok or not buf.value:
80
+ print(f"{ts} WTSQuerySessionInformationW FAILED (ok={ok}, len={length.value})")
81
+ return
82
+ try:
83
+ # WTSGetActiveConsoleSessionId is exported by Kernel32.dll, not
84
+ # Wtsapi32.dll, despite the WTS-prefixed name -- calling it on the
85
+ # wtsapi32 handle raised AttributeError the first time this ran.
86
+ console_session_id = kernel32.WTSGetActiveConsoleSessionId()
87
+ n = min(length.value, 64)
88
+ raw = ctypes.string_at(buf.value, n)
89
+ hex_str = " ".join(f"{b:02x}" for b in raw)
90
+ print(f"{ts} console_session_id={console_session_id} length={length.value} bytes={hex_str}")
91
+ # Decode straight from the byte buffer already dumped above, rather
92
+ # than a second ctypes.cast over raw pointer arithmetic on buf.value
93
+ # -- one less thing that could be wrong in a script whose whole job
94
+ # is to be a trustworthy ground truth.
95
+ fields = [
96
+ f"[{off:2d}]={int.from_bytes(raw[off:off + 4], 'little', signed=True)}"
97
+ for off in range(0, n - 3, 4)
98
+ ]
99
+ print(" " + " ".join(fields))
100
+ finally:
101
+ wtsapi32.WTSFreeMemory(buf)
102
+
103
+
104
+ def main() -> None:
105
+ if sys.platform != "win32":
106
+ raise SystemExit("This diagnostic only runs on Windows.")
107
+
108
+ import ctypes # local: importing this on non-Windows is fine, but
109
+
110
+ wtsapi32 = ctypes.windll.wtsapi32 # these two lines are Windows-only
111
+ kernel32 = ctypes.windll.kernel32
112
+ kernel32.WTSGetActiveConsoleSessionId.restype = ctypes.c_uint32
113
+
114
+ interval = float(sys.argv[1]) if len(sys.argv) > 1 else 2.0
115
+ total = float(sys.argv[2]) if len(sys.argv) > 2 else 180.0
116
+ print(f"Polling every {interval}s for {total}s.")
117
+ print("Lock (Win+L) and unlock the screen a few times while this runs, then")
118
+ print("send back the full output (or at least the rows around each toggle).")
119
+ print()
120
+ deadline = time.monotonic() + total
121
+ while time.monotonic() < deadline:
122
+ dump_once(wtsapi32, kernel32, ctypes)
123
+ time.sleep(interval)
124
+
125
+
126
+ if __name__ == "__main__":
127
+ main()
File without changes
File without changes
File without changes
File without changes