DEV Community

Cover image for Why Modern Screen Time is Mathematically Flawed: Building a Local-First Cross-Device Interval Engine in Python and Kotlin
Aditya
Aditya

Posted on Edited on Originally published at aditya8242.github.io AI-assisted

Why Modern Screen Time is Mathematically Flawed: Building a Local-First Cross-Device Interval Engine in Python and Kotlin

Most screen time tools suffer from a fundamental mathematical flaw: they compute total screen exposure by summing independent device scalars rather than calculating the union of overlapping time intervals.

If you spend two hours working on a laptop while occasionally responding to messages on your phone for 30 minutes, standard digital wellbeing trackers report 2 hours and 30 minutes of screen time. Your biological eyes were exposed to displays for exactly 2 hours, with 30 minutes spent in a state of multi-device fragmentation ("second-screening").

To solve this, I built OmniScreen: an open-source, local-first engine for Windows and Android that synchronizes active screen sessions over your local Wi-Fi network and computes the mathematical interval union with zero cloud servers and zero telemetry.

Here is a breakdown of the mathematics, the local-first architecture, and the systems engineering behind it.


1. The Mathematical Problem: Scalar Sum vs. Interval Union

Every operating system measures screen activity as discrete active sessions:

Session S = [t_start, t_end]
Enter fullscreen mode Exit fullscreen mode

When aggregating screen time across multiple devices, existing digital wellbeing dashboards compute the naive sum:

Raw Exposure = Duration(Device 1) + Duration(Device 2) + ... + Duration(Device N)
Enter fullscreen mode Exit fullscreen mode

When multiple devices are active simultaneously (for example, your laptop display is active while you check notifications on your phone), this naive scalar addition double-counts the overlapping period.

The Correct Formulation: Interval Union

True screen exposure is the measure of the mathematical union of all session intervals across all devices along a single real timeline:

True Exposure = Measure( Union of all [t_start, t_end] across Device 1 .. N )
Enter fullscreen mode Exit fullscreen mode

Where overlapping intervals are merged into continuous spans so that 1 minute of real wall-clock time never counts as more than 1 minute of physical screen exposure.

From this, we can derive the exact duration of concurrent multi-screening:

Second-Screening Duration = Raw Exposure - True Exposure
Enter fullscreen mode Exit fullscreen mode

We also compute an Attention Fragmentation Index (or Second-Screening Index, SSI):

Attention Fragmentation Index (SSI) = ( Second-Screening Duration / True Exposure ) * 100%
Enter fullscreen mode Exit fullscreen mode

A high SSI indicates fragmented cognitive attention, where your focus was repeatedly split across multiple glowing displays simultaneously.


2. Implementing the Interval Union in O(N log N)

To compute the interval union efficiently on a low-power local background daemon, we use a sorted sweep-line interval merge algorithm:

def calculate_interval_union(sessions: list[tuple[float, float]]) -> float:
    """
    Computes the total non-overlapping duration from a list of [start_ts, end_ts] intervals.
    Time Complexity: O(N log N) due to sorting.
    Space Complexity: O(N) to store merged intervals.
    """
    if not sessions:
        return 0.0

    # 1. Sort intervals by start timestamp
    sorted_intervals = sorted(sessions, key=lambda x: x[0])

    merged = []
    current_start, current_end = sorted_intervals[0]

    for start, end in sorted_intervals[1:]:
        if start <= current_end:
            # Overlapping or contiguous interval: extend the current boundary
            current_end = max(current_end, end)
        else:
            # Disjoint interval: commit previous interval and advance
            merged.append((current_start, current_end))
            current_start, current_end = start, end

    merged.append((current_start, current_end))

    # 2. Sum the durations of disjoint merged intervals
    return sum(end - start for start, end in merged)
Enter fullscreen mode Exit fullscreen mode

Running this on thousands of raw session intervals takes less than 2 milliseconds on standard hardware, eliminating any CPU overhead on the host machine.


3. System Architecture: Local-First with SQLite WAL

Screen time data is among the most sensitive personal telemetry possible: it records the exact minute you wake up, every application you switch to, and when you go to bed. Storing this on third-party cloud servers poses unacceptable privacy risks.

OmniScreen is architected strictly as a local-first system:

+-------------------------------------------------------------+
|                      Local Wi-Fi Network                    |
|                                                             |
|   +-------------------+              +------------------+   |
|   |   Android Agent   |  UDP Probe   |  Windows PC Hub  |   |
|   |  (Kotlin Sensor)  | -----------> | (FastAPI+SQLite) |   |
|   |                   | <----------- |                  |   |
|   |                   |  HTTP Sync   |                  |   |
|   +-------------------+              +------------------+   |
|                                                |            |
|                                                v            |
|                                         +--------------+    |
|                                         | SQLite (WAL) |    |
|                                         | Local Storage|    |
|                                         +--------------+    |
+-------------------------------------------------------------+
Enter fullscreen mode Exit fullscreen mode

Database Concurrency

The local PC hub uses SQLite with Write-Ahead Logging (WAL) enabled:

conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA busy_timeout=15000")
Enter fullscreen mode Exit fullscreen mode
  • WAL mode allows concurrent readers (such as the web dashboard querying metrics) while background agent syncs write incoming sessions without locking the database file.
  • All administrative and mutating endpoints (/api/device/delete, /api/device/rename, /api/tv/add) enforce loopback checks (require_localhost), ensuring external network requests cannot modify device records even on an open Wi-Fi network.

4. Native Device Sensors

Windows Win32 Agent

The desktop background agent runs quietly in the Windows System Tray with zero terminal windows:

  • Uses ctypes to call Win32 APIs: GetForegroundWindow(), GetWindowTextW(), and GetWindowThreadProcessId().
  • Implements tick-gap detection: rather than assuming continuous usage, the polling loop calculates elapsed wall-clock time between iterations. If the system sleeps, hibernates, or locks, the gap is automatically detected and excluded from active session recording.

Android Companion Sensor

On Android, query polling drains battery. Instead, OmniScreen uses native Kotlin with UsageStatsManager.queryEvents():

  • Queries raw OS events (UsageEvents.Event.ACTIVITY_RESUMED and UsageEvents.Event.ACTIVITY_PAUSED).
  • Clamps event boundaries strictly to local midnight (00:00:00) to prevent multi-day leakage.
  • Filters out system launchers and navigation overlays, tracking only genuine foreground applications.

5. Local Wi-Fi Auto-Discovery: Eliminating Cloud Relays

To allow the Android app to communicate with the PC hub without requiring static IP configurations or central accounts, OmniScreen implements a dual-discovery protocol:

  1. UDP Broadcast Auto-Discovery:
    • The Android client broadcasts a lightweight discovery payload over UDP port 8766.
    • The PC hub listens on 0.0.0.0:8766 and responds with its local LAN IP address and HTTP port (8765).
    • The Android client parses the response and initiates automated local syncing.
  2. 1-Tap QR Fallback:
    • The desktop dashboard generates a local QR code encoding omniscreen://pair?host=<LAN_IP>:8765.
    • Scanning the QR code with the phone camera deep-links directly into the Android app and establishes pairing in less than 2 seconds.

6. Open Source & Key Takeaways

Building OmniScreen reinforced several systems engineering principles:

  1. Always question basic domain math: The double-counting error in digital wellbeing metrics had existed unchallenged simply because naive summation is easier to compute than interval unions.
  2. Local-first is performant and viable: Complex multi-device synchronization does not require cloud infrastructure or subscriptions. Local networks and SQLite WAL handle modern workloads effortlessly with zero latency.
  3. Security through minimal surface area: By refusing external cloud relays, all data remains on your physical hardware under your control.

OmniScreen is 100% free and open source under the GNU General Public License v3.0 (GPL-3.0).

Contributions, feedback on the interval math, and hardware compatibility reports are welcome on the GitHub issue tracker.

Top comments (0)