Engagement tracking — system logic
How EduSpaze measures the time a pupil spends in a connected app when there is no logout to observe. This is the reference for the code in lib/engagement/, the launcher, the vendor telemetry API and the school/parent views. Last updated 2026-09-02.
1. The problem
A pupil signs in (locally, through the launcher, or via the school's SSO), opens an app, and then simply closes the tab, walks away, or opens the app again ten minutes later. We see the start. We never see an end, and we may see several starts for what a teacher would call one sitting. So the design stops looking for a logout and reconstructs sessions from activity.
2. Signals
| Signal | Source | Surface | Carries |
|---|---|---|---|
LAUNCH | Launcher "Open" button (launchApp) | LAUNCHER | pupil, app, time |
PING | Heartbeat from a page EduSpaze owns: the launcher (app = none) and the in-platform app frame | LAUNCHER / APP_FRAME | pupil, app, time |
END | pagehide beacon when the tab closes or navigates away | LAUNCHER / APP_FRAME | pupil, app, time |
PING / END | Vendor telemetry API POST /api/vendor/v1/heartbeat | VENDOR | tenant, pseudonymous subject, time |
| Completed session | Vendor telemetry API POST /api/vendor/v1/sessions | — | tenant, subject, start, end |
Every signal is time-only. Nothing about what the pupil did, wrote, scored or saw is ever sent or stored, which keeps the measurement inside the parent module's "when and how much, never what" rule.
The heartbeat client (components/engagement/heartbeat.tsx) pings on mount, then every heartbeatIntervalSeconds while the tab is visible (Page Visibility API). A hidden tab stops pinging; it does not send an end. The end beacon is best effort, so the server never relies on it alone.
3. Sessionisation
Raw signals land in StudentActivityPing; the sessioniser (recordActivity) folds each one into EngagementSession in the same transaction. Rules, each covered by tests/engagement.test.ts:
- Session key = tenant + pupil + app. Sign-ins are not sessions. Logging in is not an engagement event; opening an app is.
- Continuation. A signal that arrives within
engagementInactivityMinutesof the open session's last activity extends that session. A repeat launch inside the window incrementslaunchCounton the same row instead of opening a second session. This is the double-counting guard: three sign-ins and two "Open" clicks in ten minutes are one session. - Gap closes. A gap longer than the cutoff starts a new session. Nothing is written to close the old one; "open" is a property of recency (
lastActivityAt ≥ now − cutoff), not ofclosedAt. - Launch-only. A launch with no further signal is worth
launchOnlyMinutes(endedAt = startedAt + launchOnlyMinutes), labelledLAUNCH_ONLY. The first ping upgrades the row toHEARTBEAT; a vendor ping upgrades it toVENDOR_HEARTBEAT. - Presumed end. A ping sets
endedAt = now + heartbeatIntervalSeconds(the pupil is presumed present for one interval). AnENDpinsendedAtto now and setsclosedAt— but a signal inside the cutoff resumes that same session and clears the pin. Closing a tab and reopening the app a minute later is one sitting, not two. - Ping de-duplication. Two pings from the same surface for the same pupil + app closer than 15 seconds are one ping (retries, duplicate tabs); the second is dropped before it touches a session. A vendor ping and our own ping are different observers and both count — the interval union (§4) makes sure they still describe one minute, not two.
4. Counting minutes without double counting
Minutes are never read off session rows directly. For any pupil + app + window, engagementIntervals collects:
- vendor-reported sessions (
VendorSessionReport) and sessions from the vendor's own heartbeat (VENDOR_HEARTBEAT), source vendor, - sessions from EduSpaze's own heartbeat (
HEARTBEAT), source heartbeat, - launch-only sessions (source launch-only) — always, since 2026-10-22,
and passes them through mergeIntervals: sort, union anything that overlaps or touches, keep the most reliable source on the merged block (vendor > heartbeat > launch-only). Minutes are the length of the union inside the window. A minute described by a vendor report, by our heartbeat and by a repeat launch is still one minute.
Vendor batch posts are idempotent as well: VendorSessionReport is unique on tenant + vendor + subject + startedAt, so a re-sent batch is reported as duplicates, not counted twice.
5. Confidence — how the time is known
Every block of time says how it is known, the same way for a school and a parent (components/parent/heatmap.tsx, CONFIDENCE_LABEL in lib/engagement/report.ts). Which tier an app's time falls in follows how it opens (docs/integration/app-access.md): inside EduSpaze it is measured; in a tab of its own it is assumed, unless the app reports it.
| Tier | Meaning | Timeline (school and parent) | School engagement list |
|---|---|---|---|
| Reported by the app | the vendor posted the session, or its own heartbeat | filled block, in the day's band colour | badge "Reported by the app" |
| Measured inside EduSpaze | our heartbeat while the app was open inside EduSpaze (active time only; idle kept apart, §9) | filled block, band colour, solid outline | badge "Measured inside EduSpaze" |
| Assumed | an open with nothing after it — the app opened in a tab of its own | hatched, pale, dashed outline, never banded; the hover says "assumed" | counted at the school's assumed minutes (default 5), badge "Assumed — opened in its own tab" |
Usage bands come from reported and measured minutes only: a guess never colours a day. At day zoom a day's cell takes its best tier, and its hover lists the minutes of each.
*Changed deliberately 2026-10-22.* The parent timeline used to leave assumed time off and draw a single "opened" mark instead (a launch proves one click). With apps now opening inside EduSpaze where they can, parents and schools see the same three tiers, and an assumed block is drawn as unmistakably assumed rather than hidden. An app opened before launch sessions existed — a launch event with no session — still shows the single mark.
6. Configuration (per school, School Settings → Engagement measurement)
| Setting | Default | Range | Effect |
|---|---|---|---|
engagementInactivityMinutes | 10 | 1–120 | gap that closes a session and the continuation window for repeat sign-ins |
launchOnlyMinutes | 5 (was 2 until 2026-10-22; schools on 2 moved with it) | 0–30 | assumed time for an open with no further signal — an app in its own tab; 0 counts nothing |
heartbeatIntervalSeconds | 60 | 15–300 | client ping cadence and the presumed-presence horizon after the last ping |
These are measurement parameters, so they carry stated defaults that the school can change. The usage bands on the parent timeline are a judgement about a child and still never default (see parent-access/discovery.md).
7. Where each audience sees it
- Pupil: the launcher and app frame explain in plain words that time is counted, never content, alongside the existing Children's Code notice.
- Parent: on the Timeline tab, first a table of usage by app. It has a row for each connected app. Over the last 30 days, or the school's timeline retention if shorter, it shows minutes, idle minutes, sessions, opens, how the time is known, and when the app was last active. These are the same figures the school sees on the pupil's Engagement page (
appUsageinlib/parent/data.ts; added 2026-10-23). Below the table is the timeline heat map: merged intervals in the three tiers of §5, with bands from the day's reported and measured minutes. - School (teacher and above): School → Engagement — minutes, idle minutes, sessions, opens, confidence and last-active per pupil per app over 7 or 30 days, filterable by class; a Staff tab with the same for staff, in apps opened inside EduSpaze (§9).
- School admin — the activity dashboard (2026-10-23): part of the school's Dashboard section (
components/school/dashboard-section.tsx). Its first page, Overview (/school), holds the recommendations, credits, trials and pipeline. The usage pages sit under/school/activity. The sidebar has one *Dashboard* entry for the whole section. It needs theschool.activitymodule (VIEW). Only school admins hold it by default, because it names people and shows who is online. It is part of the *Engagement* plan feature. It has three pages (lib/school/activity.ts), each filtered to pupils, staff or both: - Usage over time, for a period: today, the last 7, 30 or 90 days, or a custom range of up to a year.
- How many people were on EduSpaze, and how many used an app.
- Time in apps, with sessions and opens.
- Time on EduSpaze itself: the launcher, and the school portal outside apps.
- A bar for each day.
- Every app the school has switched on, with pupils, staff, time, sessions, opens and when it was last used. Unused apps are listed too, and marked.
- Live now refreshes every 15 seconds while the page is in view.
- Shows who has been heard from within two heartbeats (at least 90 seconds).
- For each person it shows where they are: the launcher or EduSpaze, and any app. Each place is marked *active*, *idle* (open in the background) or *opened in its own tab*. An app opened in its own tab cannot report back, so it is shown for the school's assumed minutes.
- It also lists the apps in use now, with how many pupils and staff are in each.
- Busiest times is a heatmap of minutes in apps by day of the week (Monday first) and hour of the day.
- It is drawn in the reader's own time zone, and each session is split into quarter hours so its time lands where it fell.
- Each square shows its minutes and how many people.
- The three busiest hours are called out above the map, with day totals beside it and hour totals beneath.
- It can be filtered to one or more apps.
Overlapping signals for one person in one place count once (mergeIntervals), as on the Engagement pages. Vendor reports are matched to pupils by their pseudonymous id.
When one child uses apps (2026-10-23). The same week heatmap (components/engagement/week-heatmap.tsx, pupilWeekPattern) also appears for a single pupil, in two places:
- A pupil's Engagement page in the school portal, above the dated timeline.
- The parent's Timeline, under the usage-by-app table.
It answers "when does this child use their apps, and which one?": school hours, evenings and weekends at a glance, over 7, 30 or 90 days, for all apps or one (chips with each app's minutes). The busiest hours are given in a sentence. Each square shows minutes, not people, because there is only one person. A parent sees only the child's connected apps, and never further back than the school's timeline retention (weekPattern in lib/parent/data.ts, behind the gates). The dated timeline stays for "what happened on which day".
Staff on EduSpaze. The school portal sends the same time-only heartbeat as the launcher, with no app, so a member of staff on its pages counts as *on EduSpaze* (a StaffEngagementSession with no vendorId).
- It records time only, never which page.
- It is not sent during an EduSpaze support session.
- Staff app reports (
staffEngagementSummary) count only sessions with an app, so this never inflates them. - The pupil launcher's heartbeat now runs on every launcher page (the layout), not only the home page.
- Vendor: Startup → Integration & API — telemetry health (last seen, sessions reported, heartbeat sessions) and the endpoint reference.
- EduSpaze — the platform dashboard (2026-10-25): Admin → Dashboard is a section like the school's (
components/admin/dashboard-section.tsx): Overview (/admin, the business counters) first, then three usage pages under/admin/activitythat read the same sessions across every school (lib/admin/platform-usage.ts). They needplatform.usage(VIEW), held by the owner, operations, support and analyst. Schools and apps, never people: every figure is a count or a sum per school or per app; no page names a pupil or a member of staff, and the library never reads a name. Their own pages, not the school's, so they can grow apart; the pure arithmetic (periods, quarter-hour slots, the week heatmap) is shared fromlib/school/activity.ts. - Usage over time, for a period and pupils, staff or both: schools active (of all schools), people on EduSpaze, apps used (of those switched on anywhere), time in apps with sessions and opens, time on EduSpaze itself, a bar a day (time in apps, labelled with schools active), every school — active or not, so a school gone quiet stands out — with pupils, staff, apps used, time in apps, time on EduSpaze and last active, and every app switched on anywhere with the schools using it, pupils, staff, time, sessions, opens and last used.
- Live now, refreshed every 15 seconds: people online, schools online, people in an app, apps in use; then each school online with its pupils, staff, how many are in an app and which apps, and each app in use with its schools, pupils and staff. The horizon is two heartbeats at the platform default, widened to the slowest school that set its own.
- Busiest times: the week heatmap across every school, filterable to chosen schools and apps.
8. Retention and audit
StudentActivityPingandStaffActivityPingare kept 30 days (trimActivityPings);EngagementSession,StaffEngagementSessionandVendorSessionReportare the record and follow the tenant's timeline retention.- Nightly housekeeping (
lib/engagement/housekeeping.ts, BL-10): the hourly scheduler job (/api/internal/nudges) runs it once a night, at 02:00 Singapore time — it trims raw pings and marks sessions past the school's inactivity cutoff as closed (closedAt). Reads already treat those as closed, so no number changes. Idempotent; a missed night is caught up by the next. The run is a domain event (engagement.housekeeping, with counts). - The telemetry tables — pupils' and staff's — are excluded from the audit capture trigger (they are machine-generated, high volume and content-free); the exception is recorded in
guardrails.md. Everything a person changes about the measurement — settings, API keys, launch URLs, secrets — is a domain event on the audit trail.
9. Active, idle and stopped (added 2026-10-22)
Surfaces EduSpaze owns — the launcher, an app opened inside EduSpaze (/app/access, docs/integration/app-access.md) and the in-platform app page — report presence, not just "still here" (components/engagement/heartbeat.tsx):
| State | When | What the page sends |
|---|---|---|
| Active | the tab is visible and the browser window focused (document.hasFocus() on the top page is true while focus is anywhere in it, an app's frame included) | a ping every interval, state: "active" |
| Idle | still open, but the tab hidden or the window unfocused | a ping at once on the change, then every interval, state: "idle"; none after the school's inactivity cutoff of continuous idle |
| Stopped | the page is left or closed (pagehide) | an END beacon |
Every ping carries activeMs and idleMs, the time spent in each since the last ping, so the server never guesses. The server checks them against its own clock — never more than has passed since the session last heard from this person, plus 2 seconds (clampPresence) — so a second tab, a retry or an edited body cannot add time. Rules added to §3 (each a test in tests/app-access.test.ts):
- Idle is not use. An idle ping adds
idleSecondsand leaves the session's interval alone; time reported active before it ends the interval exactly then, not a heartbeat later. - Coming back inside the cutoff is the same session, active again; after the cutoff, a new one.
- Stopped after idle ends the interval where use stopped, not when the tab was closed.
- Idle alone never opens a session.
- A ping that reports time is never dropped as a duplicate (rule 6); its time is clamped instead.
Sessions keep activeSeconds, idleSeconds, lastPingAt and lastState. Minutes everywhere are still the merged intervals (§4) — active time — with idle minutes shown beside them.
Staff are measured the same way, by the same sessioniser, in StaffActivityPing and StaffEngagementSession, keyed by their pseudonymous staff subject: a staff launch starts a session, and the heartbeat accepts a member of staff only for an app the school has opened to teachers (never an EduSpaze support session). Pupil reporting and the parent timeline never read these tables.
10. Open items
- Rate limiting on the vendor API (per key) before general availability.
- Identity-provider back-channel logout as an additional
ENDsignal for SSO tenants. - ~~A nightly job that closes sessions older than the cutoff explicitly~~ — done 2026-10-05, §8.
